问:
Is there a way to get a difference report on two Jet (.mdb) databases?
I have code that depends a relatively small MS Jet (created in Access) database. Our source control process is far from all that it could/should be (which is a problem that needs to be solved immediately) and we have ended up with two versions of the same database. The person who edited the "other" version is no longer around to give me hints about what he changed. What is the best way to find the differences of the actual data contained in two versions of a database?</p>

答:
Ther are tools that can do this like: http://www.fmsinc.com/MicrosoftAccess/DatabaseCompare.html

Or you can look at created / modified dates to see if that gives you a clue (change the database window to show details)

Or you can run the Tools / Analyze / Documenter and look at the object properties.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: DJ


来源: stackexchange

问:
How can I most easily do IPC/RPC between Cocoa (client) and Java (server) running on the same host?
The Java end is a Bukkit plugin, so I don't have the freedom to build on a servlet engine like Tomcat. I don't need arbitrary access to any object; I just want to expose a subset of functionality available to plugins to my wrapper application.

The Cocoa application, I am building from the ground up, so the restrictions are a bit looser. It's a wrapper for the server with limited support for configuring certain plugins.

Something that can communicate over Unix sockets would be ideal since the processes are running on a single host, but TCP sockets are ok too. I'm not really picky. If I end up using TCP then I'll consider adding support for remote management, but it's not a priority. I don't want Unix sockets badly enough to bother with all the hoops I'd have to jump through to use them.

答:
Java does not support UNIX sockets out-of-the box, but this question gives some alternatives.

Or you can just open a tcp socket on localhost to keep in the standard library.

There are a lot of solutions out there, but if you want to stay lean and mean, a simple socket is not too bad. All the boxed solutions are quite complex, as they need to deal with complex issues over the net. You will face only a small subset of these, so might be better of with a simple home-grown protocol over a socket.

Just make it asynchronous to avoid blocking.

ContentLicense: CC BY-SA 3.0


问:
Adjust spacing around paragraph (within a div) so that the space on either side is always equal between divs on the right and left
I have three divs, aligned on a single row as columns, using a flex container.

The first and third columns have a small amount of text in each, the middle column has a large paragraph.

What I would like to do is to align the text in the middle div so that the space around between it and the first and third divs is always equal, even when the width of the page changes and the words wrap to the next line.

By default, the word wrapping behaviour means that you can end up with a lot of whitespace on the right of the div, which isn't equal to the whitespace on the left (because of the varying length of words). How do I ensure the spacing adjusts based on the longest word (I assume the longest word), so it it always equal?

Here is some example code:

.container {
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <div class="column1">
    <p>
      Some content
    </p>
  </div>

  <div class="column2">
    <p>
      There is more content in this div than the other divs. Blah, blah, blah, blah, blah, blah...
    </p>
  </div>

  <div class="column3">
    <p>
      Some content
    </p>
  </div>

</div></code>```

If you expand and shrink the window, you can see that as the middle column's words get closer to wrapping, the spacing isn't equal on either side of the div; there is less space on the right than the left. This what I would like to resolve, so the spacing is always equal between the divs.

答:
There is no completely satisfying solution for what you describe. justify-content: space-between on the container is the closest you will get. Or you use justify-content: space-around - maybe that's closer to what you are aiming at (hard to tell from your description...):

.container {
  display: flex;
  justify-content: space-around;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <div class="column1">
    <p>
      Some content
    </p>
  </div>

  <div class="column2">
    <p>
      There is more content in this div than the other divs. Blah, blah, blah, blah, blah, blah...
    </p>
  </div>

  <div class="column3">
    <p>
      Some content
    </p>
  </div>

</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have three divs, aligned on a single row as columns, using a flex container.

The first and third columns have a small amount of text in each, the middle column has a large paragraph.

What I would like to do is to align the text in the middle div so that the space around between it and the first and third divs is always equal, even when the width of the page changes and the words wrap to the next line.

By default, the word wrapping behaviour means that you can end up with a lot of whitespace on the right of the div, which isn't equal to the whitespace on the left (because of the varying length of words). How do I ensure the spacing adjusts based on the longest word (I assume the longest word), so it it always equal?

Here is some example code:

.container {
  display: flex;
}

      Some content

      There is more content in this div than the other divs. Blah, blah, blah, blah, blah, blah...

      Some content

If you expand and shrink the window, you can see that as the middle column's words get closer to wrapping, the spacing isn't equal on either side of the div; there is less space on the right than the left. This what I would like to resolve, so the spacing is always equal between the divs.

Body:
There is no completely satisfying solution for what you describe. justify-content: space-between on the container is the closest you will get. Or you use justify-content: space-around - maybe that's closer to what you are aiming at (hard to tell from your description...):

.container {
  display: flex;
  justify-content: space-around;
}

<div class="container">

  <div class="column1">
    <p>
      Some content
    </p>
  </div>

  <div class="column2">
    <p>
      There is more content in this div than the other divs. Blah, blah, blah, blah, blah, blah...
    </p>
  </div>

  <div class="column3">
    <p>
      Some content
    </p>
  </div>

</div>


问:
Move folder matching a specific name into another folder?
Could someone provide me with a simple example how to use App Script to move a folder matching a specific name (not ID) into another folder inside Google Drive?

I have searched the existing threads but couldn't find anything specific to matching a specific folder name.

答:
I believe your goal as follows.

You want to move a folder to other folder in your Google Drive using Google Apps Script.

For this, how about this answer? In your case, when the parent folder of the folder is moved, all files and sub folders in the folder can be moved. So the script can be simpler than the script for copying files. This has already been mentioned by Cooper's comment.

The sample script is as follows. As the input values, the source folder name and destination folder ID are used.

Sample script:

In this sample script, Drive service is used.

```<code>function myFunction() {
  const sourceFolderName = "###";  // Please set the source folder name.
  const destinationFolderId = "###";  // Please set the destination folder ID.

  const src = DriveApp.getFoldersByName(sourceFolderName);
  if (src.hasNext()) {
    const srcFol = src.next();
    srcFol.getParents().next().removeFolder(srcFol);
    DriveApp.getFolderById(destinationFolderId).addFolder(srcFol);
  }
}
</code>```

Note:

When Drive API is used, the script becomes as follows.

```<code>function myFunction() {
  const sourceFolderName = "###";  // Please set the source folder name.
  const destinationFolderId = "###";  // Please set the destination folder ID.

  const src = DriveApp.getFoldersByName(sourceFolderName);
  if (src.hasNext()) {
    Drive.Files.patch({parents: [{id: destinationFolderId}]}, src.next().getId());
  }
}
</code>```

References:

removeFolder(child)

addFolder(child)

Body:
I believe your goal as follows.

You want to move a folder to other folder in your Google Drive using Google Apps Script.

For this, how about this answer? In your case, when the parent folder of the folder is moved, all files and sub folders in the folder can be moved. So the script can be simpler than the script for copying files. This has already been mentioned by Cooper's comment.

The sample script is as follows. As the input values, the source folder name and destination folder ID are used.

Sample script:

In this sample script, Drive service is used.

function myFunction() {
  const sourceFolderName = "###";  // Please set the source folder name.
  const destinationFolderId = "###";  // Please set the destination folder ID.

  const src = DriveApp.getFoldersByName(sourceFolderName);
  if (src.hasNext()) {
    const srcFol = src.next();
    srcFol.getParents().next().removeFolder(srcFol);
    DriveApp.getFolderById(destinationFolderId).addFolder(srcFol);
  }
}

Note:

When Drive API is used, the script becomes as follows.

function myFunction() {
  const sourceFolderName = "###";  // Please set the source folder name.
  const destinationFolderId = "###";  // Please set the destination folder ID.

  const src = DriveApp.getFoldersByName(sourceFolderName);
  if (src.hasNext()) {
    Drive.Files.patch({parents: [{id: destinationFolderId}]}, src.next().getId());
  }
}

References:

removeFolder(child)

addFolder(child)


问:
Unable to Align 2 Cardviews Vertically Inside RecyclerView
I have 2 CardViews and a RecyclerView but i am

unable to align them vertically

unable to slide them independently (both slide if I slide any one in a bugged workaround)

I tried a few workarounds as well as different tutorials like edmt Dev and CodingWithMitch as well as searched for similar problems on stackoverflow but the problem seems to persist. So how do I align both of the cardviews vertically while still being able to slide each of them independently and horizontally.

(Code works fine for single card view)

Main Activity:

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

List<Articles> articlesData;

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

    articlesData = new ArrayList<>();

    //Repeats
    articlesData.add(new Articles("10 Necessary Gadgets","Gadgets","Gadgets You Must Carry",R.drawable.bagchaincustom));
    articlesData.add(new Articles("10 Benefits of Pre-Planning the Day","Self Improvement","Benefits of Planning in Advance",R.drawable.planner1custom));

    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false);
    RecyclerView recyclerView = findViewById(R.id.recyclerview);
    recyclerView.setLayoutManager(layoutManager);
    RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, articlesData);
    recyclerView.setAdapter(adapter);

}
</code>```

Here is activity_main.xml:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerview"
        android:orientation="horizontal">
        </androidx.recyclerview.widget.RecyclerView>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Here is the RecyclerViewAdapter Class:

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

private static final int LAYOUT_ONE= 0;
private static final int LAYOUT_TWO= 1;

@Override
public int getItemViewType(int position)
{
    if(position == LAYOUT_ONE){
        return LAYOUT_TWO;
    }
    else {
        return LAYOUT_ONE;
    }
}

private static final String Tag = "RecyclerViewAdapter";
private Context mContext;
private List<Articles> mData;

public RecyclerViewAdapter(Context mContext, List<Articles> mData) {
    this.mContext = mContext;
    this.mData = mData;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    LayoutInflater mInflater = LayoutInflater.from(mContext);
    View view;

    switch (viewType) {
        case 0:
            ViewHolder1 viewHolder1;
            view = mInflater.inflate(R.layout.layout_listitem, parent, false);
            return new ViewHolder1(view);

        case 1:
            ViewHolder2 viewHolder2;
            view = mInflater.inflate(R.layout.layout_listitem2, parent, false);
            return new ViewHolder2(view);

        default:
            return null;
    }

}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {

    switch (holder.getItemViewType()){
        case 0:
            ViewHolder1 viewHolder1 = (ViewHolder1)holder;
        viewHolder1.tv_article_title.setText(mData.get(position).getTitle());
            viewHolder1.img_article_thumbnail.setImageResource(mData.get(position).getThumbnail());
            viewHolder1.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ArticlesActivity.class);
                intent.putExtra("Title", mData.get(position).getTitle());
                intent.putExtra("Description", mData.get(position).getDescription());
                intent.putExtra("Thumbnail", mData.get(position).getThumbnail());
                intent.putExtra("Category", mData.get(position).getCategory());
                mContext.startActivity(intent);
            }
        });
        break;

        case 1:
            ViewHolder2 viewHolder2 = (ViewHolder2)holder;
            viewHolder2.tv_article_title2.setText(mData.get(position).getTitle());
            viewHolder2.img_article_thumbnail2.setImageResource(mData.get(position).getThumbnail());
            viewHolder2.cardView2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, ArticlesActivity.class);
                    intent.putExtra("Title", mData.get(position).getTitle());
                    intent.putExtra("Description", mData.get(position).getDescription());
                    intent.putExtra("Thumbnail", mData.get(position).getThumbnail());
                    intent.putExtra("Category", mData.get(position).getCategory());
                    mContext.startActivity(intent);
                }
            });
            break;

    }
}

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

