问:
Fill 2D array square and print in specific patterns
Ive been working on this assignment question for about 4 days now and I'm about to go crazy. We have specific directions to follow for this code;

"Your program should proceed as follows:

Display a welcome message.

Prompt the user for an integer which is  3. If the number entered is < 3. keep prompting the user until they enter a number  3 (use a do/while).    This number will determine the size of the square array.

Fill the array as per pattern 1 and display it using printf to format the array.

Fill the same array as per pattern 2 and display it using printf t0 format the array.

Display a closing message."

Pattern:

I'm still stuck on pattern one. I tried to do first do a for loop which in it there's an if statement that checks if the column number is even or not, if it is, to print out the code backwards. The question also recommends using a while loop and a do/while loop...?

Also any tips on to how to go about the second patterns.

Here is my code.

```<code>import java.util.Scanner;
public class a3q33
{

  public static void main(String[] args)
  {
    Scanner keyboard = new Scanner(System.in);

    int n;

    do
    {
        System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");

        n=keyboard.nextInt();

    } while(n < 3);

    int [][] arr = new int [n][n];

     int i, j, k=1;

    for(i=0;i<n;i++)
    {
         if(i % 2 != 0)
         {
             for(j=n;j>0;j--)
             {
                 k = k+n;
                 arr[i][j]=k;
                 k--;
             }
         }

         else
         {
             for(j=0;j<n;j++)
             {
                 arr[i][j]=k;
                 k++;
             }
         }
    }

    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            System.out.printf(arr[i][j]+" ");

        }
            System.out.printf("");
            System.out.println();
    }

    }
}
</code>```

Any help would be greatly appreciated!

答:
You can achieve this by checking the modulo:</p>

```<code>for (int i = 0; i < n; i++) {
    int start = i * n;
    for (int j = 0; j < n; j++) {
        arr[i][j] = i * n + ((i % 2 === 0) ? (j + 1) : (n - j));
    }
}
</code>```

Body:
Ive been working on this assignment question for about 4 days now and I'm about to go crazy. We have specific directions to follow for this code;

"Your program should proceed as follows:

Display a welcome message.

Prompt the user for an integer which is  3. If the number entered is < 3. keep prompting the user until they enter a number  3 (use a do/while).    This number will determine the size of the square array.

Fill the array as per pattern 1 and display it using printf to format the array.

Fill the same array as per pattern 2 and display it using printf t0 format the array.

Display a closing message."

Pattern:

I'm still stuck on pattern one. I tried to do first do a for loop which in it there's an if statement that checks if the column number is even or not, if it is, to print out the code backwards. The question also recommends using a while loop and a do/while loop...?

Also any tips on to how to go about the second patterns.

Here is my code.

import java.util.Scanner;
public class a3q33
{

  public static void main(String[] args)
  {
    Scanner keyboard = new Scanner(System.in);

    int n;

    do
    {
        System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");

        n=keyboard.nextInt();

    } while(n < 3);

    int [][] arr = new int [n][n];

     int i, j, k=1;

    for(i=0;i<n;i++)
    {
         if(i % 2 != 0)
         {
             for(j=n;j>0;j--)
             {
                 k = k+n;
                 arr[i][j]=k;
                 k--;
             }
         }

         else
         {
             for(j=0;j<n;j++)
             {
                 arr[i][j]=k;
                 k++;
             }
         }
    }

    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            System.out.printf(arr[i][j]+" ");

        }
            System.out.printf("");
            System.out.println();
    }

    }
}

Any help would be greatly appreciated!

Body:
You can achieve this by checking the modulo:

for (int i = 0; i < n; i++) {
    int start = i * n;
    for (int j = 0; j < n; j++) {
        arr[i][j] = i * n + ((i % 2 === 0) ? (j + 1) : (n - j));
    }
}


来源: stackexchange

问:
how to assign defined radio button layout to dynamic radio button
I have defined xml for radio button in activity_main.xml. In main activity i am trying to add radio buttons to radio group dynamically.
facing this error

The specified child already has a parent. You must call removeView() on the child's parent first

```<code>RadioGroup answerOptions = (RadioGroup) findViewById(R.id.answers_options);

    for (int i = 0; i < answersList.size() ; i++) {
        RadioButton radioButton = new RadioButton(MainActivity.this);
        radioButton = (RadioButton) findViewById(R.id.simpleRadioButton);
        radioButton.setText(answersList.get(i).getOption_description());
        answerOptions.addView(radioButton,i);
    }
</code>```

some part of main_activity.xml

```<code>    <RadioGroup

        android:id="@+id/answers_options"
        android:orientation="vertical"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:layout_weight="1">

        <RadioButton
            android:textSize="22sp"
            android:id="@+id/simpleRadioButton"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="0.20"
            android:text=""
            android:layout_gravity="left" />

    </RadioGroup>
</code>```

答:
That's because you are getting a reference to the same RadioButton that is defined in your xml.

Try doing:

```<code>for (int i = 0; i < answersList.size() ; i++) {
    RadioButton radioButton = new RadioButton(MainActivity.this);
    radioButton.setText(answersList.get(i).getOption_description());
    answerOptions.addView(radioButton,i);
}
</code>```

To set the same properties defined in xml you could do it programmatically or create a new layout and inflate it.

ContentLicense: CC BY-SA 3.0

Body:
I have defined xml for radio button in activity_main.xml. In main activity i am trying to add radio buttons to radio group dynamically.
facing this error

The specified child already has a parent. You must call removeView() on the child's parent first

RadioGroup answerOptions = (RadioGroup) findViewById(R.id.answers_options);

    for (int i = 0; i < answersList.size() ; i++) {
        RadioButton radioButton = new RadioButton(MainActivity.this);
        radioButton = (RadioButton) findViewById(R.id.simpleRadioButton);
        radioButton.setText(answersList.get(i).getOption_description());
        answerOptions.addView(radioButton,i);
    }

some part of main_activity.xml

    <RadioGroup

        android:id="@+id/answers_options"
        android:orientation="vertical"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:layout_weight="1">

        <RadioButton
            android:textSize="22sp"
            android:id="@+id/simpleRadioButton"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="0.20"
            android:text=""
            android:layout_gravity="left" />

    </RadioGroup>

Body:
That's because you are getting a reference to the same RadioButton that is defined in your xml.

Try doing:

for (int i = 0; i < answersList.size() ; i++) {
    RadioButton radioButton = new RadioButton(MainActivity.this);
    radioButton.setText(answersList.get(i).getOption_description());
    answerOptions.addView(radioButton,i);
}

To set the same properties defined in xml you could do it programmatically or create a new layout and inflate it.


问:
How to display SQL Server database image base64 in Aspose Word Document
I am new in Aspose and I have the following issue:

I have images in a SQL Server 2008 database, stored as a Base64 strings. I would like to display them in a Word document using Aspose.

I have successfully exported the other data, but can't display the images. Can anyone help me please?

Thanks in advance for your support.

Here is my code:

```<code>private Document createDocs(Guid ? ID)
{
    Document doc = new Document(HostingEnvironment.MapPath("~/Content/Template.doc"));
    DataTable Order = ExecuteDataTable(inspID);

    if (!(Order == null))
    {
        doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();
        doc.MailMerge.ExecuteWithRegions(Order);
    }

    return doc;
}

public DataTable ExecuteDataTable(Guid? ID)
{
    var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyStringConnection"];

    SqlConnection Conn = new SqlConnection(connectionString.ConnectionString);

    try
    {
        Conn.Open();

        SqlCommand cmd = new SqlCommand("SELECT * FROM blahblah, Conn);
        cmd.Parameters.Add("@ID", SqlDbType.UniqueIdentifier).Value = ID;

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.SelectCommand = cmd;

        DataTable table = new DataTable();
        da.Fill(table);

        return table;
    }
    finally
    {
        if (!(Conn == null))
        {
            Conn.Close();
        }
    }
}

private void SendToBrowser (Document doc, string outputFormat, Page page)
{
    MemoryStream stream = new MemoryStream();
    doc.Save(stream, SaveFormat.Doc);

    page.Response.Clear();
    page.Response.ClearHeaders();
    page.Response.ClearContent();
    page.Response.ContentType = "application/doc";
    page.Response.AddHeader("content-disposition", "attachment; filename=base_file.doc");

    byte[] bytes = stream.GetBuffer();

    page.Response.BinaryWrite(bytes);
    page.Response.End();
}

public class HandleMergeImageFieldFromBlob : IFieldMergingCallback
{
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // Do nothing.
    }

    /// <summary>
    /// This is called when mail merge engine encounters Image:XXX merge field in the document.
    /// You have a chance to return an Image object, file name or a stream that contains the image.
    /// </summary>
    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // The field value is a byte array, just cast it and create a stream on it.
        var imageStream = new MemoryStream((byte[])e.FieldValue);

        // Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream;
    }
}
</code>```

答:
To insert an image mail merge field into a document in Word, select Insert/Field command, then select MergeField and type Image:MyFieldName. Following code example shows how perform mail merge operation with Base64 image. Please check the modified code of IFieldMergingCallback.ImageFieldMerging.

