问:
RecyclerView doesn't load items on first start of activity
Everytime we open the activity that bares the recycler adapter it fails to load on the first try. Exiting the activity and re-entering fixes the problem. Here is a gif for example. https://gyazo.com/32dc664dd427ef1129704a09861a3708

The Item i am spawning in:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    android:id="@+id/show_chat_single_item_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="70dp"

        app:cardBackgroundColor="#dcdada"
        app:cardCornerRadius="0dp"
        app:contentPadding="3dp"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="2dp"
        card_view:cardUseCompatPadding="true">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/chat_persion_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:srcCompat="@mipmap/ic_launcher" />

            <TextView
                android:id="@+id/chat_persion_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="0dp"
                android:text="Name"
                android:textSize="18sp"
                android:textStyle="bold"
                app:layout_constraintLeft_toRightOf="@+id/chat_persion_image"
                app:layout_constraintTop_toTopOf="@+id/chat_persion_image" />

            <TextView
                android:id="@+id/chat_persion_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="0dp"
                android:layout_marginTop="8dp"
                android:text="Email"
                app:layout_constraintLeft_toLeftOf="@+id/chat_persion_name"
                app:layout_constraintTop_toBottomOf="@+id/chat_persion_name" />
        </android.support.constraint.ConstraintLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>
</code>```

My conversation layout:

```<code><?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/msgs_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:theme="@style/AppTheme2"

        >

        <android.support.v7.widget.RecyclerView

            android:id="@+id/active_chats"
            android:layout_width="match_parent"
            android:layout_height="510dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:layout_marginTop="57dp">

        </android.support.v7.widget.RecyclerView>

        <include
            android:id="@+id/include2"
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            />

    </RelativeLayout>
</code>```

My Adapter:

```<code>public class ActiveChatConvo extends RecyclerView.Adapter<ActiveChatConvo.ViewHolder>
{
    private ArrayList<User> mUsers;
    private Context mContext;

    public ActiveChatConvo(ArrayList<User> photos,Context dick) {
        mUsers = photos;
        mContext = dick;
    }

    private Context getContext() {
        return mContext;
    }

    @Override
    public ActiveChatConvo.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        // Inflate the custom layout
        View contactView = inflater.inflate(R.layout.chat_single_item, parent, false);

        // Return a new holder instance
        ViewHolder viewHolder = new ViewHolder(contactView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // Get the data model based on position
        User user = mUsers.get(position);

        // Set item views based on your views and data model
        TextView name = holder.mItemName;
        name.setText(user.getName());
        TextView description = holder.mItemDescription;
        description.setText(user.getEmail());
        ImageView pic = holder.mItemImage;
        Picasso.with(pic.getContext()).load(Uri.parse(user.getPic())).into(pic);

    }

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

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

        private ImageView mItemImage;
        private TextView mItemName;
        private TextView mItemDescription;
        private LinearLayout layout;
        final LinearLayout.LayoutParams params;

        public ViewHolder(View v) {
            super(v);

            mItemImage = (ImageView) v.findViewById(R.id.chat_persion_image);
            mItemName = (TextView) v.findViewById(R.id.chat_persion_name);
            mItemDescription = (TextView) v.findViewById(R.id.chat_persion_email);
            layout = (LinearLayout) itemView.findViewById(R.id.show_chat_single_item_layout);
            params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            v.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            Context context = itemView.getContext();
            Intent showChatIntent = new Intent(context, ChatConversationActivity.class);
            //showPhotoIntent.putExtra(PHOTO_KEY, mPhoto);
            context.startActivity(showChatIntent);
        }
    }
}
</code>```

My main class

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

    private Toolbar toolbar;
    private ViewPager mViewPager;
    private TextView person_name,person_email;
    private RecyclerView recyclerView;
    private DatabaseReference mRef;
    private LinearLayoutManager mLinearLayoutManager;
    private ArrayList<User> users;
    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_connections);

        //Database
        mRef = FirebaseDatabase.getInstance().getReference("Users");
        mRef.keepSynced(true);

        mAuth = FirebaseAuth.getInstance();
        FirebaseUser user = mAuth.getCurrentUser();

        users = new ArrayList<>();

        mRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists())
                {

                    for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                        String name = postSnapshot.child("Name").getValue(String.class);
                        String email = postSnapshot.child("Email").getValue(String.class);
                        String pic = postSnapshot.child("image").getValue(String.class);

                        users.add(new User(name,email,pic));
                    }
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        //Recycler View
        recyclerView = (RecyclerView)findViewById(R.id.active_chats);
        ActiveChatConvo adapter = new ActiveChatConvo(users,this);
        recyclerView.setAdapter(adapter);
        mLinearLayoutManager = new LinearLayoutManager(this);
        //mLinearLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(mLinearLayoutManager);

        //VIEWS

        toolbar = (Toolbar) findViewById(R.id.tToolbar);
        if (toolbar != null)
            setSupportActionBar(toolbar);

        ImageView profileActivity = (ImageView) toolbar.findViewById(R.id.action_profile);
        ImageView homeActivity = (ImageView) toolbar.findViewById(R.id.action_home);

        profileActivity.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent profileActivity = new Intent(ConnectionsActivity.this, ProfileActivity.class);
                startActivity(profileActivity);
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }

        });

        homeActivity.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent home = new Intent(ConnectionsActivity.this, HomeActivity.class);
                startActivity(home);
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }

        });
    }

    }
</code>```

So if the recyclerView Activity is the first activity I visit then it will not create the items.

答:
Replace this:

```<code>recyclerView = (RecyclerView)findViewById(R.id.active_chats);
ActiveChatConvo adapter = new ActiveChatConvo(users,this);
recyclerView.setAdapter(adapter);
mLinearLayoutManager = new LinearLayoutManager(this);
//mLinearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLinearLayoutManager);
</code>```

with this:

```<code>recyclerView = (RecyclerView)findViewById(R.id.active_chats);
ActiveChatConvo adapter = new ActiveChatConvo(users,this);
mLinearLayoutManager = new LinearLayoutManager(this);
//mLinearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLinearLayoutManager);
recyclerView.setAdapter(adapter);
</code>```

You need to set adapter after you set LayoutManager.

Body:
Everytime we open the activity that bares the recycler adapter it fails to load on the first try. Exiting the activity and re-entering fixes the problem. Here is a gif for example. https://gyazo.com/32dc664dd427ef1129704a09861a3708

The Item i am spawning in:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    android:id="@+id/show_chat_single_item_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="70dp"

        app:cardBackgroundColor="#dcdada"
        app:cardCornerRadius="0dp"
        app:contentPadding="3dp"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="2dp"
        card_view:cardUseCompatPadding="true">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/chat_persion_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:srcCompat="@mipmap/ic_launcher" />

            <TextView
                android:id="@+id/chat_persion_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="0dp"
                android:text="Name"
                android:textSize="18sp"
                android:textStyle="bold"
                app:layout_constraintLeft_toRightOf="@+id/chat_persion_image"
                app:layout_constraintTop_toTopOf="@+id/chat_persion_image" />

            <TextView
                android:id="@+id/chat_persion_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="0dp"
                android:layout_marginTop="8dp"
                android:text="Email"
                app:layout_constraintLeft_toLeftOf="@+id/chat_persion_name"
                app:layout_constraintTop_toBottomOf="@+id/chat_persion_name" />
        </android.support.constraint.ConstraintLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

My conversation layout:

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/msgs_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:theme="@style/AppTheme2"

        >

        <android.support.v7.widget.RecyclerView

            android:id="@+id/active_chats"
            android:layout_width="match_parent"
            android:layout_height="510dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:layout_marginTop="57dp">

        </android.support.v7.widget.RecyclerView>

        <include
            android:id="@+id/include2"
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            />

    </RelativeLayout>

My Adapter:

public class ActiveChatConvo extends RecyclerView.Adapter<ActiveChatConvo.ViewHolder>
{
    private ArrayList<User> mUsers;
    private Context mContext;

    public ActiveChatConvo(ArrayList<User> photos,Context dick) {
        mUsers = photos;
        mContext = dick;
    }

    private Context getContext() {
        return mContext;
    }

    @Override
    public ActiveChatConvo.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        // Inflate the custom layout
        View contactView = inflater.inflate(R.layout.chat_single_item, parent, false);

        // Return a new holder instance
        ViewHolder viewHolder = new ViewHolder(contactView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // Get the data model based on position
        User user = mUsers.get(position);

        // Set item views based on your views and data model
        TextView name = holder.mItemName;
        name.setText(user.getName());
        TextView description = holder.mItemDescription;
        description.setText(user.getEmail());
        ImageView pic = holder.mItemImage;
        Picasso.with(pic.getContext()).load(Uri.parse(user.getPic())).into(pic);

    }

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

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

        private ImageView mItemImage;
        private TextView mItemName;
        private TextView mItemDescription;
        private LinearLayout layout;
        final LinearLayout.LayoutParams params;

        public ViewHolder(View v) {
            super(v);

            mItemImage = (ImageView) v.findViewById(R.id.chat_persion_image);
            mItemName = (TextView) v.findViewById(R.id.chat_persion_name);
            mItemDescription = (TextView) v.findViewById(R.id.chat_persion_email);
            layout = (LinearLayout) itemView.findViewById(R.id.show_chat_single_item_layout);
            params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            v.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            Context context = itemView.getContext();
            Intent showChatIntent = new Intent(context, ChatConversationActivity.class);
            //showPhotoIntent.putExtra(PHOTO_KEY, mPhoto);
            context.startActivity(showChatIntent);
        }
    }
}