public class ViewHolder1 extends RecyclerView.ViewHolder{
    TextView tv_article_title;
    ImageView img_article_thumbnail;
    CardView cardView;

    public ViewHolder1(@NonNull View itemView) {
        super(itemView);
        tv_article_title = (TextView) itemView.findViewById(R.id.article_title_id);
        img_article_thumbnail = (ImageView) itemView.findViewById((R.id.article_image_id));
        cardView = (CardView) itemView.findViewById(R.id.cardview_id);

    }
}

public class ViewHolder2 extends RecyclerView.ViewHolder{
    TextView tv_article_title2;
    ImageView img_article_thumbnail2;
    CardView cardView2;

    public ViewHolder2(@NonNull View itemView) {
        super(itemView);
        tv_article_title2 = (TextView) itemView.findViewById(R.id.article_title_id2);
        img_article_thumbnail2 = (ImageView) itemView.findViewById((R.id.article_image_id2));
        cardView2 = (CardView) itemView.findViewById(R.id.cardview_id2);

    }
}

}
</code>```

Here is the Articles Class:

```<code>public class Articles {

private String Title;
private String Category;
private String Description;
private int Thumbnail;

public Articles(String title, String category, String description, int thumbnail) {
    Title = title;
    Category = category;
    Description = description;
    Thumbnail = thumbnail;
}

public String getTitle() {
    return Title;
}

public String getCategory() {
    return Category;
}

public String getDescription() {
    return Description;
}

public int getThumbnail() {
    return Thumbnail;
}
</code>```

And here is the CardView -> layout_listitem Layout:

```<code>    <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:layout_alignParentStart="true"
    android:id="@+id/rview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

<androidx.cardview.widget.CardView 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/cardview_id"
    android:layout_width="120dp"
    android:layout_height="220dp"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground"
    app:cardCornerRadius="0dp"
    app:cardElevation="0dp">

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/article_image_id"
            android:layout_width="match_parent"
            android:layout_height="160dp"
            android:background="#2d2d2d"
            android:scaleType="centerCrop"></ImageView>

        <TextView
            android:id="@+id/article_title_id"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal"
            android:gravity="center"
            android:text="Article Name"
            android:textSize="14sp">

        </TextView>

    </LinearLayout>

</androidx.cardview.widget.CardView>

</LinearLayout>
</code>```

And here is the CardView -> layout_listitem2 Layout:

```<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:layout_alignParentStart="true"
    android:id="@+id/rview2"
    android:layout_below="@+id/rview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="300dp">

    <androidx.cardview.widget.CardView 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/cardview_id2"
        android:layout_below="@id/cardview_id"
        android:layout_width="120dp"
        android:layout_height="220dp"
        android:clickable="true"
        android:foreground="?android:attr/selectableItemBackground"
        app:cardCornerRadius="0dp"
        app:cardElevation="0dp">

        <LinearLayout
            android:layout_marginTop="250dp"
            android:layout_alignParentBottom="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="10dp"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/article_image_id2"
                android:layout_width="match_parent"
                android:layout_height="160dp"
                android:background="#2d2d2d"
                android:scaleType="centerCrop"></ImageView>

            <TextView
                android:id="@+id/article_title_id2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center_horizontal"
                android:gravity="center"
                android:text="Article Name Sec"
                android:textSize="14sp">

            </TextView>

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>
</code>```

答: ConstraintLayout is not a scrolling parent, so it will create problem if you add a long RecyclerView inside it.</p>

Body:
I have 2 CardViews and a RecyclerView but i am

unable to align them vertically

unable to slide them independently (both slide if I slide any one in a bugged workaround)

I tried a few workarounds as well as different tutorials like edmt Dev and CodingWithMitch as well as searched for similar problems on stackoverflow but the problem seems to persist. So how do I align both of the cardviews vertically while still being able to slide each of them independently and horizontally.

(Code works fine for single card view)

Main Activity:

public class MainActivity extends AppCompatActivity {

List<Articles> articlesData;

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

    articlesData = new ArrayList<>();

    //Repeats
    articlesData.add(new Articles("10 Necessary Gadgets","Gadgets","Gadgets You Must Carry",R.drawable.bagchaincustom));
    articlesData.add(new Articles("10 Benefits of Pre-Planning the Day","Self Improvement","Benefits of Planning in Advance",R.drawable.planner1custom));

    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false);
    RecyclerView recyclerView = findViewById(R.id.recyclerview);
    recyclerView.setLayoutManager(layoutManager);
    RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, articlesData);
    recyclerView.setAdapter(adapter);

}

Here is activity_main.xml:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerview"
        android:orientation="horizontal">
        </androidx.recyclerview.widget.RecyclerView>

</androidx.constraintlayout.widget.ConstraintLayout>

Here is the RecyclerViewAdapter Class:

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

private static final int LAYOUT_ONE= 0;
private static final int LAYOUT_TWO= 1;

@Override
public int getItemViewType(int position)
{
    if(position == LAYOUT_ONE){
        return LAYOUT_TWO;
    }
    else {
        return LAYOUT_ONE;
    }
}

private static final String Tag = "RecyclerViewAdapter";
private Context mContext;
private List<Articles> mData;

public RecyclerViewAdapter(Context mContext, List<Articles> mData) {
    this.mContext = mContext;
    this.mData = mData;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    LayoutInflater mInflater = LayoutInflater.from(mContext);
    View view;

    switch (viewType) {
        case 0:
            ViewHolder1 viewHolder1;
            view = mInflater.inflate(R.layout.layout_listitem, parent, false);
            return new ViewHolder1(view);

        case 1:
            ViewHolder2 viewHolder2;
            view = mInflater.inflate(R.layout.layout_listitem2, parent, false);
            return new ViewHolder2(view);

        default:
            return null;
    }

}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {

    switch (holder.getItemViewType()){
        case 0:
            ViewHolder1 viewHolder1 = (ViewHolder1)holder;
        viewHolder1.tv_article_title.setText(mData.get(position).getTitle());
            viewHolder1.img_article_thumbnail.setImageResource(mData.get(position).getThumbnail());
            viewHolder1.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ArticlesActivity.class);
                intent.putExtra("Title", mData.get(position).getTitle());
                intent.putExtra("Description", mData.get(position).getDescription());
                intent.putExtra("Thumbnail", mData.get(position).getThumbnail());
                intent.putExtra("Category", mData.get(position).getCategory());
                mContext.startActivity(intent);
            }
        });
        break;

        case 1:
            ViewHolder2 viewHolder2 = (ViewHolder2)holder;
            viewHolder2.tv_article_title2.setText(mData.get(position).getTitle());
            viewHolder2.img_article_thumbnail2.setImageResource(mData.get(position).getThumbnail());
            viewHolder2.cardView2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, ArticlesActivity.class);
                    intent.putExtra("Title", mData.get(position).getTitle());
                    intent.putExtra("Description", mData.get(position).getDescription());
                    intent.putExtra("Thumbnail", mData.get(position).getThumbnail());
                    intent.putExtra("Category", mData.get(position).getCategory());
                    mContext.startActivity(intent);
                }
            });
            break;

    }
}

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

public class ViewHolder1 extends RecyclerView.ViewHolder{
    TextView tv_article_title;
    ImageView img_article_thumbnail;
    CardView cardView;

    public ViewHolder1(@NonNull View itemView) {
        super(itemView);
        tv_article_title = (TextView) itemView.findViewById(R.id.article_title_id);
        img_article_thumbnail = (ImageView) itemView.findViewById((R.id.article_image_id));
        cardView = (CardView) itemView.findViewById(R.id.cardview_id);

    }
}

public class ViewHolder2 extends RecyclerView.ViewHolder{
    TextView tv_article_title2;
    ImageView img_article_thumbnail2;
    CardView cardView2;

    public ViewHolder2(@NonNull View itemView) {
        super(itemView);
        tv_article_title2 = (TextView) itemView.findViewById(R.id.article_title_id2);
        img_article_thumbnail2 = (ImageView) itemView.findViewById((R.id.article_image_id2));
        cardView2 = (CardView) itemView.findViewById(R.id.cardview_id2);

    }
}

}

Here is the Articles Class:

public class Articles {

private String Title;
private String Category;
private String Description;
private int Thumbnail;

public Articles(String title, String category, String description, int thumbnail) {
    Title = title;
    Category = category;
    Description = description;
    Thumbnail = thumbnail;
}

public String getTitle() {
    return Title;
}

public String getCategory() {
    return Category;
}

public String getDescription() {
    return Description;
}

public int getThumbnail() {
    return Thumbnail;
}

And here is the CardView -> layout_listitem Layout:

    <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:layout_alignParentStart="true"
    android:id="@+id/rview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

<androidx.cardview.widget.CardView 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/cardview_id"
    android:layout_width="120dp"
    android:layout_height="220dp"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground"
    app:cardCornerRadius="0dp"
    app:cardElevation="0dp">

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/article_image_id"
            android:layout_width="match_parent"
            android:layout_height="160dp"
            android:background="#2d2d2d"
            android:scaleType="centerCrop"></ImageView>

        <TextView
            android:id="@+id/article_title_id"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal"
            android:gravity="center"
            android:text="Article Name"
            android:textSize="14sp">

        </TextView>

    </LinearLayout>

</androidx.cardview.widget.CardView>

</LinearLayout>

And here is the CardView -> layout_listitem2 Layout:

<?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:layout_alignParentStart="true"
    android:id="@+id/rview2"
    android:layout_below="@+id/rview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="300dp">

    <androidx.cardview.widget.CardView 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/cardview_id2"
        android:layout_below="@id/cardview_id"
        android:layout_width="120dp"
        android:layout_height="220dp"
        android:clickable="true"
        android:foreground="?android:attr/selectableItemBackground"
        app:cardCornerRadius="0dp"
        app:cardElevation="0dp">

        <LinearLayout
            android:layout_marginTop="250dp"
            android:layout_alignParentBottom="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="10dp"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/article_image_id2"
                android:layout_width="match_parent"
                android:layout_height="160dp"
                android:background="#2d2d2d"
                android:scaleType="centerCrop"></ImageView>

            <TextView
                android:id="@+id/article_title_id2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center_horizontal"
                android:gravity="center"
                android:text="Article Name Sec"
                android:textSize="14sp">

            </TextView>

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>


问:
How to get a text label before a daterangepicker in plotly dash?
This should be just a matter of putting text in front and making the div inline block or something like that.

Want it to look like "DATE: ". Using html.Div fails and puts things on separate lines even with the DATE inside the 2nd Div.

```<code>from datetime import datetime as dt
import dash
import dash_html_components as html
import dash_core_components as dcc
import re

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
    dcc.DatePickerRange(
        id='my-date-picker-range',
        min_date_allowed=dt(1995, 8, 5),
        max_date_allowed=dt(2017, 9, 19),
        initial_visible_month=dt(2017, 8, 5),
        end_date=dt(2017, 8, 25).date()
    ),
    html.Div(id='output-container-date-picker-range')
])