```<code>public void mailmerge()
{
    string base64String;
    using (Image image = Image.FromFile(MyDir + @"image.png"))
    {
        using (MemoryStream m = new MemoryStream())
        {
            image.Save(m, image.RawFormat);
            byte[] imageBytes = m.ToArray();

            // Convert byte[] to Base64 String
            base64String = Convert.ToBase64String(imageBytes);
        }
    }

    DataTable dt = new DataTable();
    dt.Columns.Add("ImageData", typeof(string));

    DataRow row1 = dt.NewRow();
    row1["ImageData"] = base64String;
    dt.Rows.Add(row1);

    Document doc = new Document(MyDir + "in.docx");
    doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();
    doc.MailMerge.Execute(dt);
    doc.Save(MyDir + "Out.docx");
}

public class HandleMergeImageFieldFromBlob : IFieldMergingCallback
{
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // Do nothing.
    }

    /// <summary>
    /// This is called when mail merge engine encounters Image:XXX merge field in the document.
    /// You have a chance to return an Image object, file name or a stream that contains the image.
    /// </summary>
    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        var imageStream = new MemoryStream((byte[])Convert.FromBase64String(e.FieldValue.ToString()));

        // Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream;
    }
}
</code>```

I work with Aspose as Developer evangelist.

Body:
I am new in Aspose and I have the following issue:

I have images in a SQL Server 2008 database, stored as a Base64 strings. I would like to display them in a Word document using Aspose.

I have successfully exported the other data, but can't display the images. Can anyone help me please?

Thanks in advance for your support.

Here is my code:

private Document createDocs(Guid ? ID)
{
    Document doc = new Document(HostingEnvironment.MapPath("~/Content/Template.doc"));
    DataTable Order = ExecuteDataTable(inspID);

    if (!(Order == null))
    {
        doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();
        doc.MailMerge.ExecuteWithRegions(Order);
    }

    return doc;
}

public DataTable ExecuteDataTable(Guid? ID)
{
    var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyStringConnection"];

    SqlConnection Conn = new SqlConnection(connectionString.ConnectionString);

    try
    {
        Conn.Open();

        SqlCommand cmd = new SqlCommand("SELECT * FROM blahblah, Conn);
        cmd.Parameters.Add("@ID", SqlDbType.UniqueIdentifier).Value = ID;

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.SelectCommand = cmd;

        DataTable table = new DataTable();
        da.Fill(table);

        return table;
    }
    finally
    {
        if (!(Conn == null))
        {
            Conn.Close();
        }
    }
}

private void SendToBrowser (Document doc, string outputFormat, Page page)
{
    MemoryStream stream = new MemoryStream();
    doc.Save(stream, SaveFormat.Doc);

    page.Response.Clear();
    page.Response.ClearHeaders();
    page.Response.ClearContent();
    page.Response.ContentType = "application/doc";
    page.Response.AddHeader("content-disposition", "attachment; filename=base_file.doc");

    byte[] bytes = stream.GetBuffer();

    page.Response.BinaryWrite(bytes);
    page.Response.End();
}

public class HandleMergeImageFieldFromBlob : IFieldMergingCallback
{
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // Do nothing.
    }

    ///
    /// This is called when mail merge engine encounters Image:XXX merge field in the document.
    /// You have a chance to return an Image object, file name or a stream that contains the image.
    ///
    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // The field value is a byte array, just cast it and create a stream on it.
        var imageStream = new MemoryStream((byte[])e.FieldValue);

        // Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream;
    }
}

Body:
To insert an image mail merge field into a document in Word, select Insert/Field command, then select MergeField and type Image:MyFieldName. Following code example shows how perform mail merge operation with Base64 image. Please check the modified code of IFieldMergingCallback.ImageFieldMerging.

public void mailmerge()
{
    string base64String;
    using (Image image = Image.FromFile(MyDir + @"image.png"))
    {
        using (MemoryStream m = new MemoryStream())
        {
            image.Save(m, image.RawFormat);
            byte[] imageBytes = m.ToArray();

            // Convert byte[] to Base64 String
            base64String = Convert.ToBase64String(imageBytes);
        }
    }

    DataTable dt = new DataTable();
    dt.Columns.Add("ImageData", typeof(string));

    DataRow row1 = dt.NewRow();
    row1["ImageData"] = base64String;
    dt.Rows.Add(row1);

    Document doc = new Document(MyDir + "in.docx");
    doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();
    doc.MailMerge.Execute(dt);
    doc.Save(MyDir + "Out.docx");
}

public class HandleMergeImageFieldFromBlob : IFieldMergingCallback
{
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // Do nothing.
    }

    /// <summary>
    /// This is called when mail merge engine encounters Image:XXX merge field in the document.
    /// You have a chance to return an Image object, file name or a stream that contains the image.
    /// </summary>
    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        var imageStream = new MemoryStream((byte[])Convert.FromBase64String(e.FieldValue.ToString()));

        // Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream;
    }
}

I work with Aspose as Developer evangelist.


问:
Any faster, simpler alternative to php preg_match
I am using cakephp 1.3 and I have textarea where users submit articles. On submit, I want to look into the article for certain key words and and add respective tags to the article.

I was thinking of preg_match, But preg_match pattern has to be string. So I would have to loop through an array(big).

Is there a easier way to plug in the keywords array for the pattern.

I appreciate all your help.

Thanks.

答:
strtr()

If given two arguments, the second
  should be an array in the form
  array('from' => 'to', ...). The return
  value is a string where all the
  occurrences of the array keys have
  been replaced by the corresponding
  values. The longest keys will be tried
  first. Once a substring has been
  replaced, its new value will not be
  searched again.

ContentLicense: CC BY-SA 2.5


问:
How to make sure my while loop does not break my condition?
I'm practicing a simple while loop. Buy a phone for the cost of 200 only until my bank account hits 500, but because it buys the phone first it only knows you dropped below 500 after it buys the phone.

In my code, it's buying until it takes the bankaccountmoney variable to 400:

var bankaccountmoney = 2000;
var phonesbought = 0;
var phonecost = 200;

while (bankaccountmoney > 500) {
  phonesbought = phonesbought + 1;
  bankaccountmoney = bankaccountmoney - phonecost;
  console.log("money: " + bankaccountmoney + " phonesbought: " + phonesbought);
}```

答:
Another approach, using a couple of utility functions. I don't like doing math in while predicates. Way too easy to misread.

const phoneCost = 200;
const targetSavings = 500;

// Can I afford to buy something, given target savings, purchase price,
// and current funds?
const canAffordPurchase = target => purchase => funds =>
       (funds - purchase >= target);

// Can I afford to buy this phone in particular?
const canAffordPhone = canAffordPurchase(targetSavings)(phoneCost);

let availableFunds = 2000;
let phonesBought = 0;

// Buy as many phones as I can afford.
while(canAffordPhone(availableFunds)) {
  phonesBought += 1;
  availableFunds -= phoneCost;
  console.log(`money: ` + availableFunds + " phonesBought: " + phonesBought);
}```


问:
Recycler View Adapter Manages List incorrectly
Upon deletion of item from database, recycler view changes order of data after a one or two times of deleting and adding data to the list ,Deletion operation stop working or the Data in the list changes itself..

Activity which has the view and deletes from it

```<code>String[] items;
DbHandler db = new DbHandler(getApplicationContext());
    items = db.get_item();
    db.close();
     listRecyclerView = (RecyclerView) findViewById(R.id.main_recycler_view);

    scheduleAdapter = new ScheduleAdapter(getApplicationContext());
    if (listRecyclerView != null)
        listRecyclerView.setAdapter(scheduleAdapter);

    listRecyclerView.setLayoutManager(new      WrapContentLinearLayoutManager(getApplicationContext()));
    listRecyclerView.stopScroll();
listRecyclerView.addOnItemTouchListener(new   RItemClickListener(getApplicationContext(), listRecyclerView, new  RItemClickListener.OnItemClickListener() {
     @Override
    public void onItemClick(View view, int position) {

    }

    @Override
    public void onLongItemClick(View view,final int position) {
        new AlertDialog.Builder(MySchedule.this)
                .setIcon(android.R.drawable.alert_dark_frame)
                .setTitle("Are you sure?")
                .setMessage("Do you want to delete this note?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        DbHandler db = new DbHandler(getApplicationContext());
                        db.delete_item(items[1]);
                        db.close();

scheduleAdapter.notifyDataSetChanged();
                    }
                })
                .setNegativeButton("No",null)
                .show();

    }
}));

}
  @Override
    protected void onResume(){
    listRecyclerView.stopScroll();
    super.onResume();
    scheduleAdapter.notifyDataSetChanged();
}
</code>```

My adapter class

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

public int Type_Text = 1;
Context r_context;
int pos = 1;

public ScheduleAdapter (Context context){
    r_context=context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v; ViewHolder vItem = null;

    if (viewType==Type_Text){
        v= LayoutInflater.from(parent.getContext()).inflate(R.layout.typeview1,parent,false);
        vItem = new ViewHolder(v,viewType,parent.getContext());
    }

    return vItem;
}

@Override
public void onBindViewHolder(final ViewHolder holder,final int position) {
    String[] Text_name;

    holder.setIsRecyclable(false);
    setAnimation(holder.container);

    pos = position;

    if(holder.HolderId==1){
        DbHandler db = new DbHandler(r_context);
        Text_name = db.get_item();
        holder.Text.setText(Text_name[position]);
        db.close();
    }
}

@Override
public int getItemCount() {
    DbHandler db = new DbHandler(r_context);
    int note_count = db.get_count();
    db.close();
    return note_count;
}

public int getPosition (){
    return pos;
}

@Override
public int getItemViewType (int position){
    return Type_Text;
}

private void setAnimation (View view){

    Animation animation = AnimationUtils.loadAnimation(r_context, android.R.anim.slide_in_left);
    view.startAnimation(animation);
}

// ViewHolder Class
public class ViewHolder extends RecyclerView.ViewHolder {

    int HolderId; TextView Text;
    CardView container;