My main class

public class ConnectionsActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private ViewPager mViewPager;
    private TextView person_name,person_email;
    private RecyclerView recyclerView;
    private DatabaseReference mRef;
    private LinearLayoutManager mLinearLayoutManager;
    private ArrayList<User> users;
    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_connections);

        //Database
        mRef = FirebaseDatabase.getInstance().getReference("Users");
        mRef.keepSynced(true);

        mAuth = FirebaseAuth.getInstance();
        FirebaseUser user = mAuth.getCurrentUser();

        users = new ArrayList<>();

        mRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists())
                {

                    for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                        String name = postSnapshot.child("Name").getValue(String.class);
                        String email = postSnapshot.child("Email").getValue(String.class);
                        String pic = postSnapshot.child("image").getValue(String.class);

                        users.add(new User(name,email,pic));
                    }
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        //Recycler View
        recyclerView = (RecyclerView)findViewById(R.id.active_chats);
        ActiveChatConvo adapter = new ActiveChatConvo(users,this);
        recyclerView.setAdapter(adapter);
        mLinearLayoutManager = new LinearLayoutManager(this);
        //mLinearLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(mLinearLayoutManager);

        //VIEWS

        toolbar = (Toolbar) findViewById(R.id.tToolbar);
        if (toolbar != null)
            setSupportActionBar(toolbar);

        ImageView profileActivity = (ImageView) toolbar.findViewById(R.id.action_profile);
        ImageView homeActivity = (ImageView) toolbar.findViewById(R.id.action_home);

        profileActivity.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent profileActivity = new Intent(ConnectionsActivity.this, ProfileActivity.class);
                startActivity(profileActivity);
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }

        });

        homeActivity.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent home = new Intent(ConnectionsActivity.this, HomeActivity.class);
                startActivity(home);
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }

        });
    }

    }

So if the recyclerView Activity is the first activity I visit then it will not create the items.

Body:
Replace this:

recyclerView = (RecyclerView)findViewById(R.id.active_chats);
ActiveChatConvo adapter = new ActiveChatConvo(users,this);
recyclerView.setAdapter(adapter);
mLinearLayoutManager = new LinearLayoutManager(this);
//mLinearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLinearLayoutManager);

with this:

recyclerView = (RecyclerView)findViewById(R.id.active_chats);
ActiveChatConvo adapter = new ActiveChatConvo(users,this);
mLinearLayoutManager = new LinearLayoutManager(this);
//mLinearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLinearLayoutManager);
recyclerView.setAdapter(adapter);

You need to set adapter after you set LayoutManager.


来源: stackexchange

问:
How to align 2 tables (left and center) inside a div?
I want to center one table inside a div and have another table floating to the left of the first one.
My desired result would look something like this:

```[ (Left Table)     (Center table)               ]```

But with my current HTML and CSS (seen below) I get this result:

```[ (Left Table)           (Center table)         ]```

The problem here being that it floats the first table to the left and centers the second table in the remaining space.

This is the code:

#wrapper {
  text-align: center;
  width: 500px;
  border: 1px solid black;
}

#left {
  float:left;
}

#center {
  margin: 0 auto;
}