@app.callback(
    dash.dependencies.Output('output-container-date-picker-range', 'children'),
    [dash.dependencies.Input('my-date-picker-range', 'start_date'),
     dash.dependencies.Input('my-date-picker-range', 'end_date')])
def update_output(start_date, end_date):
    string_prefix = 'You have selected: '
    if start_date is not None:
        start_date = dt.strptime(re.split('T| ', start_date)[0], '%Y-%m-%d')
        start_date_string = start_date.strftime('%B %d, %Y')
        string_prefix = string_prefix + 'Start Date: ' + start_date_string + ' | '
    if end_date is not None:
        end_date = dt.strptime(re.split('T| ', end_date)[0], '%Y-%m-%d')
        end_date_string = end_date.strftime('%B %d, %Y')
        string_prefix = string_prefix + 'End Date: ' + end_date_string
    if len(string_prefix) == len('You have selected: '):
        return 'Select a date to see it displayed here'
    else:
        return string_prefix

if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

答:
Is this layout working for you?

app.layout = html.Div([
    html.Div(["DATE: ",
    dcc.DatePickerRange(
        id='my-date-picker-range',
        min_date_allowed=dt(1995, 8, 5),
        max_date_allowed=dt(2017, 9, 19),
        initial_visible_month=dt(2017, 8, 5),
        end_date=dt(2017, 8, 25).date()
    )],
    style={'width': '49%', 'display': 'inline-block'}),
    html.Div(id='output-container-date-picker-range')
])
```

The trick is adding another Div with two elements and the inline-block style.

Body:
This should be just a matter of putting text in front and making the div inline block or something like that.

Want it to look like "DATE: ". Using html.Div fails and puts things on separate lines even with the DATE inside the 2nd Div.

from datetime import datetime as dt
import dash
import dash_html_components as html
import dash_core_components as dcc
import re

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
    dcc.DatePickerRange(
        id='my-date-picker-range',
        min_date_allowed=dt(1995, 8, 5),
        max_date_allowed=dt(2017, 9, 19),
        initial_visible_month=dt(2017, 8, 5),
        end_date=dt(2017, 8, 25).date()
    ),
    html.Div(id='output-container-date-picker-range')
])

@app.callback(
    dash.dependencies.Output('output-container-date-picker-range', 'children'),
    [dash.dependencies.Input('my-date-picker-range', 'start_date'),
     dash.dependencies.Input('my-date-picker-range', 'end_date')])
def update_output(start_date, end_date):
    string_prefix = 'You have selected: '
    if start_date is not None:
        start_date = dt.strptime(re.split('T| ', start_date)[0], '%Y-%m-%d')
        start_date_string = start_date.strftime('%B %d, %Y')
        string_prefix = string_prefix + 'Start Date: ' + start_date_string + ' | '
    if end_date is not None:
        end_date = dt.strptime(re.split('T| ', end_date)[0], '%Y-%m-%d')
        end_date_string = end_date.strftime('%B %d, %Y')
        string_prefix = string_prefix + 'End Date: ' + end_date_string
    if len(string_prefix) == len('You have selected: '):
        return 'Select a date to see it displayed here'
    else:
        return string_prefix

if __name__ == '__main__':
    app.run_server(debug=True)

Body:
Is this layout working for you?

app.layout = html.Div([
    html.Div(["DATE: ",
    dcc.DatePickerRange(
        id='my-date-picker-range',
        min_date_allowed=dt(1995, 8, 5),
        max_date_allowed=dt(2017, 9, 19),
        initial_visible_month=dt(2017, 8, 5),
        end_date=dt(2017, 8, 25).date()
    )],
    style={'width': '49%', 'display': 'inline-block'}),
    html.Div(id='output-container-date-picker-range')
])

The trick is adding another Div with two elements and the inline-block style.


问:
Is there an easy way to disable linux logs on kubernetes pod containers?
I have a go based application deployed on a kubernetes cluster.

I am using   golang:1.13 as my base image

The /var/log folders on those containers keep filling up causing the pods to evict.

Is there a way where I could specify something in deployment.yaml or something like that where I disable system logs from being written to file system?

答: You should probably have some kind of log rotation system set up, most installers do it. But failing that, if you want to disable collection of container output to log files you can do that in your Dockerd configuration, usually it's set up in the systemd unit file for dockerd but the specifics depend on your deployment.</p>


问:
How to get the name of the file that triggered the Azure Data Factory pipeline?
I am new to ADF. I have a requirement to load the data from 15 CSV files to 15 Azure Sql database tables.
In the pipeline there is a trigger to run the pipeline every time a blob is created.

I would like to make this pipeline dynamic. My CSV file name contains the tablename.
Example, Input_202005 is the csv and the table name is Input.

Similarly, I have 14 other files/tables whose metadata is different.

Because I want to run the pipeline every time there a blob is created, I do not need a metadata and a foreachfile activity. I want the pipelines to run in parallel for each blob. Is there a way to know which blob/file triggered the pipeline and to get the name of the file without using any parameters in the trigger. I do not want to use 15 trigger parameters.

Or is there a better solution for my requirement? Any suggestions are appreciated.

答:
Add a parameter to your pipeline, say, triggeringFile.

When you create the trigger, a form pops-out on the right side - after submitting the first page, a second page pops-out - this will ask for a value for the pipeline parameter triggeringFile.  In that box, put @trigger().outputs.body.fileName

If the format you gave is the standard then your table name is just @{split(pipeline().parameters.triggeringFile,'_')[0]}


问:
replace na values in rows
I was trying to replace the na values in all rows of a column with a specific character.
The column name is called 'morph'. I tried to replace na values with the character 'nul' and the R code I tried is:

```<code>data$morph[which(is.na(data$morph))] <- nul.
</code>```

An error turned out indicating that

"Error: object 'nul' not found".

What's wrong with my code and how to fix it? Thanks for answering my questions.

答:
If we need to replace then use a character string</p>

```<code>data$morph[which(is.na(data$morph))] <- "null"
</code>```

Title: replace na values in rows

Body:
I was trying to replace the na values in all rows of a column with a specific character.
The column name is called 'morph'. I tried to replace na values with the character 'nul' and the R code I tried is:

data$morph[which(is.na(data$morph))] <- nul.

An error turned out indicating that

"Error: object 'nul' not found".

What's wrong with my code and how to fix it? Thanks for answering my questions.

Body:
If we need to replace then use a character string

data$morph[which(is.na(data$morph))] <- "null"


问:
Java servlet not dispatching to another servlet
I have 2 servlets, "HomeController" and "SearchController". On the home.jsp I have a form that has a search box and when submitted actions to "Search"

```<code> <form action="Search" method="post" name="searchForm">
</code>```

So the first thing the SearchController does is:

```<code> @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!validator.isValidAlphaOnly(request.getParameter("breed"))) {
        request.setAttribute("error", "Breed search term invalid. Enter only letters");
        RequestDispatcher requestVar =  request.getRequestDispatcher("/Home");
        requestVar.forward(request, response);
    } else {
        processRequest(request, response);
    }
}
</code>```

Except is doesn't go to /Home even though I have mappings as follows:

```<code>  <servlet>
    <servlet-name>HomeController</servlet-name>
    <servlet-class>Controllers.HomeController</servlet-class>
</servlet>
<servlet>
    <servlet-name>SearchController</servlet-name>
    <servlet-class>Controllers.SearchController</servlet-class>
</servlet>
<servlet>
    <servlet-name>DogController</servlet-name>
    <servlet-class>Controllers.DogController</servlet-class>
</servlet>
<servlet>
    <servlet-name>LogoutController</servlet-name>
    <servlet-class>Controllers.LogoutController</servlet-class>
</servlet>
<servlet>
    <servlet-name>UpdateController</servlet-name>
    <servlet-class>Controllers.UpdateController</servlet-class>