    public ViewHolder(View itemView, int View_Type, Context context) {
        super(itemView);

        container = (CardView) itemView.findViewById(R.id.type1_cardview);

        if (View_Type==Type_Text){
            Text = (TextView) itemView.findViewById(R.id.type1_text);
            HolderId = 1;
        }
</code>```

My Recycler view click listener class

```<code>public class RItemClickListener implements RecyclerView.OnItemTouchListener {

private OnItemClickListener mlistener;

public interface OnItemClickListener {

    public void onItemClick(View view, int position);

    public void onLongItemClick(View view, int position);
}

GestureDetector mgesturedetector;

public RItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
  mlistener = listener;
   mgesturedetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
       @Override
       public boolean onSingleTapUp(MotionEvent e) {
          return true;
        }

      @Override
      public void onLongPress(MotionEvent e) {
           View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
           if (child != null && mlistener != null) {
               mlistener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
           }
        }
    });

 }

@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
     View childView = rv.findChildViewUnder(e.getX(), e.getY());
     if (childView != null && mlistener != null && mgesturedetector.onTouchEvent(e)) {
        mlistener.onItemClick(childView, rv.getChildAdapterPosition(childView));
        return true;
    }
    return false;
}

@Override
 public void onTouchEvent(RecyclerView rv, MotionEvent e) {}

@Override
 public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { }
}
</code>```

Somebody on stack overflow mentioned to implement this class to change the error this also didnt work

```<code> public class WrapContentLinearLayoutManager extends LinearLayoutManager {
 public WrapContentLinearLayoutManager(Context context) {
    super(context);
}

//... constructor
@Override
      public void onLayoutChildren(RecyclerView.Recycler recycler,  RecyclerView.State state) {
    try {
        super.onLayoutChildren(recycler, state);
    } catch (IndexOutOfBoundsException e) {
        Log.e("Error", "IndexOutOfBoundsException in RecyclerView happens");
    }
}
</code>```

Kindly help! ...Thanks !

答:
```<code>scheduleAdapter.notifyItemRangeChanged(position,items.length);
                        Intent intent = getIntent();
                        finish();
                        startActivity(intent);
</code>```

Adding these lines after                         scheduleAdapter.notifyItemRemoved(position)
worked :)

Body:
Upon deletion of item from database, recycler view changes order of data after a one or two times of deleting and adding data to the list ,Deletion operation stop working or the Data in the list changes itself..

Activity which has the view and deletes from it

String[] items;
DbHandler db = new DbHandler(getApplicationContext());
    items = db.get_item();
    db.close();
     listRecyclerView = (RecyclerView) findViewById(R.id.main_recycler_view);

    scheduleAdapter = new ScheduleAdapter(getApplicationContext());
    if (listRecyclerView != null)
        listRecyclerView.setAdapter(scheduleAdapter);

    listRecyclerView.setLayoutManager(new      WrapContentLinearLayoutManager(getApplicationContext()));
    listRecyclerView.stopScroll();
listRecyclerView.addOnItemTouchListener(new   RItemClickListener(getApplicationContext(), listRecyclerView, new  RItemClickListener.OnItemClickListener() {
     @Override
    public void onItemClick(View view, int position) {

    }

    @Override
    public void onLongItemClick(View view,final int position) {
        new AlertDialog.Builder(MySchedule.this)
                .setIcon(android.R.drawable.alert_dark_frame)
                .setTitle("Are you sure?")
                .setMessage("Do you want to delete this note?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        DbHandler db = new DbHandler(getApplicationContext());
                        db.delete_item(items[1]);
                        db.close();

scheduleAdapter.notifyDataSetChanged();
                    }
                })
                .setNegativeButton("No",null)
                .show();

    }
}));

}
  @Override
    protected void onResume(){
    listRecyclerView.stopScroll();
    super.onResume();
    scheduleAdapter.notifyDataSetChanged();
}

My adapter class

public class ScheduleAdapter extends RecyclerView.Adapter<ScheduleAdapter.ViewHolder> {

public int Type_Text = 1;
Context r_context;
int pos = 1;

public ScheduleAdapter (Context context){
    r_context=context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v; ViewHolder vItem = null;

    if (viewType==Type_Text){
        v= LayoutInflater.from(parent.getContext()).inflate(R.layout.typeview1,parent,false);
        vItem = new ViewHolder(v,viewType,parent.getContext());
    }

    return vItem;
}

@Override
public void onBindViewHolder(final ViewHolder holder,final int position) {
    String[] Text_name;

    holder.setIsRecyclable(false);
    setAnimation(holder.container);

    pos = position;

    if(holder.HolderId==1){
        DbHandler db = new DbHandler(r_context);
        Text_name = db.get_item();
        holder.Text.setText(Text_name[position]);
        db.close();
    }
}

@Override
public int getItemCount() {
    DbHandler db = new DbHandler(r_context);
    int note_count = db.get_count();
    db.close();
    return note_count;
}

public int getPosition (){
    return pos;
}

@Override
public int getItemViewType (int position){
    return Type_Text;
}

private void setAnimation (View view){

    Animation animation = AnimationUtils.loadAnimation(r_context, android.R.anim.slide_in_left);
    view.startAnimation(animation);
}

// ViewHolder Class
public class ViewHolder extends RecyclerView.ViewHolder {

    int HolderId; TextView Text;
    CardView container;

    public ViewHolder(View itemView, int View_Type, Context context) {
        super(itemView);

        container = (CardView) itemView.findViewById(R.id.type1_cardview);

        if (View_Type==Type_Text){
            Text = (TextView) itemView.findViewById(R.id.type1_text);
            HolderId = 1;
        }

My Recycler view click listener class

public class RItemClickListener implements RecyclerView.OnItemTouchListener {

private OnItemClickListener mlistener;

public interface OnItemClickListener {

    public void onItemClick(View view, int position);

    public void onLongItemClick(View view, int position);
}

GestureDetector mgesturedetector;

public RItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
  mlistener = listener;
   mgesturedetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
       @Override
       public boolean onSingleTapUp(MotionEvent e) {
          return true;
        }

      @Override
      public void onLongPress(MotionEvent e) {
           View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
           if (child != null && mlistener != null) {
               mlistener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
           }
        }
    });

 }

@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
     View childView = rv.findChildViewUnder(e.getX(), e.getY());
     if (childView != null && mlistener != null && mgesturedetector.onTouchEvent(e)) {
        mlistener.onItemClick(childView, rv.getChildAdapterPosition(childView));
        return true;
    }
    return false;
}

@Override
 public void onTouchEvent(RecyclerView rv, MotionEvent e) {}

@Override
 public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { }
}

Somebody on stack overflow mentioned to implement this class to change the error this also didnt work

 public class WrapContentLinearLayoutManager extends LinearLayoutManager {
 public WrapContentLinearLayoutManager(Context context) {
    super(context);
}

//... constructor
@Override
      public void onLayoutChildren(RecyclerView.Recycler recycler,  RecyclerView.State state) {
    try {
        super.onLayoutChildren(recycler, state);
    } catch (IndexOutOfBoundsException e) {
        Log.e("Error", "IndexOutOfBoundsException in RecyclerView happens");
    }
}

Kindly help! ...Thanks !

Body:
scheduleAdapter.notifyItemRangeChanged(position,items.length);
                        Intent intent = getIntent();
                        finish();
                        startActivity(intent);

Adding these lines after                         scheduleAdapter.notifyItemRemoved(position)
worked :)


问:
Implementing array element assembly
I am trying to code this in assembly language x86, but for some reason my program crashes. Here is the assignment.
Write an assembly language function that will receive a list (array) of 10 16-bit values and a
number, N, between 1-10, input by the user. The AL function should move the Nth value to the front of the list in
the following way:
Push all values from element 1 to element N-1 on the stack. Relocate the value at element N to element 1.
Pop the stack and restore its elements into locations N, N-1, … , 2

Here is my code

```<code>    void __declspec (naked) asmSwitch(short[], int)
    {
        __asm
        {
                    push    ebp
                    push    eax
                    push    ebx
                    push    ecx
                    push    edx
                    push    ebx
                    mov     ebp, esp
                    mov     ecx, [ebp + 12]         ; the element
                    dec     ecx                     ;
                    mov     ebx, [ebp + 8]          ; est ptr to array
            TOP:    push    [ebx]               ;
                    inc     ebx                     ;
                    inc     ebx
                    loop    TOP
                    mov     ax, [ebx]
                    mov     ebx, [ebp + 8]
                    mov     [ebx], ax
                    mov     ecx, [ebp + 12]
                    dec     ecx
                    mov     eax, ecx
                    add     eax, eax
                    add     ebx, eax
            TOP1:   pop     [ebx]
                    dec     ebx
                    dec     ebx
                    loop    TOP1
                    pop     esi
                    pop     edx
                    pop     ecx
                    pop     ebx
                    pop     eax
                    pop     ebp
                    ret

        }
    }
</code>```

And I am getting read violation error on

```<code>    TOP:    push    [ebx]               ;
</code>```

And my program crashes after compiling.

答:
You need a proper EBP for [ebp + 12]and [ebp + 8]. So move its initialisation straight behind push    ebp:

```<code>...
push    ebp
mov     ebp, esp
...
</code>```

push [ebx] pushes a DWORD (32 bit) because the stack is normally 32-bit-wise organized. pop [ebx] pops a WORD (16 bit) because the assembler recognizes the 16-bit array. So, ret will get a totally wrong value from the stack. Synchronize the types:

```<code>...
push    WORD PTR [ebx]
...
pop     WORD PTR [ebx]
...
</code>```

Title: Implementing array element assembly

Body:
I am trying to code this in assembly language x86, but for some reason my program crashes. Here is the assignment.
Write an assembly language function that will receive a list (array) of 10 16-bit values and a
number, N, between 1-10, input by the user. The AL function should move the Nth value to the front of the list in
the following way:
Push all values from element 1 to element N-1 on the stack. Relocate the value at element N to element 1.
Pop the stack and restore its elements into locations N, N-1, … , 2

Here is my code

    void __declspec (naked) asmSwitch(short[], int)
    {
        __asm
        {
                    push    ebp
                    push    eax
                    push    ebx
                    push    ecx
                    push    edx
                    push    ebx
                    mov     ebp, esp
                    mov     ecx, [ebp + 12]         ; the element
                    dec     ecx                     ;
                    mov     ebx, [ebp + 8]          ; est ptr to array
            TOP:    push    [ebx]               ;
                    inc     ebx                     ;
                    inc     ebx
                    loop    TOP
                    mov     ax, [ebx]
                    mov     ebx, [ebp + 8]
                    mov     [ebx], ax
                    mov     ecx, [ebp + 12]
                    dec     ecx
                    mov     eax, ecx
                    add     eax, eax
                    add     ebx, eax
            TOP1:   pop     [ebx]
                    dec     ebx
                    dec     ebx
                    loop    TOP1
                    pop     esi
                    pop     edx
                    pop     ecx
                    pop     ebx
                    pop     eax
                    pop     ebp
                    ret

        }
    }

And I am getting read violation error on

    TOP:    push    [ebx]               ;

And my program crashes after compiling.

Body:
You need a proper EBP for [ebp + 12]and [ebp + 8]. So move its initialisation straight behind push    ebp:

...
push    ebp
mov     ebp, esp
...

push [ebx] pushes a DWORD (32 bit) because the stack is normally 32-bit-wise organized. pop [ebx] pops a WORD (16 bit) because the assembler recognizes the 16-bit array. So, ret will get a totally wrong value from the stack. Synchronize the types:

...
push    WORD PTR [ebx]
...
pop     WORD PTR [ebx]
...


问:
c# commandline no error line number
If there is an exception in .NET code and and PDB file is available you normally get the errors with source code line numbers shown in the exception message. This seems to be different in command line executables, where I do not get any line number although a PDB file is available:

Anwendung: MNX.CommandLine.EpkFtpEventhandler.exe Frameworkversion: v4.0.30319 Beschreibung: Der Prozess wurde aufgrund eines Ausnahmefehlers beendet. Ausnahmeinformationen: System.Data.SqlClient.SqlException Stapel: bei System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(System.String, Boolean, Int32, Boolean) bei System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(System.Threading.Tasks.TaskCompletionSource`1, System.String, Boolean, Int32, Boolean) bei System.Data.SqlClient.SqlCommand.ExecuteNonQuery() bei MNX.DB.WriteLocal(System.String) bei MNX.DB.Write(System.String) bei MNX.CommandLine.EpkFtpEventHandler.Main(System.String[])