td {
  border: 1px solid black;
  width: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <table id="left">
    <tr>
      <td>
        Left
      </td>
    </tr>
  </table>

  <table id="center">
    <tr>
      <td>
        Center
      </td>
    </tr>
  </table>
</div></code>```

Any help on how to fix it?

答:
.table-container {
  float: left;
  position: relative;
  width: 100%;
}
table {
  float: left;
  width: 100px;
  border:1px solid #ddd;
}
.tbl2 {
  position: absolute;
  top: 0;
  left: calc(50% - 50px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='table-container'>
  <table class='tbl1'>
    <td> Hello </td>
  </table>
  <table class='tbl2'>
    <td> Hello </td>
  </table>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to center one table inside a div and have another table floating to the left of the first one.
My desired result would look something like this:

[ (Left Table)     (Center table)               ]

But with my current HTML and CSS (seen below) I get this result:

[ (Left Table)           (Center table)         ]

The problem here being that it floats the first table to the left and centers the second table in the remaining space.

This is the code:

#wrapper {
  text-align: center;
  width: 500px;
  border: 1px solid black;
}

#left {
  float:left;
}

#center {
  margin: 0 auto;
}

td {
  border: 1px solid black;
  width: 100px;
}

        Left

        Center

Any help on how to fix it?

Body:
.table-container {
  float: left;
  position: relative;
  width: 100%;
}
table {
  float: left;
  width: 100px;
  border:1px solid #ddd;
}
.tbl2 {
  position: absolute;
  top: 0;
  left: calc(50% - 50px);
}

<div class='table-container'>
  <table class='tbl1'>
    <td> Hello </td>
  </table>
  <table class='tbl2'>
    <td> Hello </td>
  </table>
</div>

ContentLicense: CC BY-SA 3.0


问:
Retrieve List from listView.ItemsSource
I'd like to do a simple thing : Retrieve a ListView ItemsSource to use Linq on it and give it again to the Listview, like : </p>

```<code>LV1.ItemsSource = LV1.ItemsSource.Where(x => x.age > 10);
</code>```

<p>Can I do it somehow ? </p>

答:
Cast it to the type and then bind,</p>

```<code>var filterResult =  LV1.ItemsSource as List<yourclass>;
LV1.ItemsSource =filterResult .Where(x => x.age > 10);
</code>```

Title: Retrieve List from listView.ItemsSource

Body:
I'd like to do a simple thing : Retrieve a ListView ItemsSource to use Linq on it and give it again to the Listview, like :

LV1.ItemsSource = LV1.ItemsSource.Where(x => x.age > 10);

Can I do it somehow ?

Body:
Cast it to the type and then bind,

var filterResult =  LV1.ItemsSource as List<yourclass>;
LV1.ItemsSource =filterResult .Where(x => x.age > 10);


问:
How to add an id automatically to a related entity
I have a OneToOne relation between 2 entities. One Molecule and one ConcGenotox (conclusion about genotoxicity).

I come from a page where all imformations about one Molecule are displayed and the id of the Molecule is in the address bar.

There is a button to edit a new ConcGenotox about this molecule witch id is always in the address bar.

My question is : How to add automatically the id from the molecule in the id_molecule relation of ConcGenotox when adding a new ConcGenotox ?

ConcGenotox Entity:

```<code>class ConcGenotox
{
    /**
     * @var \Molecule
     *
     * @ORM\OneToOne(targetEntity="Molecule")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_molecule", referencedColumnName="id")
     * })
     *
     */
    private $idMolecule;
</code>```

Molecule Entity :

```<code>class Molecule
{
   /**
    * @ORM\OneToOne(targetEntity="NcstoxBundle\Entity\ConcGenotox", mappedBy="idMolecule")
    */
   private $concGenotox;
</code>```

Contrôler:

```<code>/**
 * Creates a new concGenotox entity.
 *
 * @Route("/new/{id}", name="concgenotox_new")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request, $id)
{
    $concGenotox = new Concgenotox();
    $form = $this->createForm('NcstoxBundle\Form\ConcGenotoxType', $concGenotox);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        var_dump($id);
        $concGenotox->setIdMolecule($id);
        $em->persist($concGenotox);
        $em->flush();

        return $this->redirectToRoute('concgenotox_show', array('id' => $concGenotox->getId()));
    }

    return $this->render('concgenotox/new.html.twig', array(
        'concGenotox' => $concGenotox,
        'form' => $form->createView(),
        'id' => $id,
    ));
}
</code>```

I tried to ->setIdMolecule($id) but it give me an error :

```<code>Expected value of type "NcstoxBundle\Entity\Molecule" for association field "NcstoxBundle\Entity\ConcGenotox#$idMolecule", got "string" instead.
</code>```

答:
Relationship property should be entity, not id.

Change:

```<code>class ConcGenotox
{
    /**
     * @var \Molecule
     *
     * @ORM\OneToOne(targetEntity="Molecule")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_molecule", referencedColumnName="id")
     * })
     *
     */
    private $idMolecule;
</code>```

to:

```<code>class ConcGenotox
{
    /**
     * @var \Molecule
     *
     * @ORM\OneToOne(targetEntity="Molecule", cascade={"persist"})
     */
    private $molecule;
</code>```

and change your action to:

```<code>/**
 * Creates a new concGenotox entity.
 *
 * @Route("/new/{molecule}", name="concgenotox_new")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request, Molecule $molecule)
{
    $concGenotox = new Concgenotox();
    $form = $this->createForm(ConcGenotoxType::class);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $concGenotox = $form->getData();

        $molecule->setConcGenotox($concGenotox);

        $this->getDoctrine()->getManager()->flush();

        return $this->redirectToRoute('concgenotox_show', array('id' => $concGenotox->getId()));
    }

    return $this->render('concgenotox/new.html.twig', array(
        'concGenotox' => $concGenotox,
        'form'        => $form->createView(),
        'id'          => $id,
    ));
}
</code>```

Body:
I have a OneToOne relation between 2 entities. One Molecule and one ConcGenotox (conclusion about genotoxicity).

I come from a page where all imformations about one Molecule are displayed and the id of the Molecule is in the address bar.

There is a button to edit a new ConcGenotox about this molecule witch id is always in the address bar.

My question is : How to add automatically the id from the molecule in the id_molecule relation of ConcGenotox when adding a new ConcGenotox ?

ConcGenotox Entity:

class ConcGenotox
{
    /**
     * @var \Molecule
     *
     * @ORM\OneToOne(targetEntity="Molecule")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_molecule", referencedColumnName="id")
     * })
     *
     */
    private $idMolecule;

Molecule Entity :

class Molecule
{
   /**
    * @ORM\OneToOne(targetEntity="NcstoxBundle\Entity\ConcGenotox", mappedBy="idMolecule")
    */
   private $concGenotox;

Contrôler:

/**
 * Creates a new concGenotox entity.
 *
 * @Route("/new/{id}", name="concgenotox_new")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request, $id)
{
    $concGenotox = new Concgenotox();
    $form = $this->createForm('NcstoxBundle\Form\ConcGenotoxType', $concGenotox);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        var_dump($id);
        $concGenotox->setIdMolecule($id);
        $em->persist($concGenotox);
        $em->flush();

        return $this->redirectToRoute('concgenotox_show', array('id' => $concGenotox->getId()));
    }

    return $this->render('concgenotox/new.html.twig', array(
        'concGenotox' => $concGenotox,
        'form' => $form->createView(),
        'id' => $id,
    ));
}

I tried to ->setIdMolecule($id) but it give me an error :

Expected value of type "NcstoxBundle\Entity\Molecule" for association field "NcstoxBundle\Entity\ConcGenotox#$idMolecule", got "string" instead.

Body:
Relationship property should be entity, not id.

Change:

class ConcGenotox
{
    /**
     * @var \Molecule
     *
     * @ORM\OneToOne(targetEntity="Molecule")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_molecule", referencedColumnName="id")
     * })
     *
     */
    private $idMolecule;

to:

class ConcGenotox
{
    /**
     * @var \Molecule
     *
     * @ORM\OneToOne(targetEntity="Molecule", cascade={"persist"})
     */
    private $molecule;

and change your action to:

/**
 * Creates a new concGenotox entity.
 *
 * @Route("/new/{molecule}", name="concgenotox_new")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request, Molecule $molecule)
{
    $concGenotox = new Concgenotox();
    $form = $this->createForm(ConcGenotoxType::class);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $concGenotox = $form->getData();

        $molecule->setConcGenotox($concGenotox);

        $this->getDoctrine()->getManager()->flush();

        return $this->redirectToRoute('concgenotox_show', array('id' => $concGenotox->getId()));
    }

    return $this->render('concgenotox/new.html.twig', array(
        'concGenotox' => $concGenotox,
        'form'        => $form->createView(),
        'id'          => $id,
    ));
}


问:
How to add and substract 15 minutes from date sql
I have a query to search records depending on latitude longitude and the date.

The query works fine for the same date, but I want to get records which are 15 minutes before the date and 15 minutes after the date.

Working query is this:

```<code>SELECT
   *
FROM post
WHERE st_lati LIKE '19.878454%' AND st_longi LIKE '73.836708%'
AND ed_lati LIKE '20.012709%' AND ed_longi LIKE '73.791389%'
AND pt_date LIKE '2017-05-30 06:30%'
</code>```

I tried to minus 15 minutes using dateadd function but its giving errors.

my attempt

```<code>SELECT
 *
FROM post
WHERE pt_date DATEADD(minute, -15 * @h - @m, pt_date)
AND st_lati LIKE '19.878454%'
AND st_longi LIKE '73.836708%'
AND ed_lati LIKE '20.012709%'
AND ed_longi LIKE '73.791389%'
</code>```

I want to get records where pt_date before 15 minutes and after 15 minutes.

答:
I use the UNIX_TIMESTAMP() function for this sort of thing, where you have the dates in ISO format, or close to it.  This allows you to work in seconds (so 15 minutes is 60 * 15):

The relevant part of your where clause should be:

AND UNIX_TIMESTAMP(pt_date) BETWEEN UNIX_TIMESTAMP('2017-05-30 06:30')-60*15 AND UNIX_TIMESTAMP('2017-05-30 06:30')+60*15;

Body:
I have a query to search records depending on latitude longitude and the date.

The query works fine for the same date, but I want to get records which are 15 minutes before the date and 15 minutes after the date.

Working query is this:

SELECT
   *
FROM post
WHERE st_lati LIKE '19.878454%' AND st_longi LIKE '73.836708%'
AND ed_lati LIKE '20.012709%' AND ed_longi LIKE '73.791389%'
AND pt_date LIKE '2017-05-30 06:30%'

I tried to minus 15 minutes using dateadd function but its giving errors.

my attempt

SELECT
 *
FROM post
WHERE pt_date DATEADD(minute, -15 * @h - @m, pt_date)
AND st_lati LIKE '19.878454%'
AND st_longi LIKE '73.836708%'
AND ed_lati LIKE '20.012709%'
AND ed_longi LIKE '73.791389%'

I want to get records where pt_date before 15 minutes and after 15 minutes.


问:
magento grand total update by ajax call
during checkout when we have to move into payment method here is wallet option what i have done

after click on checkbox if customer want to use wallet amount
it will show the calculation like this

so i want to update my grand total amount as per calculation
so i want to update

```<code><?php
$quote = Mage::getModel('checkout/session')->getQuote();
$quoteData= $quote->getData();
$grandTotal=$quoteData['grand_total']; ?>
</code>```

答:
```<code>$quote = Mage::getSingleton('checkout/cart')->getQuote();
$quote->setGrandTotal(1000)
                            ->setBaseGrandTotal(700)
                            ->setSubtotalWithDiscount(700)
                            ->setBaseSubtotalWithDiscount(1000)
                            ->save();
</code>```

<p>you can set the price of quote then you have to render that review block to see the price changes. I have this will help you </p>

Title: magento grand total update by ajax call

Body:
during checkout when we have to move into payment method here is wallet option what i have done

after click on checkbox if customer want to use wallet amount
it will show the calculation like this

so i want to update my grand total amount as per calculation
so i want to update

<?php
$quote = Mage::getModel('checkout/session')->getQuote();
$quoteData= $quote->getData();
$grandTotal=$quoteData['grand_total']; ?>

Body:
$quote = Mage::getSingleton('checkout/cart')->getQuote();
$quote->setGrandTotal(1000)
                            ->setBaseGrandTotal(700)
                            ->setSubtotalWithDiscount(700)
                            ->setBaseSubtotalWithDiscount(1000)
                            ->save();

you can set the price of quote then you have to render that review block to see the price changes. I have this will help you


问:
Computed column, or update column by trigger to keep statistics
For every user, our application calculates some statistics, like how many times they logged in or how many answers they got wrong in the quiz, ... it can be all sorts of things. The app runs on SQL Server and .NET Entity Framework 6.1

Right now, the statistics are calculated on demand but as the user base grows, this makes the reporting part of the application ever slower.

We were wondering about either using computed columns (either persisted or not persisted) or use a trigger to store these values with the user.

How would you go about doing this? It seems to me that computed columns may be easier to implement, but they would get recalculated every time I read the User from the table, which may not be very much faster than what we're doing now. Since we would fit an entire SQL query into the computed column, persisting the column does not seem a right fit either (how will SQL Server deduce that it should update the calculation?).
A trigger on certain actions seems to be a more logical fit for me.

For the sake of the argument, suppose all the calculated statistics are count(*) and sum(*) of values in other tables and nothing more interesting than that.

答:
If you have to store computed values, prefer to have the SQL Engine do the work for you rather than manually implementing this via triggers.

So, that would be persisted computed column and/or indexed views.

they would get recalculated every time I read the User from the table

Only if you include the computed column in your SELECT (and you've not opted for it to be persisted). This is why queries should generally only query for the columns that are required, rather than select *. However, since you're using an ORM, you may not be able to tell it not to include an expensive column - that's why you should prefer persistence or to use an indexed view - so that it's treated as a separate object that you load only when needed.

how will SQL Server deduce that it should update the calculation?

Because behind the scenes, SQL Server effectively implements triggers itself. But the bonus here is, those triggers have been tested millions of times and are code you don't have to write.

For the sake of the argument, suppose all the calculated statistics are count(*) and sum(*) of values in other tables

In such a circumstance, you can't really go the computed column route (computed columns should only really reference their own row in their own table. There are some quirky ways to try and bypass this using UDFs, but I'd usually recommend against), so in this case, I'd definitely be recommending the indexed view.


问:
How to animate tableViewCell only once?
I am working on a table view that I want have its cells animated when loaded. I am setting the alpha fade from 0 to 1 over 1.5 seconds. The problem I am running into is that this is animated each time cellForRowAt indexPath is called. Is there a good way to do this so the cell is animated only once and not each time cellForRowAt IndexPath is called? Any help is appreciated. Thanks!</p>

```<code>// function to configure custom table view cell
func configCell(place: Place) {
    // hide image and label before image is loaded
    headlineImage.alpha = 0
    headlineLabel.alpha = 0
    headlineLabel.text = place.name
    // set image asynchronously
    headlineImage.sd_setImage(with: URL(string: "ImageUrl"), placeholderImage: UIImage(named: "restaurant"), options: .continueInBackground) { (_, _, _, _ ) in
            // image download complete fade in image
            print("COMPLETED SD SET IMAGE")
            UIView.animate(withDuration: 1.5, animations: {
                self.headlineImage.alpha = 1
                self.headlineLabel.alpha = 1
            })
    }

}
</code>```

答:
Something like this might help.

Create a global variable

```<code>var isFirstLoad = true
</code>```

then in your configCell method, wrap the animation inside an if-block and also set the flag to false

```<code>func configCell(place: Place) {
    headlineLabel.text = place.name
    if isFirstLoad == true {
        isFirstLoad = false
        headlineImage.alpha = 0
        headlineLabel.alpha = 0
        headlineImage.sd_setImage(with: URL(string: "ImageUrl"), placeholderImage: UIImage(named: "restaurant"), options: .continueInBackground) { (_, _, _, _ ) in
            print("COMPLETED SD SET IMAGE")
            UIView.animate(withDuration: 1.5, animations: {
                self.headlineImage.alpha = 1
                self.headlineLabel.alpha = 1
            })
        }
    }
}
</code>```

Title: How to animate tableViewCell only once?

Body:
I am working on a table view that I want have its cells animated when loaded. I am setting the alpha fade from 0 to 1 over 1.5 seconds. The problem I am running into is that this is animated each time cellForRowAt indexPath is called. Is there a good way to do this so the cell is animated only once and not each time cellForRowAt IndexPath is called? Any help is appreciated. Thanks!

// function to configure custom table view cell
func configCell(place: Place) {
    // hide image and label before image is loaded
    headlineImage.alpha = 0
    headlineLabel.alpha = 0
    headlineLabel.text = place.name
    // set image asynchronously
    headlineImage.sd_setImage(with: URL(string: "ImageUrl"), placeholderImage: UIImage(named: "restaurant"), options: .continueInBackground) { (_, _, _, _ ) in
            // image download complete fade in image
            print("COMPLETED SD SET IMAGE")
            UIView.animate(withDuration: 1.5, animations: {
                self.headlineImage.alpha = 1
                self.headlineLabel.alpha = 1
            })
    }

}

Body:
Something like this might help.

Create a global variable

var isFirstLoad = true

then in your configCell method, wrap the animation inside an if-block and also set the flag to false

func configCell(place: Place) {
    headlineLabel.text = place.name
    if isFirstLoad == true {
        isFirstLoad = false
        headlineImage.alpha = 0
        headlineLabel.alpha = 0
        headlineImage.sd_setImage(with: URL(string: "ImageUrl"), placeholderImage: UIImage(named: "restaurant"), options: .continueInBackground) { (_, _, _, _ ) in
            print("COMPLETED SD SET IMAGE")
            UIView.animate(withDuration: 1.5, animations: {
                self.headlineImage.alpha = 1
                self.headlineLabel.alpha = 1
            })
        }
    }
}


问:
AsyncTaskLoader issue in android
Hi I am using AsyncTaskLoader in my app and I have implemented that in MovieTaskLoader class but when I am implementing Loader callbacks in my fragment I am getting type conversion error in onCreateLoader() method.
MovieTaskLoader class:

```<code>class MovieTaskLoader extends AsyncTaskLoader<ArrayList<Movies>> {

MovieTaskLoader(Context context) {
    super(context);
}

@Override
protected void onStartLoading() {
    forceLoad();
}

@Override
public ArrayList<Movies> loadInBackground() {

    //Building URL
    URL url = null;
    String jsonData = null;
    Uri uri = Uri.parse(Utility.BASE_URL).buildUpon()
            .appendPath("popular")
            .appendQueryParameter("api_key", BuildConfig.api_key)
            .build();
    try {
        url = new URL(uri.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    //Downloading json data
    HttpURLConnection urlConnection;

    try {
        assert url != null;
        urlConnection = (HttpURLConnection) url.openConnection();
        if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
            jsonData = readStream(urlConnection.getInputStream());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return getMovieData(jsonData);
}

private String readStream(InputStream in) {
    BufferedReader reader = null;
    StringBuilder response = new StringBuilder();
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return response.toString();
}

private ArrayList<Movies> getMovieData(String jsonData){
    ArrayList<Movies> movies = new ArrayList<>();
    try {
        JSONObject jsonObject = new JSONObject(jsonData);
        JSONArray results = jsonObject.getJSONArray("results");
        for(int i=0; i<20; i++){
            Movies movie = new Movies();
            JSONObject object = results.getJSONObject(i);
            movie.setTitle(object.getString("title"));
            movie.setSynopsis("overview");
            movie.setVote_avg("vote_average");
            movie.setDate("release_date");
            movies.add(movie);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return movies;
}
}
</code>```

Fragment class:

```<code>public class PopularFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<Movies>> {

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_popular, container, false);

    RecyclerView popularView = (RecyclerView) view.findViewById(R.id.popular_view);
    GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
    popularView.setLayoutManager(layoutManager);
    popularView.setAdapter(new RecyclerViewAdapter());

    return view;
}

@Override
public Loader<ArrayList<Movies>> onCreateLoader(int id, Bundle args) {
    return new MovieTaskLoader(getContext());
}

@Override
public void onLoadFinished(Loader<ArrayList<Movies>> loader, ArrayList<Movies> data) {

}

@Override
public void onLoaderReset(Loader<ArrayList<Movies>> loader) {

}
}
</code>```

I am getting error in onCreateLoader() method and type conversion error is:

Required: "Loader"

Found: MovieTaskLoader

答:
Check your imports. Make sure both are same versions like this </p>

```<code>android.support.v4.content.AsyncTaskLoader<D>
android.support.v4.app.LoaderManager.LoaderCallbacks<D>
</code>```

Title: AsyncTaskLoader issue in android

Body:
Hi I am using AsyncTaskLoader in my app and I have implemented that in MovieTaskLoader class but when I am implementing Loader callbacks in my fragment I am getting type conversion error in onCreateLoader() method.
MovieTaskLoader class:

class MovieTaskLoader extends AsyncTaskLoader<ArrayList<Movies>> {

MovieTaskLoader(Context context) {
    super(context);
}

@Override
protected void onStartLoading() {
    forceLoad();
}

@Override
public ArrayList<Movies> loadInBackground() {

    //Building URL
    URL url = null;
    String jsonData = null;
    Uri uri = Uri.parse(Utility.BASE_URL).buildUpon()
            .appendPath("popular")
            .appendQueryParameter("api_key", BuildConfig.api_key)
            .build();
    try {
        url = new URL(uri.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    //Downloading json data
    HttpURLConnection urlConnection;

    try {
        assert url != null;
        urlConnection = (HttpURLConnection) url.openConnection();
        if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
            jsonData = readStream(urlConnection.getInputStream());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return getMovieData(jsonData);
}

private String readStream(InputStream in) {
    BufferedReader reader = null;
    StringBuilder response = new StringBuilder();
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return response.toString();
}

private ArrayList<Movies> getMovieData(String jsonData){
    ArrayList<Movies> movies = new ArrayList<>();
    try {
        JSONObject jsonObject = new JSONObject(jsonData);
        JSONArray results = jsonObject.getJSONArray("results");
        for(int i=0; i<20; i++){
            Movies movie = new Movies();
            JSONObject object = results.getJSONObject(i);
            movie.setTitle(object.getString("title"));
            movie.setSynopsis("overview");
            movie.setVote_avg("vote_average");
            movie.setDate("release_date");
            movies.add(movie);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return movies;
}
}

Fragment class:

public class PopularFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<Movies>> {

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_popular, container, false);

    RecyclerView popularView = (RecyclerView) view.findViewById(R.id.popular_view);
    GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
    popularView.setLayoutManager(layoutManager);
    popularView.setAdapter(new RecyclerViewAdapter());

    return view;
}

@Override
public Loader<ArrayList<Movies>> onCreateLoader(int id, Bundle args) {
    return new MovieTaskLoader(getContext());
}

@Override
public void onLoadFinished(Loader<ArrayList<Movies>> loader, ArrayList<Movies> data) {

}

@Override
public void onLoaderReset(Loader<ArrayList<Movies>> loader) {

}
}

I am getting error in onCreateLoader() method and type conversion error is:

Required: "Loader"

Found: MovieTaskLoader

Body:
Check your imports. Make sure both are same versions like this

android.support.v4.content.AsyncTaskLoader<D>
android.support.v4.app.LoaderManager.LoaderCallbacks<D>


问:
Converting aggregate output to wide format
I used the function aggregate to make a long-format data-frame but a colleague needs to work with it in Excel. I'm finding it tricky to convert to wide format. I need to make the column "variable" and "Type" into several columns, each for the members they contain (Frontal, Parietal and Occipital) and (alpha, beta, gamma, delta and theta).</p>

```<code>dput(head(aggdata))
structure(list(Time = c(1, 2, 3, 4, 5, 6), Type = structure(c(1L,
1L, 1L, 1L, 1L, 1L), .Label = c("alpha", "beta", "gamma", "delta",
"theta"), class = c("ordered", "factor")), Group = structure(c(1L,
1L, 1L, 1L, 1L, 1L), .Label = c("C", "N"), class = "factor"),
    variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Frontal",
    "Parietal", "Occipital"), class = "factor"), Condition = c(1,
    1, 1, 1, 1, 1), value = c(0.0947259533333333, 0.0489575420666667,
    0.0686301660666667, 0.0754647909333333, 0.0708219834666667,
    0.0644100006)), .Names = c("Time", "Type", "Group", "variable",
"Condition", "value"), row.names = c(NA, 6L), class = "data.frame")
</code>```

答:
You may want to check the reshape2 package, and the dcast and melt functions.
What you have here is a nice molten data set, that you want to cast.

Let me alterate your sample data first as it doesn't give several variables to spread.

```<code>agg_data <- rbind(agg_data,head(agg_data,1))
agg_data$variable[7] <- "Parietal"
agg_data$value[7] <- 0.0686301660666667
agg_data

# Time  Type Group variable Condition      value
# 1    1 alpha     C  Frontal         1 0.09472595
# 2    2 alpha     C  Frontal         1 0.04895754
# 3    3 alpha     C  Frontal         1 0.06863017
# 4    4 alpha     C  Frontal         1 0.07546479
# 5    5 alpha     C  Frontal         1 0.07082198
# 6    6 alpha     C  Frontal         1 0.06441000
# 7    1 alpha     C Parietal         1 0.06863017
</code>```

and here's the line I think you want:

```<code>dcast(agg_data, Time  + Type + Group + Condition ~  variable)

# Time  Type Group Condition    Frontal   Parietal
# 1    1 alpha     C         1 0.09472595 0.06863017
# 2    2 alpha     C         1 0.04895754         NA
# 3    3 alpha     C         1 0.06863017         NA
# 4    4 alpha     C         1 0.07546479         NA
# 5    5 alpha     C         1 0.07082198         NA
# 6    6 alpha     C         1 0.06441000         NA
</code>```

On the left side you put the data you want to aggregate on, on the right side you pur the variable you want to spread, you can put a sum of variables on the right side as well to spread on several variables, for example:

```<code>dcast(agg_data, Time  + Group + Condition ~  variable + Type)

# Time Group Condition Frontal_alpha Parietal_alpha
# 1    1     C         1    0.09472595     0.06863017
# 2    2     C         1    0.04895754             NA
# 3    3     C         1    0.06863017             NA
# 4    4     C         1    0.07546479             NA
# 5    5     C         1    0.07082198             NA
# 6    6     C         1    0.06441000             NA
</code>```

Body:
I used the function aggregate to make a long-format data-frame but a colleague needs to work with it in Excel. I'm finding it tricky to convert to wide format. I need to make the column "variable" and "Type" into several columns, each for the members they contain (Frontal, Parietal and Occipital) and (alpha, beta, gamma, delta and theta).

dput(head(aggdata))
structure(list(Time = c(1, 2, 3, 4, 5, 6), Type = structure(c(1L,
1L, 1L, 1L, 1L, 1L), .Label = c("alpha", "beta", "gamma", "delta",
"theta"), class = c("ordered", "factor")), Group = structure(c(1L,
1L, 1L, 1L, 1L, 1L), .Label = c("C", "N"), class = "factor"),
    variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Frontal",
    "Parietal", "Occipital"), class = "factor"), Condition = c(1,
    1, 1, 1, 1, 1), value = c(0.0947259533333333, 0.0489575420666667,
    0.0686301660666667, 0.0754647909333333, 0.0708219834666667,
    0.0644100006)), .Names = c("Time", "Type", "Group", "variable",
"Condition", "value"), row.names = c(NA, 6L), class = "data.frame")

Body:
You may want to check the reshape2 package, and the dcast and melt functions.
What you have here is a nice molten data set, that you want to cast.

Let me alterate your sample data first as it doesn't give several variables to spread.

agg_data <- rbind(agg_data,head(agg_data,1))
agg_data$variable[7] <- "Parietal"
agg_data$value[7] <- 0.0686301660666667
agg_data

# Time  Type Group variable Condition      value
# 1    1 alpha     C  Frontal         1 0.09472595
# 2    2 alpha     C  Frontal         1 0.04895754
# 3    3 alpha     C  Frontal         1 0.06863017
# 4    4 alpha     C  Frontal         1 0.07546479
# 5    5 alpha     C  Frontal         1 0.07082198
# 6    6 alpha     C  Frontal         1 0.06441000
# 7    1 alpha     C Parietal         1 0.06863017

and here's the line I think you want:

dcast(agg_data, Time  + Type + Group + Condition ~  variable)

# Time  Type Group Condition    Frontal   Parietal
# 1    1 alpha     C         1 0.09472595 0.06863017
# 2    2 alpha     C         1 0.04895754         NA
# 3    3 alpha     C         1 0.06863017         NA
# 4    4 alpha     C         1 0.07546479         NA
# 5    5 alpha     C         1 0.07082198         NA
# 6    6 alpha     C         1 0.06441000         NA

On the left side you put the data you want to aggregate on, on the right side you pur the variable you want to spread, you can put a sum of variables on the right side as well to spread on several variables, for example:

dcast(agg_data, Time  + Group + Condition ~  variable + Type)

# Time Group Condition Frontal_alpha Parietal_alpha
# 1    1     C         1    0.09472595     0.06863017
# 2    2     C         1    0.04895754             NA
# 3    3     C         1    0.06863017             NA
# 4    4     C         1    0.07546479             NA
# 5    5     C         1    0.07082198             NA
# 6    6     C         1    0.06441000             NA


问:
SQLTransaction has completed error
I got following error once in my application.

This SQLTransaction has completed; it is no longer usable

Stack Trace is attached below – It says about Zombie Check and Rollback.

What is the mistake in the code?

Note: This error came only once.

UPDATE

From MSDN - SqlTransaction.Rollback Method

A Rollback generates an InvalidOperationException if the connection is terminated or if the transaction has already been rolled back on the server.

From Zombie check on Transaction - Error

One of the most frequent reasons I have seen this error showing up in various applications is, sharing SqlConnection across our application.

CODE

```<code>public int SaveUserLogOnInfo(int empID)
{
        int? sessionID = null;
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            SqlTransaction transaction = null;
            try
            {
                transaction = connection.BeginTransaction();
                sessionID = GetSessionIDForAssociate(connection, empID, transaction);

                    //Other Code

                //Commit
                transaction.Commit();
            }
            catch
            {
                //Rollback
                if (transaction != null)
                {
                    transaction.Rollback();
                    transaction.Dispose();
                    transaction = null;
                }

                //Throw exception
                throw;
            }
            finally
            {
                if (transaction != null)
                {
                    transaction.Dispose();
                }
            }
        }

        return Convert.ToInt32(sessionID,CultureInfo.InvariantCulture);

   }
</code>```

Stack Trace

REFERENCE:

What is zombie transaction?

Zombie check on Transaction - Error

SqlTransaction has completed

http://forums.asp.net/t/1579684.aspx/1

"This SqlTransaction has completed; it is no longer usable."... configuration error?

dotnet.sys-con.com - SqlClient Connection Pooling Exposed

Thread abort leaves zombie transactions and broken SqlConnection

答:
I use code below can reproduce this error, I use 1000 tasks to execute Sql, after about 300 tasks Successfully Completed, lots of exception about timeout error start to occur on ExecuteNonQuery(),

then next error This SqlTransaction has completed will occur on transaction.RollBack(); and its call stack also contains ZombieCheck().

(If single program with 1000 tasks pressure not enough, you can execute multiple compiled exe file at the same time,  or even use multi computers execute to one DataBase.)

So I guess one of the reason cause this error can be something wrong in Connection, then cause the transaction error happens as well.

```<code>Task[] tasks = new Task[1000];
for (int i = 0; i < 1000; i++)
{
    int j = i;
    tasks[i] = new Task(() =>
         ExecuteSqlTransaction("YourConnectionString", j)
        );
}

foreach (Task task in tasks)
{
    task.Start();
}

/////////////

public void ExecuteSqlTransaction(string connectionString, int exeSqlCou)
{

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction();

        // Must assign both transaction object and connection
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "select * from Employee";
            command.ExecuteNonQuery();

            // Attempt to commit the transaction.
            transaction.Commit();

            Console.WriteLine("Execute Sql to database."
                + exeSqlCou);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
            Console.WriteLine("  Message: {0}", ex.Message);

            // Attempt to roll back the transaction.
            try
            {
                transaction.Rollback();
            }
            catch (Exception ex2)
            {
                // This catch block will handle any errors that may have occurred
                // on the server that would cause the rollback to fail, such as
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);

            }
        }
    }
}
</code>```

Besides I find if I commit twice sequentailly will invoke this exception as well.

```<code>       transaction.Commit();
       transaction.Commit();
</code>```

Or if Connection Closed before commit also invoke this error.

```<code>       connection.Close();
       transaction.Commit();
</code>```

Update:

I find it strange that I create another new table and insert 500 thousand data to it,

then use 100000 tasks with select * from newtable sql, running 5 programs at the same time, this time the Timeout Error occur, but when transaction.Rollback() it didn't invoke the SQLTransaction has completed error.

but if the Timeout Error occur, jump into the catch block, and in the catch block do transaction.Commit() again, the SQLTransaction has completed error will happen.

Title: SQLTransaction has completed error

Body:
I got following error once in my application.

This SQLTransaction has completed; it is no longer usable

Stack Trace is attached below – It says about Zombie Check and Rollback.

What is the mistake in the code?

Note: This error came only once.

UPDATE

From MSDN - SqlTransaction.Rollback Method

A Rollback generates an InvalidOperationException if the connection is terminated or if the transaction has already been rolled back on the server.

From Zombie check on Transaction - Error

One of the most frequent reasons I have seen this error showing up in various applications is, sharing SqlConnection across our application.

CODE

public int SaveUserLogOnInfo(int empID)
{
        int? sessionID = null;
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            SqlTransaction transaction = null;
            try
            {
                transaction = connection.BeginTransaction();
                sessionID = GetSessionIDForAssociate(connection, empID, transaction);

                    //Other Code

                //Commit
                transaction.Commit();
            }
            catch
            {
                //Rollback
                if (transaction != null)
                {
                    transaction.Rollback();
                    transaction.Dispose();
                    transaction = null;
                }

                //Throw exception
                throw;
            }
            finally
            {
                if (transaction != null)
                {
                    transaction.Dispose();
                }
            }
        }

        return Convert.ToInt32(sessionID,CultureInfo.InvariantCulture);

   }

Stack Trace

REFERENCE:

What is zombie transaction?

Zombie check on Transaction - Error

SqlTransaction has completed

http://forums.asp.net/t/1579684.aspx/1

"This SqlTransaction has completed; it is no longer usable."... configuration error?

dotnet.sys-con.com - SqlClient Connection Pooling Exposed

Thread abort leaves zombie transactions and broken SqlConnection

Body:
I use code below can reproduce this error, I use 1000 tasks to execute Sql, after about 300 tasks Successfully Completed, lots of exception about timeout error start to occur on ExecuteNonQuery(),

then next error This SqlTransaction has completed will occur on transaction.RollBack(); and its call stack also contains ZombieCheck().

(If single program with 1000 tasks pressure not enough, you can execute multiple compiled exe file at the same time,  or even use multi computers execute to one DataBase.)

So I guess one of the reason cause this error can be something wrong in Connection, then cause the transaction error happens as well.

Task[] tasks = new Task[1000];
for (int i = 0; i < 1000; i++)
{
    int j = i;
    tasks[i] = new Task(() =>
         ExecuteSqlTransaction("YourConnectionString", j)
        );
}

foreach (Task task in tasks)
{
    task.Start();
}

/////////////

public void ExecuteSqlTransaction(string connectionString, int exeSqlCou)
{

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction();

        // Must assign both transaction object and connection
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "select * from Employee";
            command.ExecuteNonQuery();

            // Attempt to commit the transaction.
            transaction.Commit();

            Console.WriteLine("Execute Sql to database."
                + exeSqlCou);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
            Console.WriteLine("  Message: {0}", ex.Message);

            // Attempt to roll back the transaction.
            try
            {
                transaction.Rollback();
            }
            catch (Exception ex2)
            {
                // This catch block will handle any errors that may have occurred
                // on the server that would cause the rollback to fail, such as
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);

            }
        }
    }
}

Besides I find if I commit twice sequentailly will invoke this exception as well.

       transaction.Commit();
       transaction.Commit();

Or if Connection Closed before commit also invoke this error.

       connection.Close();
       transaction.Commit();

Update:

I find it strange that I create another new table and insert 500 thousand data to it,

then use 100000 tasks with select * from newtable sql, running 5 programs at the same time, this time the Timeout Error occur, but when transaction.Rollback() it didn't invoke the SQLTransaction has completed error.

but if the Timeout Error occur, jump into the catch block, and in the catch block do transaction.Commit() again, the SQLTransaction has completed error will happen.


问:
Can DeviceId (UDID) in android can be change in case of os upadate?
following code i have use  to get udid in android . Any chances that below method should not return unique value?</p>

```<code>  TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    String deviceId;
    if (telephonyManager.getDeviceId() != null)
        deviceId = telephonyManager.getDeviceId(); //*** use for mobiles
    else {
        deviceId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
    }
    return deviceId;
</code>```

答:
Any chances that below method should not return unique value?

AFAIK the UDID is based on the device itself. As far as I know, that means the software is irrelevant (assuming Android OS, but software here = any version of android). Meaning no, you will always get a unique ID for the device. Please note that you will always get the same UDID on the same device.

Body:
following code i have use  to get udid in android . Any chances that below method should not return unique value?

  TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    String deviceId;
    if (telephonyManager.getDeviceId() != null)
        deviceId = telephonyManager.getDeviceId(); //*** use for mobiles
    else {
        deviceId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
    }
    return deviceId;


问:
How to reach derived class variable from base class vector?
```<code>#include <iostream>
#include <vector>

class Entity
{
public:
    bool hinders_sight = false;
};

class Pillar : public Entity
{
public:
    bool hinders_sight = true;
};

int main()
{
    std::vector<Entity*> Entities;

    Pillar pillar;

    Entities.push_back(&pillar);

    std::cout << pillar.hinders_sight << std::endl;
    std::cout << Entities[0]->hinders_sight << std::endl;

    return 0;
}
</code>```

pillar.hinders_sight returns true (as it should)

but

Entities[0]->hinders_sight returns false.

How can I reach hinders_sight of pillar from the vector?

答:
What is happening right now is that there are two variables called hinders_sight in your derived class, one from the base class and another of the derived class.

There are two main approaches to solve this problem here (I would not recommend keeping two separate variables for the same thing in your base and derived classes), either you can make the variable a protected/private variable in the base class and then offer functions to get and store the variable as needed, or you can make the get_hinders_sight() function virtual.

```<code>class Entity {
public:
    Entity(bool hinders_sight_in = false)
        : hinders_sight{hinders_sight_in} {}
    bool get_hinders_sight() { return this->hinders_sight; }
private:
    bool hinders_sight = false;
};

class Pillar : public Entity {
public:
    Pillar() : Entity{true} {}
};
</code>```

Or

```<code>class Entity {
public:
    virtual bool get_hinders_sight() { return false; }
};

class Pillar : public Entity {
public:
    bool get_hinders_sight() override { return true; }
};
</code>```

Body:
#include <iostream>
#include <vector>

class Entity
{
public:
    bool hinders_sight = false;
};

class Pillar : public Entity
{
public:
    bool hinders_sight = true;
};

int main()
{
    std::vector<Entity*> Entities;

    Pillar pillar;

    Entities.push_back(&pillar);

    std::cout << pillar.hinders_sight << std::endl;
    std::cout << Entities[0]->hinders_sight << std::endl;

    return 0;
}

pillar.hinders_sight returns true (as it should)

but

Entities[0]->hinders_sight returns false.

How can I reach hinders_sight of pillar from the vector?

Body:
What is happening right now is that there are two variables called hinders_sight in your derived class, one from the base class and another of the derived class.

There are two main approaches to solve this problem here (I would not recommend keeping two separate variables for the same thing in your base and derived classes), either you can make the variable a protected/private variable in the base class and then offer functions to get and store the variable as needed, or you can make the get_hinders_sight() function virtual.

class Entity {
public:
    Entity(bool hinders_sight_in = false)
        : hinders_sight{hinders_sight_in} {}
    bool get_hinders_sight() { return this->hinders_sight; }
private:
    bool hinders_sight = false;
};

class Pillar : public Entity {
public:
    Pillar() : Entity{true} {}
};

Or

class Entity {
public:
    virtual bool get_hinders_sight() { return false; }
};

class Pillar : public Entity {
public:
    bool get_hinders_sight() override { return true; }
};


问:
Split a column into separate columns using regex
I have got a single column that includes the information as follows:

```<code>1 x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo
2 x=oljhh88999\ty=lop9876666
3 x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid
</code>```

So, none of the id types has a certain number of occurences in a line.
They are all separated by tab.
I am searching for a way to obtain the IDs for each line as separate columns and have found tstrsplit within data.table but cannot figure out how I can use it with multiple split arguments. Any ideas?

Edit: The expected format is:

```<code>     x1          x2        y1    y2                          z1                  z2
1  abc1000000   NA pqr2000000    NA         olk78fgzu_zuii8999_ikooo            NA
2  oljhh88999   NA lop9876666    NA                               NA            NA
3  frdt876544   NA ztr6u76532   uzrt899963  wertttts_765342_ioooosww  zuuuee_66554422_88uuiiid
</code>```

Note that the id's do not include 'id' in their names. So I updated the example accordingly. The id's may appear a number of times in each line. The format given above is just an example to make the question clearer. In reality, the X type of IDs for example, can have 20 occurences in one line. The number of columns for X will be then the maximum number of appearance of this particular type of ID in a line given the whole dataset. The data is pretty large. We are talking about some 30m lines.

答:
New answer:

For the updated example you could approach the problem as follows:

```<code>dt2 <- dt[, rn := .I
          ][, .(V1 = unlist(tstrsplit(V1, '\t'))), by = rn
            ][, c('id','value') := tstrsplit(V1, '=')
              ][, idn := 1:.N, by = .(rn, id)]

dcast(dt2, rn ~ id + idn, value.var = 'value', sep = '')
</code>```

which results in:

```<code>   rn         x1         y1         y2                       z1                        z2
1:  1 abc1000000 pqr2000000         NA olk78fgzu_zuii8999_ikooo                        NA
2:  2 oljhh88999 lop9876666         NA                       NA                        NA
3:  3 frdt876544 ztr6u76532 uzrt899963 wertttts_765342_ioooosww tzuuuee_66554422_88uuiiid
</code>```

To get the exact output (thus also including a x2 column), you can do:

```<code>dcast(dt2[CJ(rn = rn, id = id, idn = idn, unique = TRUE), on = .(rn, id, idn)],
      rn ~ id + idn, value.var = 'value', sep = '')
</code>```

which results in:

```<code>   rn         x1 x2         y1         y2                       z1                        z2
1:  1 abc1000000 NA pqr2000000         NA olk78fgzu_zuii8999_ikooo                        NA
2:  2 oljhh88999 NA lop9876666         NA                       NA                        NA
3:  3 frdt876544 NA ztr6u76532 uzrt899963 wertttts_765342_ioooosww tzuuuee_66554422_88uuiiid
</code>```

Used data:

```<code>dt <- fread('"x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo"
             "x=oljhh88999\ty=lop9876666"
             "x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid"',
            header=FALSE)
</code>```

Answer for the original question:

If you want to use tstrsplit, you could approach it as follows:

```<code>dt[, rn := .I
   ][, .(V1 = unlist(tstrsplit(V1, '\t'))), by = rn
     ][, .(rn, id = gsub('([a-z0-9]+)(=.*$)','\\1',V1))]
</code>```

which results in:

```<code>   rn   id
1:  1 xid1
2:  1 yid2
3:  1 zid3
4:  2 xid4
5:  2 yid5
6:  3 xid6
7:  3 yid7
8:  3 yid8
9:  3 zid9
</code>```

An alternative which results in a wide format output:

```<code>dt[, tstrsplit(V1, '\t'),
   ][, lapply(.SD, gsub, pattern = '([a-z0-9]+)(=.*$)', replacement = '\\1')]
</code>```

which results in:

```<code>     V1   V2   V3   V4
1: xid1 yid2 zid3   NA
2: xid4 yid5   NA   NA
3: xid6 yid7 yid8 zid9
</code>```

And if you want to extract all id's as @UweBlock mentioned, you could also do (though a bit less straightforward then @UweBlock's approach):

```<code>l <- regmatches(dt$V1, gregexpr('([a-z]{1}id[0-9]{1})',dt$V1))
l <- lapply(l, as.data.frame.list)
l <- lapply(l, function(x) {names(x) <- paste0('v',seq_along(x)); as.data.table(x)})

rbindlist(l, fill = TRUE)
</code>```

which results in:

```<code>     v1   v2   v3   v4   v5
1: xid1 yid2 zid3   NA   NA
2: xid4 yid5   NA   NA   NA
3: xid6 yid7 yid8 zid8 zid9
</code>```

Used data:

```<code>dt <- fread('"xid1=abc1000000\tyid2=pqr2000000\tzid3=olk78fgzu_zuii8999_ikooo"
"xid4=oljhh88999\tyid5=lop9876666"
"xid6=frdt876544\tyid7=ztr6u76532\tyid8=uzrt899963tzid8=wertttts_765342_ioooosww\tzid9=tzuuuee_66554422_88uuiiid"',header=FALSE)
</code>```

Body:
I have got a single column that includes the information as follows:

1 x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo
2 x=oljhh88999\ty=lop9876666
3 x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid

So, none of the id types has a certain number of occurences in a line.
They are all separated by tab.
I am searching for a way to obtain the IDs for each line as separate columns and have found tstrsplit within data.table but cannot figure out how I can use it with multiple split arguments. Any ideas?

Edit: The expected format is:

     x1          x2        y1    y2                          z1                  z2
1  abc1000000   NA pqr2000000    NA         olk78fgzu_zuii8999_ikooo            NA
2  oljhh88999   NA lop9876666    NA                               NA            NA
3  frdt876544   NA ztr6u76532   uzrt899963  wertttts_765342_ioooosww  zuuuee_66554422_88uuiiid

Note that the id's do not include 'id' in their names. So I updated the example accordingly. The id's may appear a number of times in each line. The format given above is just an example to make the question clearer. In reality, the X type of IDs for example, can have 20 occurences in one line. The number of columns for X will be then the maximum number of appearance of this particular type of ID in a line given the whole dataset. The data is pretty large. We are talking about some 30m lines.

Body:
New answer:

For the updated example you could approach the problem as follows:

dt2 <- dt[, rn := .I
          ][, .(V1 = unlist(tstrsplit(V1, '\t'))), by = rn
            ][, c('id','value') := tstrsplit(V1, '=')
              ][, idn := 1:.N, by = .(rn, id)]

dcast(dt2, rn ~ id + idn, value.var = 'value', sep = '')

which results in:

   rn         x1         y1         y2                       z1                        z2
1:  1 abc1000000 pqr2000000         NA olk78fgzu_zuii8999_ikooo                        NA
2:  2 oljhh88999 lop9876666         NA                       NA                        NA
3:  3 frdt876544 ztr6u76532 uzrt899963 wertttts_765342_ioooosww tzuuuee_66554422_88uuiiid

To get the exact output (thus also including a x2 column), you can do:

dcast(dt2[CJ(rn = rn, id = id, idn = idn, unique = TRUE), on = .(rn, id, idn)],
      rn ~ id + idn, value.var = 'value', sep = '')

which results in:

   rn         x1 x2         y1         y2                       z1                        z2
1:  1 abc1000000 NA pqr2000000         NA olk78fgzu_zuii8999_ikooo                        NA
2:  2 oljhh88999 NA lop9876666         NA                       NA                        NA
3:  3 frdt876544 NA ztr6u76532 uzrt899963 wertttts_765342_ioooosww tzuuuee_66554422_88uuiiid

Used data:

dt <- fread('"x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo"
             "x=oljhh88999\ty=lop9876666"
             "x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid"',
            header=FALSE)

Answer for the original question:

If you want to use tstrsplit, you could approach it as follows:

dt[, rn := .I
   ][, .(V1 = unlist(tstrsplit(V1, '\t'))), by = rn
     ][, .(rn, id = gsub('([a-z0-9]+)(=.*$)','\\1',V1))]

which results in:

   rn   id
1:  1 xid1
2:  1 yid2
3:  1 zid3
4:  2 xid4
5:  2 yid5
6:  3 xid6
7:  3 yid7
8:  3 yid8
9:  3 zid9

An alternative which results in a wide format output:

dt[, tstrsplit(V1, '\t'),
   ][, lapply(.SD, gsub, pattern = '([a-z0-9]+)(=.*$)', replacement = '\\1')]

which results in:

     V1   V2   V3   V4
1: xid1 yid2 zid3   NA
2: xid4 yid5   NA   NA
3: xid6 yid7 yid8 zid9

And if you want to extract all id's as @UweBlock mentioned, you could also do (though a bit less straightforward then @UweBlock's approach):

l <- regmatches(dt$V1, gregexpr('([a-z]{1}id[0-9]{1})',dt$V1))
l <- lapply(l, as.data.frame.list)
l <- lapply(l, function(x) {names(x) <- paste0('v',seq_along(x)); as.data.table(x)})

rbindlist(l, fill = TRUE)

which results in:

     v1   v2   v3   v4   v5
1: xid1 yid2 zid3   NA   NA
2: xid4 yid5   NA   NA   NA
3: xid6 yid7 yid8 zid8 zid9

Used data:

dt <- fread('"xid1=abc1000000\tyid2=pqr2000000\tzid3=olk78fgzu_zuii8999_ikooo"
"xid4=oljhh88999\tyid5=lop9876666"
"xid6=frdt876544\tyid7=ztr6u76532\tyid8=uzrt899963tzid8=wertttts_765342_ioooosww\tzid9=tzuuuee_66554422_88uuiiid"',header=FALSE)


问:
Error while upgrading from 1.4.4.2 to 1.4.4.3 or higher
I faced below error when I ran below commands;

meteor update --patch

ran command meteor

ERROR

```<code>D:\test>meteor update --patch

Changes to your project's package version selections from updating the
release:

accounts-base              upgraded from 1.2.17 to 1.3.0
babel-compiler             upgraded from 6.18.2 to 6.19.1
boilerplate-generator      upgraded from 1.0.11 to 1.1.0
dynamic-import             added, version 0.1.0
ecmascript                 upgraded from 0.7.3 to 0.8.0
ecmascript-runtime         upgraded from 0.3.15 to 0.4.1
ecmascript-runtime-client  added, version 0.4.1
ecmascript-runtime-server  added, version 0.4.1
localstorage               upgraded from 1.0.12 to 1.1.0
meteor-base                upgraded from 1.0.4 to 1.1.0
minifier-js                upgraded from 2.0.0 to 2.1.0
minimongo                  upgraded from 1.0.23 to 1.2.0
modules                    upgraded from 0.8.2 to 0.9.0
modules-runtime            upgraded from 0.7.10 to 0.8.0
mongo                      upgraded from 1.1.17 to 1.1.18
promise                    upgraded from 0.8.8 to 0.8.9
reactive-dict              upgraded from 1.1.8 to 1.1.9
standard-minifier-js       upgraded from 2.0.0 to 2.1.0
webapp                     upgraded from 1.3.15 to 1.3.16

test: updated to Meteor 1.4.4.3.

D:\test>meteor
[[[[[ ~\D\test ]]]]]

=> Started proxy.
=> Meteor 1.5 is available. Update this project with 'meteor update'.
=> Started MongoDB.
=> Errors prevented startup:

   While selecting package versions:
   error: Potentially incompatible change required to top-level
   dependency: meteor-base 1.0.4, was 1.1.0.
   Constraints on package "meteor-base":
   * meteor-base@1.0.4 <- top level
   * meteor-base@1.0.4 <- top level

   Potentially incompatible change required to top-level dependency:
   dynamic-import 0.1.0-beta.20, was 0.1.0.
   Constraints on package "dynamic-import":

   To allow potentially incompatible changes to top-level dependencies,
   you must pass --allow-incompatible-update on the command line.

=> Your application has errors. Waiting for file change.
</code>```

答:
if you update to meteor 1.5 with meteor update Everything will work as expected with 0 conflict.
Dont touch any files!
Worked for me, first update that actually does not break anything.

Body:
I faced below error when I ran below commands;

meteor update --patch

ran command meteor

ERROR

D:\test>meteor update --patch

Changes to your project's package version selections from updating the
release:

accounts-base              upgraded from 1.2.17 to 1.3.0
babel-compiler             upgraded from 6.18.2 to 6.19.1
boilerplate-generator      upgraded from 1.0.11 to 1.1.0
dynamic-import             added, version 0.1.0
ecmascript                 upgraded from 0.7.3 to 0.8.0
ecmascript-runtime         upgraded from 0.3.15 to 0.4.1
ecmascript-runtime-client  added, version 0.4.1
ecmascript-runtime-server  added, version 0.4.1
localstorage               upgraded from 1.0.12 to 1.1.0
meteor-base                upgraded from 1.0.4 to 1.1.0
minifier-js                upgraded from 2.0.0 to 2.1.0
minimongo                  upgraded from 1.0.23 to 1.2.0
modules                    upgraded from 0.8.2 to 0.9.0
modules-runtime            upgraded from 0.7.10 to 0.8.0
mongo                      upgraded from 1.1.17 to 1.1.18
promise                    upgraded from 0.8.8 to 0.8.9
reactive-dict              upgraded from 1.1.8 to 1.1.9
standard-minifier-js       upgraded from 2.0.0 to 2.1.0
webapp                     upgraded from 1.3.15 to 1.3.16

test: updated to Meteor 1.4.4.3.

D:\test>meteor
[[[[[ ~\D\test ]]]]]

=> Started proxy.
=> Meteor 1.5 is available. Update this project with 'meteor update'.
=> Started MongoDB.
=> Errors prevented startup:

   While selecting package versions:
   error: Potentially incompatible change required to top-level
   dependency: meteor-base 1.0.4, was 1.1.0.
   Constraints on package "meteor-base":
   * meteor-base@1.0.4 <- top level
   * meteor-base@1.0.4 <- top level

   Potentially incompatible change required to top-level dependency:
   dynamic-import 0.1.0-beta.20, was 0.1.0.
   Constraints on package "dynamic-import":

   To allow potentially incompatible changes to top-level dependencies,
   you must pass --allow-incompatible-update on the command line.

=> Your application has errors. Waiting for file change.


问:
How to prepare Ansible inventory, playbook and configuration file used by Ansible module using Ansible/Jinja2?
I have a plain-text file routers in versioning system which contains host-names separated by newlines:

```<code>$ cat routers
r1
r2
r3
$
</code>```

I also have routers configuration templates in versioning system as a plain-text files. For example:

```<code>$ cat system:syslog
system {
    syslog {
        host 10.10.10.153 {
            any notice;
            daemon info;
        }
    }
}
$
</code>```

I can't change the format of those two types of files because they are used by other systems. Now what I need, is to create Ansible inventory file from this routers file, configuration file for Ansible junos_config module from routers configuration template and finally Ansible playbook in YAML. At the moment I use a bash script for this. Simplified, it takes four arguments:

routers file

configuration template file(for example system:syslog described
above)

ticket number in ticketing system(integer)

comment string(this is used in router to describe the change)

Based on the examples above, routers file is converted to following inventory file:

```<code>junipers ansible_connection=local
[junipers]
r1
r2
r3
</code>```

system:syslog file is converted to a file name <ticket_nr>.cfg with following content:

```<code>groups {
    replace: system:syslog {
        system {
            syslog {
                host 10.10.10.153 {
                    any notice;
                    daemon info;
                }
            }
        }
    }
}
</code>```

Basically, bash script does something like this:

```<code>cat << EOF
groups {
    replace: ${templatefile##*/} {
EOF
sed 's/^/        /' "$templatefile"
cat << EOF
    }
}
EOF
</code>```

And finally playbook file is generated:

```<code>- hosts: junipers
  remote_user: admin
  tasks:
    - name: Change routers conf.
      ignore_errors: yes
      junos_config:
       comment: "<comment>"
       timeout: 60
       port: 22
       src: <ticket_nr>.cfg
       src_format: text
       replace: yes
</code>```

<comment> and <ticket_nr> are arguments given to the bash script. In addition, this bash script checks out the latest revision of mentioned routers file and configuration templates.

Now is there a better way to do all this without bash? While this works, I'm feeling that I'm doing it wrong and I'm relying heavily on bash. Is it possible to do all this in Ansible/Jinja2?

答:
```<code>$ cat system:syslog
system {
    syslog {
        host 10.10.10.153 {
            any notice;
            daemon info;
        }
    }
}
$ cat replace_sys_syslog.j2
groups {
    replace: system:syslog {
{{ conf }}
    }
}
$ cat example.py
from jinja2 import Template

tmpl = Template(open('replace_sys_syslog.j2').read())
conf = tmpl.render(conf=open('system:syslog').read())
print conf
$ python example.py
groups {
    replace: system:syslog {
system {
    syslog {
        host 10.10.10.153 {
            any notice;
            daemon info;
        }
    }
}

    }
}
</code>```

Now using these template file, Ansible task can generate config.

Body:
I have a plain-text file routers in versioning system which contains host-names separated by newlines:

$ cat routers
r1
r2
r3
$

I also have routers configuration templates in versioning system as a plain-text files. For example:

$ cat system:syslog
system {
    syslog {
        host 10.10.10.153 {
            any notice;
            daemon info;
        }
    }
}
$

I can't change the format of those two types of files because they are used by other systems. Now what I need, is to create Ansible inventory file from this routers file, configuration file for Ansible junos_config module from routers configuration template and finally Ansible playbook in YAML. At the moment I use a bash script for this. Simplified, it takes four arguments:

routers file

configuration template file(for example system:syslog described
above)

ticket number in ticketing system(integer)

comment string(this is used in router to describe the change)

Based on the examples above, routers file is converted to following inventory file:

junipers ansible_connection=local
[junipers]
r1
r2
r3

system:syslog file is converted to a file name <ticket_nr>.cfg with following content:

groups {
    replace: system:syslog {
        system {
            syslog {
                host 10.10.10.153 {
                    any notice;
                    daemon info;
                }
            }
        }
    }
}

Basically, bash script does something like this:

cat << EOF
groups {
    replace: ${templatefile##*/} {
EOF
sed 's/^/        /' "$templatefile"
cat << EOF
    }
}
EOF

And finally playbook file is generated:

- hosts: junipers
  remote_user: admin
  tasks:
    - name: Change routers conf.
      ignore_errors: yes
      junos_config:
       comment: "<comment>"
       timeout: 60
       port: 22
       src: <ticket_nr>.cfg
       src_format: text
       replace: yes

<comment> and <ticket_nr> are arguments given to the bash script. In addition, this bash script checks out the latest revision of mentioned routers file and configuration templates.

Now is there a better way to do all this without bash? While this works, I'm feeling that I'm doing it wrong and I'm relying heavily on bash. Is it possible to do all this in Ansible/Jinja2?

Body:
$ cat system:syslog
system {
    syslog {
        host 10.10.10.153 {
            any notice;
            daemon info;
        }
    }
}
$ cat replace_sys_syslog.j2
groups {
    replace: system:syslog {
{{ conf }}
    }
}
$ cat example.py
from jinja2 import Template

tmpl = Template(open('replace_sys_syslog.j2').read())
conf = tmpl.render(conf=open('system:syslog').read())
print conf
$ python example.py
groups {
    replace: system:syslog {
system {
    syslog {
        host 10.10.10.153 {
            any notice;
            daemon info;
        }
    }
}

    }
}

Now using these template file, Ansible task can generate config.


问:
How can I change the color of each button separately in UIAlertSheet?
How to replace the color of a single button in the AlertSheet?

答:
If you are looking to use a destructive button you can change the style to destructive.

The below example will make delete red;

```<code>self.optionAlertController.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { (action: UIAlertAction!) in
</code>```

Body:
If you are looking to use a destructive button you can change the style to destructive.

The below example will make delete red;

self.optionAlertController.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { (action: UIAlertAction!) in