</servlet>
<servlet>
    <servlet-name>AddController</servlet-name>
    <servlet-class>Controllers.AddController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SearchController</servlet-name>
    <url-pattern>/Search</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>LogoutController</servlet-name>
    <url-pattern>/Logout</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>UpdateController</servlet-name>
    <url-pattern>/Update</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>AddController</servlet-name>
    <url-pattern>/Add</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>DogController</servlet-name>
    <url-pattern>/Dog/View/*</url-pattern>
    <url-pattern>/Dog/Edit/*</url-pattern>
    <url-pattern>/Dog/Add</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>HomeController</servlet-name>
    <url-pattern>/Home</url-pattern>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</code>```

答:
You can use getNamedDispatcher:</p>

```<code>ServletContext context = getServletContext();
RequestDispatcher requestVar = context.getNamedDispatcher("HomeController");
</code>```

Body:
I have 2 servlets, "HomeController" and "SearchController". On the home.jsp I have a form that has a search box and when submitted actions to "Search"

 <form action="Search" method="post" name="searchForm">

So the first thing the SearchController does is:

 @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!validator.isValidAlphaOnly(request.getParameter("breed"))) {
        request.setAttribute("error", "Breed search term invalid. Enter only letters");
        RequestDispatcher requestVar =  request.getRequestDispatcher("/Home");
        requestVar.forward(request, response);
    } else {
        processRequest(request, response);
    }
}

Except is doesn't go to /Home even though I have mappings as follows:

  <servlet>
    <servlet-name>HomeController</servlet-name>
    <servlet-class>Controllers.HomeController</servlet-class>
</servlet>
<servlet>
    <servlet-name>SearchController</servlet-name>
    <servlet-class>Controllers.SearchController</servlet-class>
</servlet>
<servlet>
    <servlet-name>DogController</servlet-name>
    <servlet-class>Controllers.DogController</servlet-class>
</servlet>
<servlet>
    <servlet-name>LogoutController</servlet-name>
    <servlet-class>Controllers.LogoutController</servlet-class>
</servlet>
<servlet>
    <servlet-name>UpdateController</servlet-name>
    <servlet-class>Controllers.UpdateController</servlet-class>
</servlet>
<servlet>
    <servlet-name>AddController</servlet-name>
    <servlet-class>Controllers.AddController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SearchController</servlet-name>
    <url-pattern>/Search</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>LogoutController</servlet-name>
    <url-pattern>/Logout</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>UpdateController</servlet-name>
    <url-pattern>/Update</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>AddController</servlet-name>
    <url-pattern>/Add</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>DogController</servlet-name>
    <url-pattern>/Dog/View/*</url-pattern>
    <url-pattern>/Dog/Edit/*</url-pattern>
    <url-pattern>/Dog/Add</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>HomeController</servlet-name>
    <url-pattern>/Home</url-pattern>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Body:
You can use getNamedDispatcher:

ServletContext context = getServletContext();
RequestDispatcher requestVar = context.getNamedDispatcher("HomeController");


问:
Track time taken to scale up in Kubernetes using HPA and CA
I am trying to track and monitor, how much time does a pod take to come online/healthy/Running.

I am using EKS. And I have got HPA and cluster-autoscaler installed on  my cluster.

Let's say I have a deployment with HorizontalPodAutoscaler scaling policy with 70% targetAverageUtilization.

So whenever the average utilization of deployment will go beyond 70%, HPA will trigger to create new POD. Now, based on different factors, like if nodes are available or not, and if not is already available, then the image needs to be downloaded or is it present on cache, the scaling can take from few seconds to few minutes to come up.

I want to track this time/duration, every time the POD is scheduled, how much time does it take to come to Running state. Any suggestions?

Or any direction where I should be looking at.

I found this Cluster Autoscaler Visibility Logs, but this is only available in GCE.

I am looking for any solution, can be out-of-the-box integration, or raising events and storing them in some time-series DB or scraping data from Prometheus. But I couldn't find any solution for this till now.

Thanks in advance.

答: There is nothing out of the box for this, you will need to build something yourself.</p>


问:
Swift NOT operator (~) prints different values than when used
Swift bitwise NOT operator (~) inverts all bits in a number.

The docs provide the example:

```<code>let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits  // equals 11110000
</code>```

And I can confirm this by printing a String:

```<code>print(String(invertedBits, radix: 2)) // equals 11110000
</code>```

Given this logic I would expect ~0 to equal 1 and ~1 to equal 0. However printing these as I did above print something unexpected:

```<code> print(String(~0b1, radix: 2)) // equals -10
 print(String(~0b0, radix: 2)) // equals -1
</code>```

When in use I see something different:

```<code>print(String(0b100 & ~0b111, radix: 2)) // equals 0 just as I would expect 100 & 000  to equal 000
</code>```

but

```<code>print(String(~0b111, radix: 2)) // equals -1000
</code>```

~0b111 seems to act as if it were 0b000 but it prints as -1000

What's going on here?

答:
In the documentation provided example, initialBits has an explicit type. What is happening can be shown by the following code

```<code>let number = 0b1 // we don't specify a type, therefore it's inferred

print(type(of: number))           // Int
print(String(~number, radix: 2))  // -10 as you know

print(number.bitWidth)            // 64 because integers have 64 bits

// now if we create a 64 bit number, we can see what happened
// prints -10 because this number is equivalent to the initial number
print(String(~0b0000000000000000000000000000000000000000000000000000000000000001, radix: 2))
</code>```

Body:
Swift bitwise NOT operator (~) inverts all bits in a number.

The docs provide the example:

let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits  // equals 11110000

And I can confirm this by printing a String:

print(String(invertedBits, radix: 2)) // equals 11110000

Given this logic I would expect ~0 to equal 1 and ~1 to equal 0. However printing these as I did above print something unexpected:

 print(String(~0b1, radix: 2)) // equals -10
 print(String(~0b0, radix: 2)) // equals -1

When in use I see something different:

print(String(0b100 & ~0b111, radix: 2)) // equals 0 just as I would expect 100 & 000  to equal 000

but

print(String(~0b111, radix: 2)) // equals -1000

~0b111 seems to act as if it were 0b000 but it prints as -1000

What's going on here?

Body:
In the documentation provided example, initialBits has an explicit type. What is happening can be shown by the following code

let number = 0b1 // we don't specify a type, therefore it's inferred

print(type(of: number))           // Int
print(String(~number, radix: 2))  // -10 as you know

print(number.bitWidth)            // 64 because integers have 64 bits

// now if we create a 64 bit number, we can see what happened
// prints -10 because this number is equivalent to the initial number
print(String(~0b0000000000000000000000000000000000000000000000000000000000000001, radix: 2))


问:
Merging two almost identical strings
I have two objects, one which is a list of tuples with (int, str), like this:

```<code>first_input = [
    (0  ,  "Lorem ipsum dolor sit amet, consectetur"),
    (1  ,  " adipiscing elit"),
    (0  ,  ". In pellentesque\npharetra ex, at varius sem suscipit ac. "),
    (-1 ,  "Suspendisse luctus\ncondimentum velit a laoreet. "),
    (0  ,  "Donec dolor urna, tempus sed nulla vitae, dignissim varius neque.")
]
# Note that the strings contain newlines `\n` on purpose.
</code>```

The other object is a string, which is the result of a series of operations(*) which, by design, will result in a concatenation of all the strings above but with some additional newlines \n inserted.

(* : that can't be done while conserving the list of tuples structure, obviously)

For instance:

```<code>second_input = "Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit. In pellentesque\npharetra ex, at varius sem\nsuscipit ac. Suspendisse luctus\ncondimentum velit a laoreet. Donec dolor urna, tempus sed\nnulla vitae, dignissim varius neque."
# Note that there are 3 new newlines,  here ^ for instance
# but also in "sem\nsuscipit" and "sed\nnulla"
</code>```

My goal is to go back to the first structure, but keeping the additional newlines. So in my example, I would get:

```<code>expected_output = [
    (0  ,  "Lorem ipsum dolor sit amet,\nconsectetur"),  # new newline here
    (1  ,  " adipiscing elit"),
    (0  ,  ". In pellentesque\npharetra ex, at varius sem\nsuscipit ac. "), # new newline here
    (-1 ,  "Suspendisse luctus\ncondimentum velit a laoreet. "),
    (0  ,  "Donec dolor urna, tempus sed\nnulla vitae, dignissim varius neque.") # new newline here
]
</code>```

Do you have a smart way to do it, other than reconstructing the string with a character by character comparison?

(NB: I don't care in which of the two tuples it ends if a new \n is at the limit of a string. E.g. getting [(0, "foo\n"), (1, "bar")] or [(0, "foo"), (1, "\nbar")] doesn't matter.)

Edit: what I want to avoid, is to do something like this:

```<code>position=0
output = []
for tup in first_input:
    reconstructed_string = ""
    for letter in tup[1]:
        if letter == second_input[position]:
            reconstructed_string = reconstructed_string + letter
        else:
            reconstructed_string = reconstructed_string + second_input[position]
        position +=1
    output.append((tup[0], reconstructed_string))
# Note: this is hastily written to give you an idea, I have no idea if it would work properly, probably not
# Well, it does seem to work without bug, at least in my example. That's unexpected lol. Anyway, if you can think of a better solution...!
</code>```

That is, going through each character of the strings and compare them to reconstruct the strings character by character.

答:
Ok, considering that NO CHARACTERS are replaced or modified (as the OP stated), here's what I could come up to:

first_input_no_newline = list(map(lambda x: (x[0], x[1].replace('\n', '')), first_input))

expected_output = []
for item in first_input_no_newline:
    next_index = len(item[1])

    second_input_copy = second_input
    offset = 0
    while True:
        amount = second_input_copy[:next_index].count("\n")
        if not amount:
            next_index += offset
            break
        offset += amount
        second_input_copy = second_input_copy.replace('\n', '', amount)

    expected_output.append((item[0], second_input[:next_index]))
    second_input = second_input[next_index:]

print(expected_output)
```

<p>Explaining: you don't have to keep track of the newlines or anything like that. Also the newlines in "first_input" doesn't really matter, because we have all of them in the second input (plus more of them).</p>

<p>So, just take the length of each item of <code>first_input_no_newline</code>, this should also be the length of the substring in <code>second_input</code> if there were no newlines in it but, if there are newlines, ok, just keep counting and removing them from a copy of the second_input and add this result as an offset to cut the original second_input.</p>

<p>Input sample (fixed OP's original input, adding the missing white characters in between some phrases):</p>

<pre class="lang-py prettyprint-override"><code>first_input = [
        (0, "Lorem ipsum dolor sit amet, consectetur"),
        (1, " adipiscing elit"),
        (0, ". In pellentesque\npharetra ex, at varius sem suscipit ac. "),
        (-1, "Suspendisse luctus\ncondimentum velit a laoreet. "),
        (0, "Donec dolor urna, tempus sed nulla vitae, dignissim varius neque.")
    ]

second_input = "Lorem ipsum dolor sit amet, \nconsectetur adipiscing elit. In pellentesque\npharetra ex, at varius sem \nsuscipit ac. Suspendisse luctus\ncondimentum velit a laoreet. Donec dolor urna, tempus sed \nnulla vitae, dignissim varius neque."

</code>```

Output:

[
    (0, 'Lorem ipsum dolor sit amet, \nconsectetur'),
    (1, ' adipiscing elit'),
    (0, '. In pellentesque\npharetra ex, at varius sem \nsuscipit ac. '),
    (-1, 'Suspendisse luctus\ncondimentum velit a laoreet. '),
    (0, 'Donec dolor urna, tempus sed \nnulla vitae, dignissim varius neque.')
]

```

Title: Merging two almost identical strings

Body:
I have two objects, one which is a list of tuples with (int, str), like this:

first_input = [
    (0  ,  "Lorem ipsum dolor sit amet, consectetur"),
    (1  ,  " adipiscing elit"),
    (0  ,  ". In pellentesque\npharetra ex, at varius sem suscipit ac. "),
    (-1 ,  "Suspendisse luctus\ncondimentum velit a laoreet. "),
    (0  ,  "Donec dolor urna, tempus sed nulla vitae, dignissim varius neque.")
]
# Note that the strings contain newlines `\n` on purpose.

The other object is a string, which is the result of a series of operations(*) which, by design, will result in a concatenation of all the strings above but with some additional newlines \n inserted.

(* : that can't be done while conserving the list of tuples structure, obviously)

For instance:

second_input = "Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit. In pellentesque\npharetra ex, at varius sem\nsuscipit ac. Suspendisse luctus\ncondimentum velit a laoreet. Donec dolor urna, tempus sed\nnulla vitae, dignissim varius neque."
# Note that there are 3 new newlines,  here ^ for instance
# but also in "sem\nsuscipit" and "sed\nnulla"

My goal is to go back to the first structure, but keeping the additional newlines. So in my example, I would get:

expected_output = [
    (0  ,  "Lorem ipsum dolor sit amet,\nconsectetur"),  # new newline here
    (1  ,  " adipiscing elit"),
    (0  ,  ". In pellentesque\npharetra ex, at varius sem\nsuscipit ac. "), # new newline here
    (-1 ,  "Suspendisse luctus\ncondimentum velit a laoreet. "),
    (0  ,  "Donec dolor urna, tempus sed\nnulla vitae, dignissim varius neque.") # new newline here
]

Do you have a smart way to do it, other than reconstructing the string with a character by character comparison?

(NB: I don't care in which of the two tuples it ends if a new \n is at the limit of a string. E.g. getting [(0, "foo\n"), (1, "bar")] or [(0, "foo"), (1, "\nbar")] doesn't matter.)

Edit: what I want to avoid, is to do something like this:

position=0
output = []
for tup in first_input:
    reconstructed_string = ""
    for letter in tup[1]:
        if letter == second_input[position]:
            reconstructed_string = reconstructed_string + letter
        else:
            reconstructed_string = reconstructed_string + second_input[position]
        position +=1
    output.append((tup[0], reconstructed_string))
# Note: this is hastily written to give you an idea, I have no idea if it would work properly, probably not
# Well, it does seem to work without bug, at least in my example. That's unexpected lol. Anyway, if you can think of a better solution...!

That is, going through each character of the strings and compare them to reconstruct the strings character by character.

Body:
Ok, considering that NO CHARACTERS are replaced or modified (as the OP stated), here's what I could come up to:

first_input_no_newline = list(map(lambda x: (x[0], x[1].replace('\n', '')), first_input))

expected_output = []
for item in first_input_no_newline:
    next_index = len(item[1])

    second_input_copy = second_input
    offset = 0
    while True:
        amount = second_input_copy[:next_index].count("\n")
        if not amount:
            next_index += offset
            break
        offset += amount
        second_input_copy = second_input_copy.replace('\n', '', amount)

    expected_output.append((item[0], second_input[:next_index]))
    second_input = second_input[next_index:]

print(expected_output)

Explaining: you don't have to keep track of the newlines or anything like that. Also the newlines in "first_input" doesn't really matter, because we have all of them in the second input (plus more of them).

So, just take the length of each item of first_input_no_newline, this should also be the length of the substring in second_input if there were no newlines in it but, if there are newlines, ok, just keep counting and removing them from a copy of the second_input and add this result as an offset to cut the original second_input.

Input sample (fixed OP's original input, adding the missing white characters in between some phrases):

first_input = [
        (0, "Lorem ipsum dolor sit amet, consectetur"),
        (1, " adipiscing elit"),
        (0, ". In pellentesque\npharetra ex, at varius sem suscipit ac. "),
        (-1, "Suspendisse luctus\ncondimentum velit a laoreet. "),
        (0, "Donec dolor urna, tempus sed nulla vitae, dignissim varius neque.")
    ]

second_input = "Lorem ipsum dolor sit amet, \nconsectetur adipiscing elit. In pellentesque\npharetra ex, at varius sem \nsuscipit ac. Suspendisse luctus\ncondimentum velit a laoreet. Donec dolor urna, tempus sed \nnulla vitae, dignissim varius neque."

Output:

[
    (0, 'Lorem ipsum dolor sit amet, \nconsectetur'),
    (1, ' adipiscing elit'),
    (0, '. In pellentesque\npharetra ex, at varius sem \nsuscipit ac. '),
    (-1, 'Suspendisse luctus\ncondimentum velit a laoreet. '),
    (0, 'Donec dolor urna, tempus sed \nnulla vitae, dignissim varius neque.')
]


问:
XMLHttpRequest setRequestHeader Error
IE 9 developer tools say "Unspecified error." at this line of code:

```<code>xmlhttp.setRequestHeader ("If-Modified-Since", "Sat 1 Jan 2005 00:00:00 GMT");
</code>```

I am trying to disable caching of Ajax requests and I don't have control over the server and I cannot append a unique ID to the end of each request, so this looks like my only option. Any ideas why Javascript doesn't like it?

答:
I was calling this before xmlhttp.open (...);. That was the mistake. Modify the header after you open the request, but before you send it.

```<code>xmlhttp.open (...);
xmlhttp.setRequestHeader ("...", "...");
xmlhttp.send ();
</code>```

Title: XMLHttpRequest setRequestHeader Error

Body:
IE 9 developer tools say "Unspecified error." at this line of code:

xmlhttp.setRequestHeader ("If-Modified-Since", "Sat 1 Jan 2005 00:00:00 GMT");

I am trying to disable caching of Ajax requests and I don't have control over the server and I cannot append a unique ID to the end of each request, so this looks like my only option. Any ideas why Javascript doesn't like it?

Body:
I was calling this before xmlhttp.open (...);. That was the mistake. Modify the header after you open the request, but before you send it.

xmlhttp.open (...);
xmlhttp.setRequestHeader ("...", "...");
xmlhttp.send ();


问:
Identifying an 11 digit timestamp
I've been working with a dataset from a client that contains 11 digits as a timestamp. Here are some examples:

The only clues I have are that the dates are supposed to be for the year 2013, and that days_spent is the difference between date_admitted and date_discharged in number of days.

Any pointers would be much appreciated!

答:
My best guess is that these are tenths of a second.  So, divide by ten and add this as a number of seconds to 1970-01-01.

In standard SQL, you could convert them as:

```<code>select date '1970-01-01' + (date_admitted / 10) * interval '1 second'
</code>```

This is possible in any database, but the syntax varies.

Title: Identifying an 11 digit timestamp

Body:
My best guess is that these are tenths of a second.  So, divide by ten and add this as a number of seconds to 1970-01-01.

In standard SQL, you could convert them as:

select date '1970-01-01' + (date_admitted / 10) * interval '1 second'

This is possible in any database, but the syntax varies.


问:
UISlider that snaps to a fixed number of steps (like Text Size in the iOS 7 Settings app)
I'm trying to create a UISlider that lets you choose from an array of numbers. Each slider position should be equidistant and the slider should snap to each position, rather than smoothly slide between them. (This is the behavior of the slider in Settings > General > Text Size, which was introduced in iOS 7.)

The numbers I want to choose from are: -3, 0, 2, 4, 7, 10, and 12.

(I'm very new to Objective-C, so a complete code example would be much more helpful than a code snippet. =)

答:
If anyone also needs snaping animation then can do the following:

Uncheck the continuous update of the slider from the storyboard.

You can do the same from swift slider.isContinuous = false

Add the following @IBAction in your ViewController:

   @IBAction func sliderMoved(_ slider: UISlider){

        let stepCount = 10

        let roundedCurrent = (slider.value/Float(stepCount)).rounded()
        let newValue = Int(roundedCurrent) * stepCount

        slider.setValue(Float(newValue), animated: true)
    }
```

I was inspired by this answer

Body:
If anyone also needs snaping animation then can do the following:

Uncheck the continuous update of the slider from the storyboard.

You can do the same from swift slider.isContinuous = false

Add the following @IBAction in your ViewController:

   @IBAction func sliderMoved(_ slider: UISlider){

        let stepCount = 10

        let roundedCurrent = (slider.value/Float(stepCount)).rounded()
        let newValue = Int(roundedCurrent) * stepCount

        slider.setValue(Float(newValue), animated: true)
    }

I was inspired by this answer


问:
How does LazyFrames from OpenAI's baselines save memory?
OpenAI's baselines use the following code to return a LazyFrames instead of a concatenated numpy array to save memory. The idea is to take the advantage of the fact that a numpy array can be saved at different lists at the same time as lists only save a reference not object itself. However, in the implementation of LazyFrames, it further saves the concatenated numpy array in self._out, in that case if every LazyFrames object has been invoked at least once, it will always save a concatenated numpy array within it, which does not seem to save any memory at all. Then what's the point of LazeFrames? Or do I misunderstand anything?

class FrameStack(gym.Wrapper):
    def __init__(self, env, k):
        """Stack k last frames.

        Returns lazy array, which is much more memory efficient.

        See Also
        --------
        baselines.common.atari_wrappers.LazyFrames
        """
        gym.Wrapper.__init__(self, env)
        self.k = k
        self.frames = deque([], maxlen=k)
        shp = env.observation_space.shape
        self.observation_space = spaces.Box(low=0, high=255, shape=(shp[:-1] + (shp[-1] * k,)), dtype=env.observation_space.dtype)

    def reset(self):
        ob = self.env.reset()
        for _ in range(self.k):
            self.frames.append(ob)
        return self._get_ob()

    def step(self, action):
        ob, reward, done, info = self.env.step(action)
        self.frames.append(ob)
        return self._get_ob(), reward, done, info

    def _get_ob(self):
        assert len(self.frames) == self.k
        return LazyFrames(list(self.frames))

class LazyFrames(object):
    def __init__(self, frames):
        """This object ensures that common frames between the observations are only stored once.
        It exists purely to optimize memory usage which can be huge for DQN's 1M frames replay
        buffers.

        This object should only be converted to numpy array before being passed to the model.

        You'd not believe how complex the previous solution was."""
        self._frames = frames
        self._out = None

    def _force(self):
        if self._out is None:
            self._out = np.concatenate(self._frames, axis=-1)
            self._frames = None
        return self._out

    def __array__(self, dtype=None):
        out = self._force()
        if dtype is not None:
            out = out.astype(dtype)
        return out

    def __len__(self):
        return len(self._force())

    def __getitem__(self, i):
        return self._force()[i]

    def count(self):
        frames = self._force()
        return frames.shape[frames.ndim - 1]

    def frame(self, i):
        return self._force()[..., I]
```

答:
I actually came here trying to understand how this saved any memory at all! But you mention that the lists store references to the underlying data, while the numpy arrays store copies of that data, and I think you are correct about that.

To answer your question, you are right! When _force is called, it populates the self._out item with a numpy array, thereby expanding the memory. But until you call _force (which is called in any of the API functions of the LazyFrame), self._out is None. So the idea is to not call _force (and therefore, don't call any of the LazyFrames methods) until you need the underlying data, hence the warning in its doc string of "This object should only be converted to numpy array before being passed to the model".

Note that when self._out gets populated by the array, it also clears the self._frames, so that it doesn't store duplicate information (thereby harming its whole purpose of storing only as much as it needs).

Also, in the same file, you'll find the ScaledFloatFrame which carries this doc string:

```<code>    Scales the observations by 255 after converting to float.
    This will undo the memory optimization of LazyFrames,
    so don't use it with huge replay buffers.
</code>```

Body:
I actually came here trying to understand how this saved any memory at all! But you mention that the lists store references to the underlying data, while the numpy arrays store copies of that data, and I think you are correct about that.

To answer your question, you are right! When _force is called, it populates the self._out item with a numpy array, thereby expanding the memory. But until you call _force (which is called in any of the API functions of the LazyFrame), self._out is None. So the idea is to not call _force (and therefore, don't call any of the LazyFrames methods) until you need the underlying data, hence the warning in its doc string of "This object should only be converted to numpy array before being passed to the model".

Note that when self._out gets populated by the array, it also clears the self._frames, so that it doesn't store duplicate information (thereby harming its whole purpose of storing only as much as it needs).

Also, in the same file, you'll find the ScaledFloatFrame which carries this doc string:

    Scales the observations by 255 after converting to float.
    This will undo the memory optimization of LazyFrames,
    so don't use it with huge replay buffers.


问:
In codepen, Intersection observer has different behavior from browser window
If I write this codes in separate HTML, CSS and Javascript files and open it with a browser, sticky sharebar appears when the target observed in middle of viewport height, but in codepen appears when the target observed in bottom of viewport height. What is the reason?</p>

```<code>{
    class StickyShareBar {
        constructor(element) {
            this.element = element;
            this.contentTarget = document.getElementsByClassName('js-sticky-sharebar-target');
            this.showClass = 'sticky-sharebar--on-target';
            this.threshold = '50%';
            this.initShareBar();
        }

        initShareBar() {
            if(this.contentTarget.length < 1) {
              this.element.addClass( this.showClass);
              return;
            }
            if(intersectionObserverSupported) {
              this.initObserver();
            } else {
              this.element.addClass(this.showClass);
            }
        }

        initObserver() {
            const self = this;
            var observer = new IntersectionObserver(
              function(entries, observer) {
                self.element.classList.toggle( self.showClass, entries[0].isIntersecting);
              },
              {
               rootMargin: "0px 0px -"+this.threshold+" 0px"}
            );
            observer.observe(this.contentTarget[0]);
        }
    }

    const stickyShareBar = document.getElementsByClassName('js-sticky-sharebar'),
      intersectionObserverSupported = ('IntersectionObserver' in window && 'IntersectionObserverEntry' in window && 'intersectionRatio' in window.IntersectionObserverEntry.prototype);

    new StickyShareBar(stickyShareBar[0]);
}
</code>```

答:
It's because of the targeted element. When the srcollbar can reach the targeted element ( js-sticky-sharebar-target ) then the event is fired. When the content container width is smaller the scroll wheel can't reach the targeted element. For this reason it's not showing on browser or small screens. I have changed the targeted element and placed it on the top. Now it's working as you expected.

Changed HTML:

```<code><div class="container new-js-sticky-sharebar-target">
</code>```

Changed JS:

```<code>this.contentTarget = document.getElementsByClassName('new-js-sticky-sharebar-target');
</code>```

See Demo

Body:
If I write this codes in separate HTML, CSS and Javascript files and open it with a browser, sticky sharebar appears when the target observed in middle of viewport height, but in codepen appears when the target observed in bottom of viewport height. What is the reason?

{
    class StickyShareBar {
        constructor(element) {
            this.element = element;
            this.contentTarget = document.getElementsByClassName('js-sticky-sharebar-target');
            this.showClass = 'sticky-sharebar--on-target';
            this.threshold = '50%';
            this.initShareBar();
        }

        initShareBar() {
            if(this.contentTarget.length < 1) {
              this.element.addClass( this.showClass);
              return;
            }
            if(intersectionObserverSupported) {
              this.initObserver();
            } else {
              this.element.addClass(this.showClass);
            }
        }

        initObserver() {
            const self = this;
            var observer = new IntersectionObserver(
              function(entries, observer) {
                self.element.classList.toggle( self.showClass, entries[0].isIntersecting);
              },
              {
               rootMargin: "0px 0px -"+this.threshold+" 0px"}
            );
            observer.observe(this.contentTarget[0]);
        }
    }

    const stickyShareBar = document.getElementsByClassName('js-sticky-sharebar'),
      intersectionObserverSupported = ('IntersectionObserver' in window && 'IntersectionObserverEntry' in window && 'intersectionRatio' in window.IntersectionObserverEntry.prototype);

    new StickyShareBar(stickyShareBar[0]);
}

Body:
It's because of the targeted element. When the srcollbar can reach the targeted element ( js-sticky-sharebar-target ) then the event is fired. When the content container width is smaller the scroll wheel can't reach the targeted element. For this reason it's not showing on browser or small screens. I have changed the targeted element and placed it on the top. Now it's working as you expected.

Changed HTML:

<div class="container new-js-sticky-sharebar-target">

Changed JS:

this.contentTarget = document.getElementsByClassName('new-js-sticky-sharebar-target');

See Demo


问:
Laravel dependency injection without relying on the controller
I'm trying to figure out how to inject a dependency into a class in Laravel.

My structure:

```<code>SimpleController extends BaseController
{
    public function example(SimpleModel $model, SimpleValidationRequest $request)
    {
        $result = $model->doStuff()
        return $this->makeResponse($result);
    }
}

SimpleModel extends Model
{
    public function doStuff(ComplexService $service)
    {
        $service->doComplexLogic($this);
    }
}
</code>```

I have registered the ComplexService in my own service provider:

```<code>class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(ComplexService::class);
    }
}
</code>```

I want to inject the service straight into the simpleModel's doStuff method, without having to inject it into the controller and then into the model. We're busy moving a monolithic application to Laravel and have service classes that contain all the complex business logic. Much of the logic is shared between different classes, so a controller method might call a model that calls a service that ends up making 4 or 5 calls to other services, and I want to be able to inject another service into any method that needs it without having to send it down from the controller all the way through to the bottom method that might need it.

Is there a way to do this? I have been looking online but everything I've found has required me to inject the service into the controller and then sending it through the application from there, which I want to avoid.

答:
You can simply call the singleton inside the method via the app() helper

SimpleModel extends Model
{
    public function doStuff(ComplexService $service)
    {
        app()->singleton(ComplexService::class)->doComplexLogic($this);
    }
}
```

or recover the singleton by injecting it in the model via it's __construct() method.

Body:
I'm trying to figure out how to inject a dependency into a class in Laravel.

My structure:

SimpleController extends BaseController
{
    public function example(SimpleModel $model, SimpleValidationRequest $request)
    {
        $result = $model->doStuff()
        return $this->makeResponse($result);
    }
}

SimpleModel extends Model
{
    public function doStuff(ComplexService $service)
    {
        $service->doComplexLogic($this);
    }
}

I have registered the ComplexService in my own service provider:

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(ComplexService::class);
    }
}

I want to inject the service straight into the simpleModel's doStuff method, without having to inject it into the controller and then into the model. We're busy moving a monolithic application to Laravel and have service classes that contain all the complex business logic. Much of the logic is shared between different classes, so a controller method might call a model that calls a service that ends up making 4 or 5 calls to other services, and I want to be able to inject another service into any method that needs it without having to send it down from the controller all the way through to the bottom method that might need it.

Is there a way to do this? I have been looking online but everything I've found has required me to inject the service into the controller and then sending it through the application from there, which I want to avoid.

Body:
You can simply call the singleton inside the method via the app() helper

SimpleModel extends Model
{
    public function doStuff(ComplexService $service)
    {
        app()->singleton(ComplexService::class)->doComplexLogic($this);
    }
}

or recover the singleton by injecting it in the model via it's __construct() method.


问:
Core Data: setPrimitiveValue and saving changes
In Core Data, is there some trick to saving changes to managed objects' attributes when the changes were made with setPrimitiveValue versus the object's regular accessor methods?

I've switched to using setPrimitiveValue and setPrimitiveAttributeName in a few scenarios in order to avoid triggering my FRC's notification methods (controllerWillChangeContent, controllerDidChangeObject, etc.).  In both cases, after making changes to the core data objects and saving the managed object context, the changes look like they were made (i.e I can see the changes with NSLog) but they are actually lost (i.e. if I exit the application in the simulator and rerun it, the FRC reloads, and the attributes I thought I changed are gone).

The save code is copied from Apple examples, and the managed object classes for my Core Data entities  are as-generated by Xcode.  Everything I've read from Apple and on this site suggests this is a valid use of the setPrimitive methods, though I admit I must be lacking a some understanding of how these setPrimitive functions really work...

Code:

```<code>// header file for Managed Object sub class generated by xcode from my core data entity:
#import <CoreData/CoreData.h>
@interface PlannedItem :  NSManagedObject
{
}

@property (nonatomic, retain) NSNumber * ptType;
@property (nonatomic, retain) NSNumber * whenOrder;
@end

// .m file for Managed Object subclass
#import "PlannedItem.h"
@implementation PlannedItem

@dynamic ptType;
@dynamic whenOrder;

@end

// trying to use setPrimitiveValue or even setPrimitiveWhenOrder to modify
// this is in my view controller
// p is a pointer to PlannedItem
int oldOrder = [p.whenOrder intValue];
[p setPrimitiveValue:[NSNumber numberWithInt:(oldOrder +1)] forKey:@"whenOrder"];

// later on in same method, save is executed.
if (![[self managedObjectContext] save:&error]) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}
NSLog(@"Saved");
</code>```

Thanks for any tips

答:
If you don't want the code in the notification handlers to execute (BTW, why would you want that?), it might be easier to disable that, instead of completely avoiding the notifications. Also, remember that Core Data uses those notifications to update your relationships and maintain coherence in your model when you make changes.

In your view controller, setup a boolean and set it according to your need to execute the notification handler code or not. Then, in your handlers check that flag, e.g.:

```<code>- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    if (notificationIgnored) {
        return;
    }
    // rest of the code...
}
</code>```

Body:
In Core Data, is there some trick to saving changes to managed objects' attributes when the changes were made with setPrimitiveValue versus the object's regular accessor methods?

I've switched to using setPrimitiveValue and setPrimitiveAttributeName in a few scenarios in order to avoid triggering my FRC's notification methods (controllerWillChangeContent, controllerDidChangeObject, etc.).  In both cases, after making changes to the core data objects and saving the managed object context, the changes look like they were made (i.e I can see the changes with NSLog) but they are actually lost (i.e. if I exit the application in the simulator and rerun it, the FRC reloads, and the attributes I thought I changed are gone).

The save code is copied from Apple examples, and the managed object classes for my Core Data entities  are as-generated by Xcode.  Everything I've read from Apple and on this site suggests this is a valid use of the setPrimitive methods, though I admit I must be lacking a some understanding of how these setPrimitive functions really work...

Code:

// header file for Managed Object sub class generated by xcode from my core data entity:
#import <CoreData/CoreData.h>
@interface PlannedItem :  NSManagedObject
{
}

@property (nonatomic, retain) NSNumber * ptType;
@property (nonatomic, retain) NSNumber * whenOrder;
@end

// .m file for Managed Object subclass
#import "PlannedItem.h"
@implementation PlannedItem

@dynamic ptType;
@dynamic whenOrder;

@end

// trying to use setPrimitiveValue or even setPrimitiveWhenOrder to modify
// this is in my view controller
// p is a pointer to PlannedItem
int oldOrder = [p.whenOrder intValue];
[p setPrimitiveValue:[NSNumber numberWithInt:(oldOrder +1)] forKey:@"whenOrder"];

// later on in same method, save is executed.
if (![[self managedObjectContext] save:&error]) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}
NSLog(@"Saved");

Thanks for any tips

Body:
If you don't want the code in the notification handlers to execute (BTW, why would you want that?), it might be easier to disable that, instead of completely avoiding the notifications. Also, remember that Core Data uses those notifications to update your relationships and maintain coherence in your model when you make changes.

In your view controller, setup a boolean and set it according to your need to execute the notification handler code or not. Then, in your handlers check that flag, e.g.:

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    if (notificationIgnored) {
        return;
    }
    // rest of the code...
}


问:
Some packages can be imported others cannot. Why?
The packages I installed work perfectly in Jupyter Notebooks but when I try importing the same packages in Sublime Text I get the following error message:

```<code>ImportError: No module named flask
</code>```

Interestingly, some packages (like matplotlib and numpy) import with no problem but some (like flask and networkx) do not.
I am currently on Python Version 3.7.6 and I have tried sudo & pip3 install.

Anyone have any idea what is happening?

答:
That sounds like you've installed those packages in the environment in which Jupyter is running, but not in the environment where Sublime Text is running.

In order to be able to use different combinations of packages on different projects, python packages are often installed into an environment (often "virtual environment", though there can be others). It sounds like flask and networkx were installed that way, so you only get them from your Jupiter "project" but not your Sublime Text "project". The matplotlib and numpy libraries are probably installed by default.

Two solutions, depending on the circumstances:

Change the configuration in Jupyter and/or Sublime Text so they use the same environment (so they're the same project). This is most practical if you have them both running on the same computer, because you'll be sure of having the same versions of the same packages used in both places.

OR

Repeat the installation of flask and networkx in the Sublime Text environment. This will mean they're separate projects, but may be most practical if you're unsure of the setup, or if Jupyter is running on a different computer than Sublime Text. You'll have to make sure you match any package upgrades or installations in the future.

Body:
The packages I installed work perfectly in Jupyter Notebooks but when I try importing the same packages in Sublime Text I get the following error message:

ImportError: No module named flask

Interestingly, some packages (like matplotlib and numpy) import with no problem but some (like flask and networkx) do not.
I am currently on Python Version 3.7.6 and I have tried sudo & pip3 install.

Anyone have any idea what is happening?


问:
Invalid token when using Apple Push Notifications (APN) for Passbook
I am trying to create a server-side implementation for passbook APN, but the server does not like the push token that the device is giving me.  If I send the token to Apple's sandbox server, it sends me an "invalid token" response.  If I send the token to Apple's production server, it returns the token in the feedback service as one that I should remove from my list.  At least I know that the APN certificates and connection to the server work fine.

My iPhone 4s has been enabled for development.  The APP ID is enabled for both development and production and the device is enabled in the provisioning profiles.  I have verified that the 32 byte binary token data is correct with respect to the string token that is sent from the device.

One question that I have is, how does passbook in the device determine which token to use (development vs production)?  I would prefer to be using the sandbox environment right now, but I'm not sure how to "select" it.

I have seen similar topics for this but none seem to have the answer for this issue.  It is really frustrating as I feel that I'm so close to making this work!  Thanks in advance for any advice!

答:
I stuck in a hour and I find a way to fix it:
In xcode 11: project setting -> singing & Capabilities -> (+) -> background -> tick Remote notifications. </p>


问:
is there any risk using std::addressof(std::cout) instead of &std::cout?
I am using std::cout for logging and sonarqube reports error when "Don't take the address of 'cout', call it from a lambda instead".

```<code>std::ostream *streamp;
streamp = &std::cout;
</code>```

When I use the below code there is no error observed in sonarqube. Is using std::addressof on std::cout function safe?

```<code>std::ostream *streamp;
streamp = std::addressof(std::cout);
</code>```

答:
The difference between &x and std::addressof(x) (for variables of class type) only occurs if x has an overloaded & operator.

addressof is for "no, no, I really want the address of this thing, no matter what the class designer has decreed".

That being said, 99++% of the time &x is fine. It's certainly fine for cout, since you can look and see that it doesn't have an operator &.

Body:
I am using std::cout for logging and sonarqube reports error when "Don't take the address of 'cout', call it from a lambda instead".

std::ostream *streamp;
streamp = &std::cout;

When I use the below code there is no error observed in sonarqube. Is using std::addressof on std::cout function safe?

std::ostream *streamp;
streamp = std::addressof(std::cout);


问:
jquery choosing methods
I love using the hide()  and show() methods, but I've come across someone's scripting where they never use it.

Instead I see them using attr() for anything related to display.

```<code>$("#element").attr("style", "visibility:hidden");
$("#element").attr("style", "visibility:visible");
</code>```

Is this just purely preferential?

Or is it more beneficial to use one vs the other?

答:
There is a difference. Take .hide() for example:

This is roughly equivalent to calling .css('display', 'none'), (...)

visibility and display are two different CSS properties. Using visibility: hidden; leaves space for the element in the layout but does not display it.

Another (minor) difference is that calling .attr("style", '...') will override all other styles that might be set on the element.

Title: jquery choosing methods

Body:
I love using the hide()  and show() methods, but I've come across someone's scripting where they never use it.

Instead I see them using attr() for anything related to display.

$("#element").attr("style", "visibility:hidden");
$("#element").attr("style", "visibility:visible");

Is this just purely preferential?

Or is it more beneficial to use one vs the other?


问:
Sequence of numbers, loop does not work with the chosen input
I have to print the same number of times that I enter (var number) example: if I put 21 it has to give me 21 numbers to print.

Currently if I put 20 it gives me exactly 20 (all good) but if I put 21 it gives me 3 more not 1 (which is what it should give me) if I put 23 it doesn't give me anything.

1º = 10
2º = 8

3º Sum of the 2 previous elements: (10 + 8 = 18)

4º The element twice before (8) is multiplied by 3 and divided by 2 and the whole part is taken: (8 * 3/2 = 12)

5º The element 2 times before is divided by 2 and the whole part is taken. (2/18 = 9)

and the process is repeated from the 3rd element.
y se vuelve a repetir el proceso desde el elemento 3º.
This is an image of the solved exercise

What i have

```<code>for(i = 1; i <= numero/3; i++){
            zenb3 = parseInt(zenb1+zenb2);
            txt = txt + zenb3 + " ; ";
      zenb4 = parseInt((zenb2*3)/2);
            txt = txt + zenb4 + " ; ";
      zenb5 = parseInt(zenb3/2);
            txt = txt + zenb5 + " ; ";
            zenb1 = zenb4;
      zenb2 = zenb5;

        }
</code>```

Complete code

     <!DOCTYPE html>

          <meta http-equiv="content-type" content="text/html;charset=utf-8">
          <title>Serie</title>

Serie

          <fieldset>
            <legend>Serie</legend>
          <form action="" method="get" name="finfo">

Ingrese el numero de elementos:

<input type="text" id="zenbakia" name="tope" size="10" maxlength="50">
                    <input type="button" value="Erakutsi" onclick="creaMensaje()"/>
                    <input type="reset" value="Garbitu" onclick="iniciar()"/>

          </form>
        </fieldset>

        ```

答:
Perhaps you want to start your loop at 1 and go for count+1:

function fibonacci(num){
  if(num < 2){
    return 1;
  }
  return fibonacci(num-1)+fibonacci(num-2);
}
function fabWalk(count, func){
  for(let i=1,l=count+1; i<l; i++){
    func(fibonacci(i));
  }
}
fabWalk(21, console.log);```

Body:
I have to print the same number of times that I enter (var number) example: if I put 21 it has to give me 21 numbers to print.

Currently if I put 20 it gives me exactly 20 (all good) but if I put 21 it gives me 3 more not 1 (which is what it should give me) if I put 23 it doesn't give me anything.

1º = 10
2º = 8

3º Sum of the 2 previous elements: (10 + 8 = 18)

4º The element twice before (8) is multiplied by 3 and divided by 2 and the whole part is taken: (8 * 3/2 = 12)

5º The element 2 times before is divided by 2 and the whole part is taken. (2/18 = 9)

and the process is repeated from the 3rd element.
y se vuelve a repetir el proceso desde el elemento 3º.
This is an image of the solved exercise

What i have

for(i = 1; i <= numero/3; i++){
            zenb3 = parseInt(zenb1+zenb2);
            txt = txt + zenb3 + " ; ";
      zenb4 = parseInt((zenb2*3)/2);
            txt = txt + zenb4 + " ; ";
      zenb5 = parseInt(zenb3/2);
            txt = txt + zenb5 + " ; ";
            zenb1 = zenb4;
      zenb2 = zenb5;

        }

Complete code

     <!DOCTYPE html>

          <meta http-equiv="content-type" content="text/html;charset=utf-8">
          <title>Serie</title>

Serie

          <fieldset>
            <legend>Serie</legend>
          <form action="" method="get" name="finfo">

Ingrese el numero de elementos:

<input type="text" id="zenbakia" name="tope" size="10" maxlength="50">
                    <input type="button" value="Erakutsi" onclick="creaMensaje()"/>
                    <input type="reset" value="Garbitu" onclick="iniciar()"/>

          </form>
        </fieldset>


问:
Why does a MySql query, valid in Workbench, return syntax errors in phpmyadmin?
so i have 2 tables as table1 and table2 in 2 different databases as id_information and id_information_backup. Both the tables have the following columns: (id bigint, name varchar, surname varchar) I made this trigger where when the user enters name and surname in table1 , it calculates the ascii code of it and do some calculations and store it in the "name" column of the second table which is "table2". All of these has been done in Mysql workbench. when i import the code into phpmyadmin then it gives me too many syntax errors. I tried to figure what syntax errors do i have but i could not find. I am sharing the trigger below. Kindly help me if you can. I will really appreciate it. I guess it is because of the version that i used is MySQL workbench 8.0 and the version that i am importing this into is PHPmyadmin 4.9.4 . Fix the problem if you can please. </p>

```<code>delimiter $$
CREATE DEFINER = CURRENT_USER TRIGGER `id_information`.`table1_after_INSERT1` AFTER INSERT ON `table1` FOR EACH ROW
BEGIN
declare p , r , copy, result, result1 decimal(64,0);
declare name1, surnam varchar(15);
declare a int;
set name1 = new.name;
set surnam = new.surname;
set a= 100;
set result =0;
set copy = 0;
set result1 =0;
set p =0 ;
set r =0 ;
with recursive cte as (
    select name1 as name1, left(name1, 1) as val, 1 as idx
    union all
    select name1, substring(name1, idx + 1, 1), idx + 1
    from cte
    where idx < char_length(name1)
)
select group_concat(ascii(val) + a order by idx separator '') ascii_word from cte into result;
with recursive ctee as (
    select surnam as surnam, left(surnam, 1) as vall , 1 as idxx
    union all
    select surnam, substring(surnam, idxx+ 1, 1), idxx+ 1
    from ctee
    where idxx< char_length(surnam)
)
select group_concat(ascii(vall )  + a order by idxx separator '') ascii_word from ctee into result1;
select group_concat(result, result1) into copy;
insert into id_information_backup.table2  set table2.name = copy;
END$$
delimiter ;
</code>```

答:
When you try to run the command (by pressing the "Go" button at the bottom of the SQL text area), what happens?

If phpMyAdmin is showing the errors as red circles with a white x to the left of the SQL area before submitting, then these are syntax warnings that won't affect your ability to submit the query. These are provided as hints by the SQL linter in phpMyAdmin.

phpMyAdmin syntax warning:

If the errors come after submitting the statements, then the errors come from MySQL itself and aren't directly caused by phpMyAdmin.

MySQL syntax error:

Body:
so i have 2 tables as table1 and table2 in 2 different databases as id_information and id_information_backup. Both the tables have the following columns: (id bigint, name varchar, surname varchar) I made this trigger where when the user enters name and surname in table1 , it calculates the ascii code of it and do some calculations and store it in the "name" column of the second table which is "table2". All of these has been done in Mysql workbench. when i import the code into phpmyadmin then it gives me too many syntax errors. I tried to figure what syntax errors do i have but i could not find. I am sharing the trigger below. Kindly help me if you can. I will really appreciate it. I guess it is because of the version that i used is MySQL workbench 8.0 and the version that i am importing this into is PHPmyadmin 4.9.4 . Fix the problem if you can please.

delimiter $$
CREATE DEFINER = CURRENT_USER TRIGGER `id_information`.`table1_after_INSERT1` AFTER INSERT ON `table1` FOR EACH ROW
BEGIN
declare p , r , copy, result, result1 decimal(64,0);
declare name1, surnam varchar(15);
declare a int;
set name1 = new.name;
set surnam = new.surname;
set a= 100;
set result =0;
set copy = 0;
set result1 =0;
set p =0 ;
set r =0 ;
with recursive cte as (
    select name1 as name1, left(name1, 1) as val, 1 as idx
    union all
    select name1, substring(name1, idx + 1, 1), idx + 1
    from cte
    where idx < char_length(name1)
)
select group_concat(ascii(val) + a order by idx separator '') ascii_word from cte into result;
with recursive ctee as (
    select surnam as surnam, left(surnam, 1) as vall , 1 as idxx
    union all
    select surnam, substring(surnam, idxx+ 1, 1), idxx+ 1
    from ctee
    where idxx< char_length(surnam)
)
select group_concat(ascii(vall )  + a order by idxx separator '') ascii_word from ctee into result1;
select group_concat(result, result1) into copy;
insert into id_information_backup.table2  set table2.name = copy;
END$$
delimiter ;


问:
Setting numpy array to slice without any in-place operations
How can I do this operation efficiently without any inplace operations?

```<code>n_id = np.random.choice(np.arange(2708), size=100)
z = np.random.rand(100, 64)
z_sparse = np.zeros((2708,64))
z_sparse[n_id[:100]] = z
</code>```

Essentially I want the n_id rows of z_sparse to contain z's rows, but I can't do any inplace operations because my end goal is to use this in a pytorch problem.

One though would be to create zero rows within z precisely so that the rows of z end up in the positions n_id, but not sure how this would work efficiently.

Essentially row 1 of z should be placed at row n_id[0] of z_sparse, then row 2 of z should be at row n_id[1] of z_sparse, and so on...

Here's the PyTorch error jic you are curious:
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation

答:
If n_id is a fixed index array, you can get z_sparse as a matrix multiplication:

```<code># N, n, m = 2078,100, 64
row_mat = (n_id[:n] == np.arange(N)[:,None])

# for pytorch tensor
# row_mat = Tensor(n_id[:n] == np.arange(N)[:,None])

z_sparse =  row_mat @ z
</code>```

Since row_mat is a constant array (tensor), your graph should work just fine.

Body:
How can I do this operation efficiently without any inplace operations?

n_id = np.random.choice(np.arange(2708), size=100)
z = np.random.rand(100, 64)
z_sparse = np.zeros((2708,64))
z_sparse[n_id[:100]] = z

Essentially I want the n_id rows of z_sparse to contain z's rows, but I can't do any inplace operations because my end goal is to use this in a pytorch problem.

One though would be to create zero rows within z precisely so that the rows of z end up in the positions n_id, but not sure how this would work efficiently.

Essentially row 1 of z should be placed at row n_id[0] of z_sparse, then row 2 of z should be at row n_id[1] of z_sparse, and so on...

Here's the PyTorch error jic you are curious:
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation

Body:
If n_id is a fixed index array, you can get z_sparse as a matrix multiplication:

# N, n, m = 2078,100, 64
row_mat = (n_id[:n] == np.arange(N)[:,None])

# for pytorch tensor
# row_mat = Tensor(n_id[:n] == np.arange(N)[:,None])

z_sparse =  row_mat @ z

Since row_mat is a constant array (tensor), your graph should work just fine.