Does anyone know why?

答: Exception.StackTrace gave back the line number, when it comes from a catch. Strangely only when I catch the exception, not when it's thrown without being catched.</p>

Title: c# commandline no error line number


问:
Clear all fields in Xamarin Forms
I have a form with about 25 fields and some dropdowns too, I want to have a clean button that resets all the form, is there an easy way to do this?</p>

答:
If your controls are bound to an object with two way binding you can iterate over the properties and clear the values using the code below.

```<code>    private async void btnClear_Clicked(object sender, EventArgs e)
    {
        MyData data = (MyData)this.BindingContext;
        await ClearProperties(data);
    }

    private async Task ClearProperties<T>(T instance)
    {
        await ClearProperties(typeof(T), instance);
    }

    private async Task ClearProperties(Type classType, object instance)
    {
        foreach (PropertyInfo property in classType.GetRuntimeProperties())
        {
            object value = null;
            try
            {
                value = property.GetValue(instance, null);
            }
            catch (Exception)
            {
                //Debug.WriteLine(ex.Message);
            }
            if (value != null && property.PropertyType != typeof(String))
                await ClearProperties(property.PropertyType, value);
            else if (value != null && (String)value != "")
                property.SetValue(instance, null);
        }
    }
</code>```

This loops through the properties and their properties and if it is a String and it is not empty it will set the value to null. If you are binding to something other than a String you may have to modify it a bit.

Title: Clear all fields in Xamarin Forms

Body:
If your controls are bound to an object with two way binding you can iterate over the properties and clear the values using the code below.

    private async void btnClear_Clicked(object sender, EventArgs e)
    {
        MyData data = (MyData)this.BindingContext;
        await ClearProperties(data);
    }

    private async Task ClearProperties<T>(T instance)
    {
        await ClearProperties(typeof(T), instance);
    }

    private async Task ClearProperties(Type classType, object instance)
    {
        foreach (PropertyInfo property in classType.GetRuntimeProperties())
        {
            object value = null;
            try
            {
                value = property.GetValue(instance, null);
            }
            catch (Exception)
            {
                //Debug.WriteLine(ex.Message);
            }
            if (value != null && property.PropertyType != typeof(String))
                await ClearProperties(property.PropertyType, value);
            else if (value != null && (String)value != "")
                property.SetValue(instance, null);
        }
    }

This loops through the properties and their properties and if it is a String and it is not empty it will set the value to null. If you are binding to something other than a String you may have to modify it a bit.


问:
IBM MobileFirst Platform 7.1 doesn't create android project from the hybrid app
I have an IBM MobileFirst Platform running on my eclipse and I have created a hello app with adding android environment to it. However, when I build the android environment, it just creates the native folder without creating the android project separately that I need to use to run using Android Studio. Is something wrong with my setup?

Jave Version:

```<code>Listening for transport dt_socket at address: 10777
Launching worklight (WebSphere Application Server 8.5.5.5/wlp-1.0.8.cl50520150305-2202) on Java HotSpot(TM) 64-Bit Server VM, version 1.8.0_121-b13 (en_US)
</code>```

IBM MobileFirst Platform Version:

```<code>7.1.0.00.20170301-1645
</code>```

Hello app project:

答: Right click on the android environment and select Run As -> Build Android Environment (This will create the Android project separately) or You can directly select Run As -> Android Studio Project and run the application using Android Studio (Make sure you have set the path to Android Studio installation in the preferences).

Body:
I have an IBM MobileFirst Platform running on my eclipse and I have created a hello app with adding android environment to it. However, when I build the android environment, it just creates the native folder without creating the android project separately that I need to use to run using Android Studio. Is something wrong with my setup?

Jave Version:

Listening for transport dt_socket at address: 10777
Launching worklight (WebSphere Application Server 8.5.5.5/wlp-1.0.8.cl50520150305-2202) on Java HotSpot(TM) 64-Bit Server VM, version 1.8.0_121-b13 (en_US)

IBM MobileFirst Platform Version:

7.1.0.00.20170301-1645

Hello app project:


问:
How do recommender systems and search engines work together?
When a user searches on a website like Tripadvisor, does the system filter the items with the user's input first and then the recommender system decides the order of the results?

In other words: is the output of the search engine the input of the recommender system?

Wouldn't this leave out some relevant items for the user because it doesn't consider her preferences? Also the diversity of the results may be affected.

In this question Better or Not combine Search Engine and Recommend System? they mention to use topic modeling. But I think this would represent a lot of changes to my system.

So, how do real recommender systems deal with this problem? Do they "relax" the search? Is it done before or after the search?

答:
A common approach to this problem is to use a hybrid recommender system, which consists of many approaches running simultaneously (usually on a distributed environment). The outputs of each approach is combined somehow, forming the final result. Some example of how this could be done are:

weighted - each approach gets a number of votes

cascade - one approach identifies candidates, another ranks

mixed - take n results from each system

There are many more. Also, context should be considered as an input, and the exact hybrid method (including parameters) learned either from historic data or online testing.


问:
How to set date created and date updated fields in JIRA using Python REST API?
I am using the JIRA Python REST API to create an issue in JIRA, but I don't know how to set the date created and date updated fields for an issue, as well as format the date to how JIRA wants it. My is code below:

jira.create_issue(project={'key': 'DEL'},
created='10/4/2012  9:30:00 AM',
updated='12/22/2012  10:00:00 AM',
priority={'name': 'Critical'},
summary='My summary',
description='My description',
issuetype={'name': 'Bug'})
```

<p>It gives me the annoying error that it doesn't even recognize the fields even though they exist (reference: http://jira-python.readthedocs.org/en/latest/index.html): </p>

```JIRAError: HTTP 400: "{u'updated': u"Field 'updated' cannot be set. It is not on the appropriate screen, or unknown.", u'created': u"Field 'created' cannot be set. It is not on the appropriate screen, or unknown."}"
```

答:
You can change the issue creation date with a CSV file import (even on existing issues):

Create a file with the following content:

```<code>issue key, date created, summary
TST-30002,30/11/13 22:00,
</code>```

The summary field is mandatory, but you can leave it empty to preserve the current summary text.

Go to "External System Import" in the JIRA Administration ( > System) or use the shortcut "." and search for "External System Import".

Choose "CSV".

Select the file above and check the correct encoding and delimiter , under "Advanced".

On next page, select the project where your existing issues reside and set the date format to dd/MM/yy HH:mm (valid Java SimpleDateFormat)

On next page, map the fields with the same name. E.g. issue key to Issue Key.

Start the import process on the next page.

Body:
I am using the JIRA Python REST API to create an issue in JIRA, but I don't know how to set the date created and date updated fields for an issue, as well as format the date to how JIRA wants it. My is code below:

jira.create_issue(project={'key': 'DEL'},
created='10/4/2012  9:30:00 AM',
updated='12/22/2012  10:00:00 AM',
priority={'name': 'Critical'},
summary='My summary',
description='My description',
issuetype={'name': 'Bug'})

It gives me the annoying error that it doesn't even recognize the fields even though they exist (reference: http://jira-python.readthedocs.org/en/latest/index.html):

JIRAError: HTTP 400: "{u'updated': u"Field 'updated' cannot be set. It is not on the appropriate screen, or unknown.", u'created': u"Field 'created' cannot be set. It is not on the appropriate screen, or unknown."}"

Body:
You can change the issue creation date with a CSV file import (even on existing issues):

Create a file with the following content:

issue key, date created, summary
TST-30002,30/11/13 22:00,

The summary field is mandatory, but you can leave it empty to preserve the current summary text.

Go to "External System Import" in the JIRA Administration ( > System) or use the shortcut "." and search for "External System Import".

Choose "CSV".

Select the file above and check the correct encoding and delimiter , under "Advanced".

On next page, select the project where your existing issues reside and set the date format to dd/MM/yy HH:mm (valid Java SimpleDateFormat)

On next page, map the fields with the same name. E.g. issue key to Issue Key.

Start the import process on the next page.


答:
If you don't need the power of regular expressions, you should just use strpos().

You will still need to loop through the array of words, but strpos is much, much faster than preg_match.

Title: Any faster, simpler alternative to php preg_match

Body:
I am using cakephp 1.3 and I have textarea where users submit articles. On submit, I want to look into the article for certain key words and and add respective tags to the article.

I was thinking of preg_match, But preg_match pattern has to be string. So I would have to loop through an array(big).

Is there a easier way to plug in the keywords array for the pattern.

I appreciate all your help.

Thanks.


问:
Analogue of vbCr (Carriage return) in Environment
I found vbCrLf has it's analogue (or copy) in Environment namespace in VB.net. As I understood there is no difference between them except vbCrLf is harder for reading when Environment.NewLine is clear.

But I can't find any comfortable analogue of vbCr in Environment. I checked all the methods but still can't find.

Is there any comfortable for reading analogue of vbCr in VB.net?

P.S. Why they create analogue for new line symbol but forget about this one?

答:
Why they create analogue for new line symbol but forget about this one?

They did not create an analogue for the new line symbol.

The Environment.NewLine is platform-dependent and will be different on different platforms. You use it e.g. when you want to generate human-readable text and therefore want the "whatever the newline symbol is, I don't care what it is exactly".

The vbCrLf is not platform-dependent, it's \r\n on all platforms. You use that when you are dealing with data contracts that specify there must be an \r\n (e.g. forming or reading HTTP headers, these are separated with \r\n).

They are not interchangeable and you are supposed to pick the one that is correct for the given purpose.

Personally I like how vbCrLf and vbCr look and have no problems with them. If you think otherwise, you can confuse future readers of your code by defining custom constants named the way you like.


问:
crashlyticsDidDetectCrashDuringPreviousExecution for crashlytics NDK
We are using crashlyticsDidDetectCrashDuringPreviousExecution to detect java crashes and report them to our BI systems, but our app is mostly C++ and we are using crashlytics NDK, we can't find anything similar to crashlyticsDidDetectCrashDuringPreviousExecution.

Is there any way that we can actually detect an NDK crash when the app starts?

thanks
Oded

答:
Mike from Fabric here.

Currently, there isn't a way to do this within Fabric or the SDK for an NDK crash.

ContentLicense: CC BY-SA 4.0


问:
Why is Excel temporarily locking us out of non-locked sheets/cells?
I am having trouble diagnosing this problem we in our office have begun to experience since... upgrading(???)... to Excel 2016.

We cannot recreate the issue on command; we are not sure what causes it. I am not even sure what to Google (list below)! We'll be working in a sheet, all is normal, moving from cell to cell or whatever... then at some point, moving from one typical cell to the next, suddenly, the sheet just... stops letting us use it. It just stops letting us make changes and acts strange.

Here are the symptoms:

Can edit some cells, but the changes will "vanish" when you leave the cell.

Can not click on all cells. The selector with just not highlight them.

Can not add or remove filters, or sort.

Can not Copy or Paste.

Can not delete any cells that can be highlighted.

This can happen to us on a variety of sheets and none of them have "protection" or sheet locking of any kind whatsoever. Zero, zilch, nada. These sheets are NOT "Locked for Editing". And I've looked at my co-workers keyboards to ensure that something silly like Num or Scroll lock wasn't causing the problem; they're not enabled.

One solution which I've found sometimes seems to fix the problem, is to switch sheets. That's it! Sheet1 not responding and treating you like you're locked out? Switch to Sheet2 (just click on it) then switch back to Sheet1. Fixed! Now the cells just... work again. The selector works again. Editing works again, just from switching from one sheet back to another. Well... sometimes.

Other times that does nothing, and then we have to save and reopen the sheet, and it works fine without any other changes. It is very confusing that, without even doing anything besides reopening it, that it works again.

These are a few examples of the stuff I've tried Googling over the last few weeks (I don't think I need to provide the complete list here... all searches have returned nothing useful, only articles talking about how to Lock and Unlock your sheet properly, which isn't this):

excel 2016 locks from editing

excel 2016 locks while working

excel 2016 locked for editing not locked

excel 2016 can't edit until switch sheets

答:
I believe this is a known problem in excel 2016, Especially if you have windows 10.  It looks like you need to keep resetting it like you have been doing but it is annoying.

If you try to disable "hardware graphics acceleration" in options menu, that should fix the issue and you would not have to keep switching between sheets.


问:
What's the difference between DomainKey-Signature & DKIM-Signature?
I'm trying to sign emails with DKIM using PHPMailer Class and i can't get it to work.

When i see the headers in my emails on gmail, i find that the class is successfully injecting DKIM in the email header but gmail doesn't even care.

The question is that i've viewed the headers of linkedIn emails and i found out that they are using 2 DKIM headers, DomainKey-Signature & DKIM-Signature.

What's the difference? and is that why Gmail doesn't verify my emails? & do you recommend any alternative & robust classes to sign emails with domain keys on php?

Thanks

答:
Both use Public/Private keys to digitally sign emails.  Both use a text file in the sender's DNS server that contain the public key that can be used by the recipient to verify the signature.

Domain Keys was the first version.

DKIM is the updated version.

The difference is how Domain Keys and DKIM sign the messages, and build the header.

Email recipients may implement either of them (or both). The only thing you can do, is sign with both classes, if you want to cover all bases.

Do you want the technical details on the differences between DomainKeys vs DKIM?

--Dave


问:
For loop for finding index in string
I'm wondering why my function does not call the index of the character in the string. I used a for loop for this, and for some reason it's just listing all of the possible indices of the string. I made a specific if statement, but I don't get why it's not following the instructions.</p>

```<code>def where_is(char,string):
  c=0
  for char in string:
    if char==(string[c]):
      print (c)
      c+=1
    else:
      print ("")
where_is('p','apple')
</code>```

答:
Your loop is overwriting your parameter char. As soon as you enter your loop, it is overwritten with a character from the string, which you then compare to itself. Rename either your parameter or your loop variable. Also, your counter increment c+=1 should also be outside of your if. You want to increase the index whether or not you find a match, otherwise your results are going to be off.

And just as a matter of style, you don't really need that else block, the print call will just give you extra newlines you probably don't want.

Title: For loop for finding index in string

Body:
I'm wondering why my function does not call the index of the character in the string. I used a for loop for this, and for some reason it's just listing all of the possible indices of the string. I made a specific if statement, but I don't get why it's not following the instructions.

def where_is(char,string):
  c=0
  for char in string:
    if char==(string[c]):
      print (c)
      c+=1
    else:
      print ("")
where_is('p','apple')


问:
Screen wrap a 2-D array in C++
I am finishing up a Conway's Game of Life assignment. I created a function to generate a random array of 1s and 0s; the 1s represent a living cell and the zero an empty space.

I created a separate function to inspect the neighborhood and make a count to determine how the game progresses.

The rules: if a cell has 2 or 3 neighbors it survives, more than 3 or less than 2 it dies, and if an empty  space has 3 neighbors it is "born". My "planet" is 79 x 24 characters but it's not a real planet yet until I wrap the screen.

Here is the function:

```<code>void life (int master[24][79]) //generates/kills cells based on neighborhood
{
    int temp[24][79]; //temporary array for manipulating data
    copy (master, temp); //copy array onto temp
    for(int j = 0; j < h; j++) //height loop
    {

        for (int i = 0; i < w; i++) //width loop
        {
            int count = 0; //intialize neighbor count variable
            count = master[j-1][i] + //searches down
            master[j-1][i-1] + //down left
            master[j][i-1] + //left
            master[j+1][i-1] + //up left
            master[j+1][i] + //up
            master[j+1][i+1] + //up right
            master[j][i+1] + //right
            master[j-1][i+1]; //down right
            //cell dies if count falls below 2 or rises above 3
            if(count < 2 || count > 3)
                temp[j][i] = 0;
            //cell stays alive if it has two neighbors
            if(count == 2)
                temp[j][i] = master[j][i];
            //cell either stays alive or gets born if three neighbors
            if(count == 3)
                temp[j][i] = 1;
        } //end width loop
    }//end height loop
    copy(temp, master); //copy temp back to main array
} //end life function
</code>```

Im sure that I am supposed to use the modulus but nothing that I try seems to work. I have tried using while loops to bring the maximum values back to zero, but I can tell that has the effect of wrapping gradually downwards similar to how threads wrap around a screw. Should I just mod-ify (sorry) search part of the code to look like this?

```<code>int count = 0; //intialize neighbor count variable
            count = master[(j-1)%h][i%w] + //searches down
            master[(j-1)%h][(i-1)%w] + //down left
            master[j%h][(i-1)%w] + //left
            master[(j+1)%h][(i-1)%w] + //up left
            master[(j+1)%h][i%w] + //up
            master[(j+1)%h][(i+1)%w] + //up right
            master[j%h][(i+1)%w] + //right
            master[(j-1)%h][(i+1)%w]; //down right
</code>```

答:
To stay in range [0-w[ you have to use modulus and make sure than your number is positive, so, something like

```<code>master[(j - 1 + h) % h][i % w]
+ master[(j - 1 + h) % h][(i - 1 + w) % w]
// ...
</code>```

and so on.

I suggest to add a accessor function, something like

```<code>int& get(int master[24][79], int i, int j)
{
    return master[(j - 1 + 24) % 24][(i - 1 + 79) % 79]
}
</code>```

and then simply use

```<code>get(master, i, j - 1)
+ get(master, i - 1, j - 1)
// ...
</code>```

I suggest to wrap your data in a class:

```<code>class WorldMap
{
public:
    int  get(int i, int j) const { return cells[(i + 24) % 24][(j + 79) % 79]; }
    int& get(int i, int j)       { return cells[(i + 24) % 24][(j + 79) % 79]; }
private:
    int cells[24][79] = {};
};
</code>```

And then

```<code>void life (WorldMap& worldMap)
{
    WorldMap next;
    // ... initialize next according to rules of life
    worldMap = next;
}
</code>```

Title: Screen wrap a 2-D array in C++

Body:
I am finishing up a Conway's Game of Life assignment. I created a function to generate a random array of 1s and 0s; the 1s represent a living cell and the zero an empty space.

I created a separate function to inspect the neighborhood and make a count to determine how the game progresses.

The rules: if a cell has 2 or 3 neighbors it survives, more than 3 or less than 2 it dies, and if an empty  space has 3 neighbors it is "born". My "planet" is 79 x 24 characters but it's not a real planet yet until I wrap the screen.

Here is the function:

void life (int master[24][79]) //generates/kills cells based on neighborhood
{
    int temp[24][79]; //temporary array for manipulating data
    copy (master, temp); //copy array onto temp
    for(int j = 0; j < h; j++) //height loop
    {

        for (int i = 0; i < w; i++) //width loop
        {
            int count = 0; //intialize neighbor count variable
            count = master[j-1][i] + //searches down
            master[j-1][i-1] + //down left
            master[j][i-1] + //left
            master[j+1][i-1] + //up left
            master[j+1][i] + //up
            master[j+1][i+1] + //up right
            master[j][i+1] + //right
            master[j-1][i+1]; //down right
            //cell dies if count falls below 2 or rises above 3
            if(count < 2 || count > 3)
                temp[j][i] = 0;
            //cell stays alive if it has two neighbors
            if(count == 2)
                temp[j][i] = master[j][i];
            //cell either stays alive or gets born if three neighbors
            if(count == 3)
                temp[j][i] = 1;
        } //end width loop
    }//end height loop
    copy(temp, master); //copy temp back to main array
} //end life function

Im sure that I am supposed to use the modulus but nothing that I try seems to work. I have tried using while loops to bring the maximum values back to zero, but I can tell that has the effect of wrapping gradually downwards similar to how threads wrap around a screw. Should I just mod-ify (sorry) search part of the code to look like this?

int count = 0; //intialize neighbor count variable
            count = master[(j-1)%h][i%w] + //searches down
            master[(j-1)%h][(i-1)%w] + //down left
            master[j%h][(i-1)%w] + //left
            master[(j+1)%h][(i-1)%w] + //up left
            master[(j+1)%h][i%w] + //up
            master[(j+1)%h][(i+1)%w] + //up right
            master[j%h][(i+1)%w] + //right
            master[(j-1)%h][(i+1)%w]; //down right

Body:
To stay in range [0-w[ you have to use modulus and make sure than your number is positive, so, something like

master[(j - 1 + h) % h][i % w]
+ master[(j - 1 + h) % h][(i - 1 + w) % w]
// ...

and so on.

I suggest to add a accessor function, something like

int& get(int master[24][79], int i, int j)
{
    return master[(j - 1 + 24) % 24][(i - 1 + 79) % 79]
}

and then simply use

get(master, i, j - 1)
+ get(master, i - 1, j - 1)
// ...

I suggest to wrap your data in a class:

class WorldMap
{
public:
    int  get(int i, int j) const { return cells[(i + 24) % 24][(j + 79) % 79]; }
    int& get(int i, int j)       { return cells[(i + 24) % 24][(j + 79) % 79]; }
private:
    int cells[24][79] = {};
};

And then

void life (WorldMap& worldMap)
{
    WorldMap next;
    // ... initialize next according to rules of life
    worldMap = next;
}


问:
observeSingleEvent(of:with:) fetching old data
Background:

I have an app where new users complete a sign-up form (consisting of a username, email, and a password) to register for an account. When the new user submits the form, the app checks its Firebase Database to see if the username has already been taken. The problem here is that observeSingleEvent(of:with:) is not getting the newest data. When I update the data directly from the Firebase console, the changes are not reflected back in the returned results of observeSingleEvent(of:with:). Even between app restarts, the new data changes are not returned.

The only thing I've seen on the issue is here. A user says not to have persistence enabled when using observeSingleEvent(of:with:). But, I have persistence disabled. Also, I set the keepSynced() on the FIRDatabase instance to false (and I've tried true as well). No luck with either setting.

Here's an example of what I am trying:

```<code>let usersDatabaseReference = FIRDatabase.database().reference().child("users")
usersDatabaseReference.keepSynced(false)

// Query the database to see if the username is available
// The user with the username "mark" was removed from the database via the Firebase console
let username = "mark" // This user used to exist in the database (and was previously added through the app).
usersDatabaseReference.child(username).observeSingleEvent(of: .value, with: { (snapshot) in ... } )
</code>```

The above code block should return the newest data (one where the user "mark" should not exist).

I am wondering if anyone else ran into this problem, or if anyone has possible solutions.

Note: Developing using iOS 10.1 and swift 3.

答:
the observeSingleEvent(of:with:) return the value only one time

try this :

```<code>refHandle = postRef.observe(FIRDataEventType.value, with: { (snapshot) in
  let postDict = snapshot.value as? [String : AnyObject] ?? [:]
  // ...
})
</code>```

this will add a listener on database event link

Body:
Background:

I have an app where new users complete a sign-up form (consisting of a username, email, and a password) to register for an account. When the new user submits the form, the app checks its Firebase Database to see if the username has already been taken. The problem here is that observeSingleEvent(of:with:) is not getting the newest data. When I update the data directly from the Firebase console, the changes are not reflected back in the returned results of observeSingleEvent(of:with:). Even between app restarts, the new data changes are not returned.

The only thing I've seen on the issue is here. A user says not to have persistence enabled when using observeSingleEvent(of:with:). But, I have persistence disabled. Also, I set the keepSynced() on the FIRDatabase instance to false (and I've tried true as well). No luck with either setting.

Here's an example of what I am trying:

let usersDatabaseReference = FIRDatabase.database().reference().child("users")
usersDatabaseReference.keepSynced(false)

// Query the database to see if the username is available
// The user with the username "mark" was removed from the database via the Firebase console
let username = "mark" // This user used to exist in the database (and was previously added through the app).
usersDatabaseReference.child(username).observeSingleEvent(of: .value, with: { (snapshot) in ... } )

The above code block should return the newest data (one where the user "mark" should not exist).

I am wondering if anyone else ran into this problem, or if anyone has possible solutions.

Note: Developing using iOS 10.1 and swift 3.

Body:
the observeSingleEvent(of:with:) return the value only one time

try this :

refHandle = postRef.observe(FIRDataEventType.value, with: { (snapshot) in
  let postDict = snapshot.value as? [String : AnyObject] ?? [:]
  // ...
})

this will add a listener on database event link


问:
Semaphore signalling vs mutex
I was looking over some topics that describes the difference between mutex and binary semaphore. In many topics it is stated that semaphore act as a signalling mechanism i.e if a thread has locked a semaphore then another thread can unlock(release) the semaphore(acting as signal).
But in case of mutex only the thread that locks the mutex can unlock it .It can't be unlocked by any other thread and if other thread tries to unlock it this will return error.

I have tried writing a code that uses mutex for synchronization. In the code I am locking the mutex in one thread and successfully unlocking the mutex in other thread.
Can someone please explain how this can happen.According to the answers everywhere  the other thread should not be able to unlock mutex.

Any suggestions are most welcome.

答:
Any suggestions are most welcome.

I have had no problems using this Posix Process Semaphore encapsulation for  std::thread as well as posix.

```<code>//
#include <semaphore.h>  // posix semaphore

class PPLSem_t // Posix Process Semaphore, set to Local mode (unnamed, unshared)
{
public: //           not shared-between-process-v  v--initial-value-unlocked
   PPLSem_t()   { int stat = ::sem_init(&m_sem, 0, 1);  assert(0 == stat); } // ctor
   ~PPLSem_t()  { int stat = ::sem_destroy(&m_sem);     assert(0 == stat); } // dtor

   int lock()   { return (::sem_wait(&m_sem)); }   // returns 0 when success, else -1
   int unlock() { return (::sem_post(&m_sem)); }   // returns 0 when success, else -1
private:
   ::sem_t m_sem;
};
</code>```

There is no restriction of which thread might signal it.

Title: Semaphore signalling vs mutex

Body:
Any suggestions are most welcome.

I have had no problems using this Posix Process Semaphore encapsulation for  std::thread as well as posix.

//
#include <semaphore.h>  // posix semaphore

class PPLSem_t // Posix Process Semaphore, set to Local mode (unnamed, unshared)
{
public: //           not shared-between-process-v  v--initial-value-unlocked
   PPLSem_t()   { int stat = ::sem_init(&m_sem, 0, 1);  assert(0 == stat); } // ctor
   ~PPLSem_t()  { int stat = ::sem_destroy(&m_sem);     assert(0 == stat); } // dtor

   int lock()   { return (::sem_wait(&m_sem)); }   // returns 0 when success, else -1
   int unlock() { return (::sem_post(&m_sem)); }   // returns 0 when success, else -1
private:
   ::sem_t m_sem;
};

There is no restriction of which thread might signal it.


问:
Find All Records from Customer where ALL their records have NULL value in Price Field
Hopefully I can describe this simply if not I'll try to make a table for it: say I have a table that tracks all visits to my store by customer name. I log their Name and Purchase Amount (if any). I want to get a list of visitors who never buy anything.  So if I have

VisitorName   PurchaseAmount

Bob           10

Bob           NULL

Mary          NULL

Mary          NULL

I want a query that returns Mary since all of her records have NULL in the PurchaseAmount

答:
You could use a not in subselect the VisitorName that have value not null</p>

```<code>select distinct visitorName from my_table
 where visitorName not in ( select VisitorName
                     from my_table where PurchaseAmount is not null)
</code>```

Body:
You could use a not in subselect the VisitorName that have value not null

select distinct visitorName from my_table
 where visitorName not in ( select VisitorName
                     from my_table where PurchaseAmount is not null)


问:
That assembly does not allow partially trusted callers. InitializeComponent()
Scenario: I am in the process of refactoring one of our applications to use Nhibernate and came across this issue a couple weeks back. The issue was originally with Nhibernate and Castle and to solve this they were both recompiled with the [assembly: AllowPartiallyTrustedCallers]. However after making some changes to the UI and codebase this error has reappeared again. Also worth noting is that I control the loading my user controls programmatically from Form_Main.

Problem: Whenever the user controls are generated I receive the error below. If I comment out the loading then the program will run. When I debug it ends at the InitializeComponent() function which is auto-generated. Note that I can't step into that function.

```<code>System.Security.SecurityException was unhandled
      Message="That assembly does not allow partially trusted callers."
      Source="A"
      GrantedSet=""
      PermissionState=""
      RefusedSet=""
      Url="file:///C:/Documents and Settings/ID/Desktop/A-NHIB2/bin/Debug/A.EXE"
      StackTrace:
           at A.UserControlCyber.InitializeComponent()
           at A.UserControlCyber..ctor() in C:\Documents and Settings\ID\Desktop\A-NHIB2\UserControl_Cyber.cs:line 34
           at A.FormMain.FormMainLoad(Object sender, EventArgs e) in C:\Documents and Settings\ID\Desktop\A-NHIB2\Form_Main.cs:line 30
           at System.Windows.Forms.Form.OnLoad(EventArgs e)
           at System.Windows.Forms.Form.OnCreateControl()
           at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
           at System.Windows.Forms.Control.CreateControl()
           at System.Windows.Forms.Control.WmShowWindow(Message& m)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
           at System.Windows.Forms.ContainerControl.WndProc(Message& m)
           at System.Windows.Forms.Form.WmShowWindow(Message& m)
           at System.Windows.Forms.Form.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           at System.Windows.Forms.SafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow)
           at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
           at System.Windows.Forms.Form.SetVisibleCore(Boolean value)
           at System.Windows.Forms.Control.set_Visible(Boolean value)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.Run(Form mainForm)
           at A.Program.Main() in C:\Documents and Settings\ID\Desktop\A-NHIB2\Program.cs:line 32
           at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
           at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
           at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
           at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
           at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
           at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
           at System.Activator.CreateInstance(ActivationContext activationContext)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.runTryCode(Object userData)
           at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
           at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException:
</code>```

Anyone have any ideas on the subject? I have already added [assembly: AllowPartiallyTrustedCallers] to the assembly. Is there any way to find out which reference(?) is causing this error? Or any way to step through InitializeComponent()?

NOTE: I have every permission included and the project is set to partial trust.

Anyways any help is greatly appreciated.

答:
OK, if I were to troubleshoot this issue, I would approach it as below:

1) If I am using .NET 4.0 make sure this is already handled.

2) Use ILDASM or reflector to open all DLLs in question on the bin folder to make sure AllowPartiallyTrustedCallersAttribute is set on them.

3) Use AppDomain.CurrentDomain.GetAssemblies() at the time of error (using immediate window) to see which assembly is loaded from where. This I think could be your problem as I have seen too often that old or rogue versions of assemblies are loaded from GAC or various bin folders

I think using these 3 steps you will be able to find your problem.

Body:
Scenario: I am in the process of refactoring one of our applications to use Nhibernate and came across this issue a couple weeks back. The issue was originally with Nhibernate and Castle and to solve this they were both recompiled with the [assembly: AllowPartiallyTrustedCallers]. However after making some changes to the UI and codebase this error has reappeared again. Also worth noting is that I control the loading my user controls programmatically from Form_Main.

Problem: Whenever the user controls are generated I receive the error below. If I comment out the loading then the program will run. When I debug it ends at the InitializeComponent() function which is auto-generated. Note that I can't step into that function.

System.Security.SecurityException was unhandled
      Message="That assembly does not allow partially trusted callers."
      Source="A"
      GrantedSet=""
      PermissionState=""
      RefusedSet=""
      Url="file:///C:/Documents and Settings/ID/Desktop/A-NHIB2/bin/Debug/A.EXE"
      StackTrace:
           at A.UserControlCyber.InitializeComponent()
           at A.UserControlCyber..ctor() in C:\Documents and Settings\ID\Desktop\A-NHIB2\UserControl_Cyber.cs:line 34
           at A.FormMain.FormMainLoad(Object sender, EventArgs e) in C:\Documents and Settings\ID\Desktop\A-NHIB2\Form_Main.cs:line 30
           at System.Windows.Forms.Form.OnLoad(EventArgs e)
           at System.Windows.Forms.Form.OnCreateControl()
           at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
           at System.Windows.Forms.Control.CreateControl()
           at System.Windows.Forms.Control.WmShowWindow(Message& m)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
           at System.Windows.Forms.ContainerControl.WndProc(Message& m)
           at System.Windows.Forms.Form.WmShowWindow(Message& m)
           at System.Windows.Forms.Form.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           at System.Windows.Forms.SafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow)
           at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
           at System.Windows.Forms.Form.SetVisibleCore(Boolean value)
           at System.Windows.Forms.Control.set_Visible(Boolean value)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.Run(Form mainForm)
           at A.Program.Main() in C:\Documents and Settings\ID\Desktop\A-NHIB2\Program.cs:line 32
           at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
           at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
           at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
           at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
           at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
           at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
           at System.Activator.CreateInstance(ActivationContext activationContext)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.runTryCode(Object userData)
           at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
           at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException:

Anyone have any ideas on the subject? I have already added [assembly: AllowPartiallyTrustedCallers] to the assembly. Is there any way to find out which reference(?) is causing this error? Or any way to step through InitializeComponent()?

NOTE: I have every permission included and the project is set to partial trust.

Anyways any help is greatly appreciated.


问:
Get rid of strings containing a pattern within a file
Within a linux file with the following content I want to get rid of everything starting with a specific pattern, which is aws: in this particular case:

```<code>aws:cloudformation:logical-id="somestring" Name="abc" Product="xyz" Role="www" aws:autoscaling:groupName="strings-and-numbers-012345" aws:cloudformation:stack-id="strings-and-numbers-012345" aws:cloudformation:stack-name="strings-and-numbers-012345"
</code>```

The output I need is just: Name="abc" Product="xyz" Role="www"; how do I do it?

答:
Given:

```<code>$ echo "$s"
aws:cloudformation:logical-id="somestring" Name="abc" Product="xyz" Role="www" aws:autoscaling:groupName="strings-and-numbers-012345" aws:cloudformation:stack-id="strings-and-numbers-012345" aws:cloudformation:stack-name="strings-and-numbers-012345"
</code>```

With GNU Grep and Perl regex you can do:

```<code>$ echo "$s" | grep -Po '(\bName=.*?)(?=aws)'
Name="abc" Product="xyz" Role="www"
</code>```

If the fields you are interested in are strictly positional, you can use awk or cut to print those positional fields:

```<code>$ echo "$s" | awk '{print $2, $3, $4}'
Name="abc" Product="xyz" Role="www"
$ echo "$s" | cut -d" " -f2-4
Name="abc" Product="xyz" Role="www"
</code>```

To weed out any entries that start with aws you can use perl:

```<code>$ echo "$s" | perl -lane 'foreach (@F) {$s=$s."$_ " unless /^aws/} print "$s"'
Name="abc" Product="xyz" Role="www"
</code>```

or

```<code>$ echo "$s" | perl -lane 'print join(" ", grep {!/^aws/} @F)'
Name="abc" Product="xyz" Role="www"
</code>```

Body:
Within a linux file with the following content I want to get rid of everything starting with a specific pattern, which is aws: in this particular case:

aws:cloudformation:logical-id="somestring" Name="abc" Product="xyz" Role="www" aws:autoscaling:groupName="strings-and-numbers-012345" aws:cloudformation:stack-id="strings-and-numbers-012345" aws:cloudformation:stack-name="strings-and-numbers-012345"

The output I need is just: Name="abc" Product="xyz" Role="www"; how do I do it?

Body:
Given:

$ echo "$s"
aws:cloudformation:logical-id="somestring" Name="abc" Product="xyz" Role="www" aws:autoscaling:groupName="strings-and-numbers-012345" aws:cloudformation:stack-id="strings-and-numbers-012345" aws:cloudformation:stack-name="strings-and-numbers-012345"

With GNU Grep and Perl regex you can do:

$ echo "$s" | grep -Po '(\bName=.*?)(?=aws)'
Name="abc" Product="xyz" Role="www"

If the fields you are interested in are strictly positional, you can use awk or cut to print those positional fields:

$ echo "$s" | awk '{print $2, $3, $4}'
Name="abc" Product="xyz" Role="www"
$ echo "$s" | cut -d" " -f2-4
Name="abc" Product="xyz" Role="www"

To weed out any entries that start with aws you can use perl:

$ echo "$s" | perl -lane 'foreach (@F) {$s=$s."$_ " unless /^aws/} print "$s"'
Name="abc" Product="xyz" Role="www"

or

$ echo "$s" | perl -lane 'print join(" ", grep {!/^aws/} @F)'
Name="abc" Product="xyz" Role="www"


问:
Using 3 octets (0.0.0) and storing as a variable
I have an imported excel sheet with 3100 subnets (192.168.1.0/24) as an example. I want to be able to search the first 3 octets with a stored variable. If I can get that, I can edit the spreadsheet to just contain he first 3 octets and get the outcome I would like in the future of the program. Thank you very much in advance.</p>

```<code> string octets = ("10.2.30");
        var match = false;

        for (int i = 0; i < xlRange.Rows.Count; i++)
        {
            IPAddress excelIP;

            if (IPAddress.TryParse(xlWorksheet.Cells[i + 1, 1].Value.ToString(), out excelIP))
            {

                if (excelIP.ToString().Equals(octets))
                {
                    match = true;
                    Console.Write(excelIP.ToString());
                    Console.WriteLine(" -This id was found");
                }
            }
        }
        if (!match)
        {
            Console.WriteLine("No Match ");

        }

        xlWorkbook.Close(); xlApp = null;
    }
</code>```

答:
Here are a couple of ways to do this:

Modify your octets string with a trailing period and match it to the beginning of the excelIP string.

Split the octets string into a List and compare the elements in that list with the same number of elements of the excelIP when split into a list of octets.

In either case, you'll need to add a reference to System.Linq to use the expressions.

```<code>using System;
using System.Linq;
using System.Net;
</code>```

For #1:

```<code>// add a trailing '.' so we can match the start of the excelIP
string octets = ("10.2.30.");
var match = false;

for (int i = 0; i < xlRange.Rows.Count; i++)
{
    // Get the IP address portion of the CIDR string
    var cellString = xlWorksheet.Cells[i + 1, 1].Value.Split('/')[0];
    IPAddress excelIP;

    // If cellString starts with the octets string and it's a valid IP address...
    if (cellString.StartsWith(octets) && IPAddress.TryParse(cellString, out excelIP))
    {
        match = true;
        Console.Write(excelIP.ToString());
        Console.WriteLine(" -This id was found");
    }
}
</code>```

For #2:

```<code>var match = false;
string octets = ("10.2.30");

string[] octetsToMatch = octets.Split('.');

for (int i = 0; i < xlRange.Rows.Count; i++)
{
    // Get the IP address portion of the CIDR string
    var cellString = xlWorksheet.Cells[i + 1, 1].Value.Split('/')[0];
    IPAddress excelIP;

    if (IPAddress.TryParse(cellString, out excelIP))
    {
        // Compare the first octets of the IP address with our octetsToMatch
        if (octetsToMatch.SequenceEqual(cellString.Split('.').Take(octetsToMatch.Length)))
        {
            match = true;
            Console.Write(excelIP.ToString());
            Console.WriteLine(" -This id was found");
        }
    }
}
</code>```

Body:
I have an imported excel sheet with 3100 subnets (192.168.1.0/24) as an example. I want to be able to search the first 3 octets with a stored variable. If I can get that, I can edit the spreadsheet to just contain he first 3 octets and get the outcome I would like in the future of the program. Thank you very much in advance.

 string octets = ("10.2.30");
        var match = false;

        for (int i = 0; i < xlRange.Rows.Count; i++)
        {
            IPAddress excelIP;

            if (IPAddress.TryParse(xlWorksheet.Cells[i + 1, 1].Value.ToString(), out excelIP))
            {

                if (excelIP.ToString().Equals(octets))
                {
                    match = true;
                    Console.Write(excelIP.ToString());
                    Console.WriteLine(" -This id was found");
                }
            }
        }
        if (!match)
        {
            Console.WriteLine("No Match ");

        }

        xlWorkbook.Close(); xlApp = null;
    }

Body:
Here are a couple of ways to do this:

Modify your octets string with a trailing period and match it to the beginning of the excelIP string.

Split the octets string into a List and compare the elements in that list with the same number of elements of the excelIP when split into a list of octets.

In either case, you'll need to add a reference to System.Linq to use the expressions.

using System;
using System.Linq;
using System.Net;

For #1:

// add a trailing '.' so we can match the start of the excelIP
string octets = ("10.2.30.");
var match = false;

for (int i = 0; i < xlRange.Rows.Count; i++)
{
    // Get the IP address portion of the CIDR string
    var cellString = xlWorksheet.Cells[i + 1, 1].Value.Split('/')[0];
    IPAddress excelIP;

    // If cellString starts with the octets string and it's a valid IP address...
    if (cellString.StartsWith(octets) && IPAddress.TryParse(cellString, out excelIP))
    {
        match = true;
        Console.Write(excelIP.ToString());
        Console.WriteLine(" -This id was found");
    }
}

For #2:

var match = false;
string octets = ("10.2.30");

string[] octetsToMatch = octets.Split('.');

for (int i = 0; i < xlRange.Rows.Count; i++)
{
    // Get the IP address portion of the CIDR string
    var cellString = xlWorksheet.Cells[i + 1, 1].Value.Split('/')[0];
    IPAddress excelIP;

    if (IPAddress.TryParse(cellString, out excelIP))
    {
        // Compare the first octets of the IP address with our octetsToMatch
        if (octetsToMatch.SequenceEqual(cellString.Split('.').Take(octetsToMatch.Length)))
        {
            match = true;
            Console.Write(excelIP.ToString());
            Console.WriteLine(" -This id was found");
        }
    }
}


问:
Find parent node position using XSLT
I want to find the parent node position from the child node in XSLT.</p>

答:
I want to find the parent node
  position from the child node in
  XSLT.

This is done entirely using XPath.

The answer depends on what is the definition of "parent node position:

```<code>count(../preceding-sibling::*) + 1
</code>```

is the ordinal number of the parent among all upper-level elements

```<code>count(../preceding-sibling::node()) + 1
</code>```

is the ordinal number of the parent among all upper-level nodes (including text-nodes, comments and PIs.

The above expression is the only correct one if the current node is an immediate child of the root / (such as top element, top-level comment or top-level processing instruction).

Title: Find parent node position using XSLT

Body:
I want to find the parent node
  position from the child node in
  XSLT.

This is done entirely using XPath.

The answer depends on what is the definition of "parent node position:

count(../preceding-sibling::*) + 1

is the ordinal number of the parent among all upper-level elements

count(../preceding-sibling::node()) + 1

is the ordinal number of the parent among all upper-level nodes (including text-nodes, comments and PIs.

The above expression is the only correct one if the current node is an immediate child of the root / (such as top element, top-level comment or top-level processing instruction).


问:
Predict in R after GLM
I trained   my model on 6000 training sample (glm)
Then, I tried predict for vector with 200000 rows,
But as a result I received only 6000 rows.

I used these arguments for the function predict():

```<code>     predict(
object = model_ppp2,
newdate = Model_education,
type = c("link", "response", "terms"),
se.fit = TRUE,
dispersion = NULL,
terms = NULL,
na.action = na.pass
)
</code>```

Thanks

答:
The code should be

```<code>predict(
 object = model_ppp2,
 newdata = Model_education,
 type = c("link", "response", "terms"),
 se.fit = TRUE,
 dispersion = NULL,
 terms = NULL,
 na.action = na.pass
)
</code>```

so newdatA instead of newdatE

Title: Predict in R after GLM

Body:
I trained   my model on 6000 training sample (glm)
Then, I tried predict for vector with 200000 rows,
But as a result I received only 6000 rows.

I used these arguments for the function predict():

     predict(
object = model_ppp2,
newdate = Model_education,
type = c("link", "response", "terms"),
se.fit = TRUE,
dispersion = NULL,
terms = NULL,
na.action = na.pass
)

Thanks

Body:
The code should be

predict(
 object = model_ppp2,
 newdata = Model_education,
 type = c("link", "response", "terms"),
 se.fit = TRUE,
 dispersion = NULL,
 terms = NULL,
 na.action = na.pass
)

so newdatA instead of newdatE