问:
Attempt to invoke virtual method on a null object reference Error in my application.any suggestion wlcome.Thanks
REST API XML

posts[
  {
    "id": 16344,
    "date": "2017-11-29T12:45:58",
    "date_gmt": "2017-11-29T07:15:58",
    "modified": "2017-11-29T12:45:58",
    "modified_gmt": "2017-11-29T07:15:58",
    "type": "post",
    "title": {
      "rendered": "This is post from example.com"
    },
    "content": {
      "rendered": "
This is post from example.com
\n",
      "protected": false
    },
    "excerpt": {
      "rendered": "
This is post from example.com
\n",
      "protected": false
    },
    "featured_media": 0,
    "categories": [
      1
    ],

```<code>"better_featured_image": {
"id": 16221,
"alt_text": "",
"caption": "",
"description": "",
"media_type": "image",
"media_details": {
  "width": 1070,
  "height": 286,
  "sizes": {
    "thumbnail": {
      "file": "under_construction-e1509092603289-150x150.jpg",
      "width": 150,
      "height": 150,
      "mime-type": "image/jpeg",
      "source_url": "http://example.com/under_construction-    e1509092603289-150x150.jpg"
    }
    }
    }
    }
</code>```

}
]

public class PostList {

```<code>@SerializedName("date")
@Expose
private String date;

@SerializedName("title")
@Expose
private Title title;

@SerializedName("excerpt")
@Expose
private Excerpt excerpt;

@SerializedName("better_featured_image")
@Expose
private FeaturedImage betterFeaturedImage;

@SerializedName("categories")
@Expose
private List<Integer> categories = null;

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

 public Title getTitle() {
    return title;
}

public void setTitle(Title title) {
    this.title = title;
}

 public Excerpt getExcerpt() {
    return excerpt;
}

public void setExcerpt(Excerpt excerpt) {
    this.excerpt = excerpt;
}

 public FeaturedImage getBetterFeaturedImage() {
    return betterFeaturedImage;
}

public void setBetterFeaturedImage(FeaturedImage betterFeaturedImage) {
    this.betterFeaturedImage = betterFeaturedImage;
}

public List<Integer> getCategories() {
    return categories;
}

public void setCategories(List<Integer> categories) {
    this.categories = categories;
}

public class FeaturedImage {

@SerializedName("media_details")
@Expose
private MediaDetail media_details = null;

public MediaDetail getMedia_details() {
    return media_details;
}

public void setMedia_details(MediaDetail media_details) {
    this.media_details = media_details;
}
</code>```

}

public class MediaDetail {

```<code>@SerializedName("sizes")
@Expose
private Sizes sizes = null;

public Sizes getSizes() {
    return sizes;
}

public void setSizes(Sizes sizes) {
    this.sizes = sizes;
}
</code>```

}

public class Sizes {

```<code>@SerializedName("medium")
@Expose
private Medium medium = null;

public Medium getMedium() {
    return medium;
}

public void setMedium(Medium medium) {
    this.medium = medium;
}
</code>```

}

public class Medium {

```<code>@SerializedName("source_url")
@Expose
private String source_url;

public String getSource_url() {
    return source_url;
}

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

}

public class ProgramingAdapter extends RecyclerView.Adapter {

```<code>Context context;
private PostList[] data;

public ProgramingAdapter(Context context, PostList[] data) {
    this.context = context;
    this.data = data;

}

@Override
public ProgramingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.list_item, parent, false);
    return new ProgramingViewHolder(view);
}

@Override
public void onBindViewHolder(ProgramingViewHolder holder, int position) {
    PostList FImage = data[position];

    final String Tit = FImage.getTitle().getRendered();

    if (Tit.length() <= 70) {
        holder.txtTitle.setText(Tit);
    } else {
        String TitNew = FImage.getTitle().getRendered().substring(0, 70);
        holder.txtTitle.setText(TitNew + "...");
    }

    String Cat = FImage.getCategories().toString();
    String Cat1 = Cat.replaceAll("\\[", "").replaceAll("\\]", "");
    holder.txtCat.setText(Cat1);

    String date = FImage.getDate().substring(0, 10);
    holder.txtDate.setText(date);

    String Exc = FImage.getExcerpt().getRendered();

    if (Exc.length() <= 80) {
        holder.txtExc.setText(Exc);
    } else {
        String ExcNew = FImage.getExcerpt().getRendered().substring(0, 80);
        holder.txtExc.setText(ExcNew + "...");
    }

    Picasso.with(holder.ImgIcon.getContext()).load(FImage.getBetterFeaturedImage().getMedia_details().getSizes().getMedium().toString()).into(holder.ImgIcon);

    holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Toast.makeText(context, Tit , Toast.LENGTH_SHORT).show();
            return false;
        }
    });
}

@Override
public int getItemCount() {
    return data.length;
}

public class ProgramingViewHolder extends RecyclerView.ViewHolder {
    ImageView ImgIcon;
    TextView txtTitle;
    TextView txtDate;
    TextView txtExc;
    TextView txtCat;

    public ProgramingViewHolder(View itemView) {
        super(itemView);
        ImgIcon =  itemView.findViewById(R.id.Img);
        txtTitle =  itemView.findViewById(R.id.Title);
        txtDate =  itemView.findViewById(R.id.Date);
        txtExc =  itemView.findViewById(R.id.Exc);
        txtCat =  itemView.findViewById(R.id.Cat);

    }
}
</code>```

}

public class MainActivity extends AppCompatActivity {

```<code>ImageView imageView;
private static final String URL = "http://example.com/wp-json/wp/v2/posts";

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

    setContentView(R.layout.activity_main);

    imageView = (ImageView) findViewById(R.id.Img);
    final RecyclerView programingList = (RecyclerView) findViewById(R.id.progeramingList);
    programingList.setLayoutManager(new LinearLayoutManager(this));

        final StringRequest request = new StringRequest(Request.Method.GET,URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("PostList", response);
            GsonBuilder gsonBuilder = new GsonBuilder();
            Gson gson = gsonBuilder.create();
            PostList[] post = gson.fromJson(response, PostList[].class);
            programingList.setAdapter(new ProgramingAdapter(MainActivity.this, post));

            Toast.makeText(MainActivity.this, "Ok", Toast.LENGTH_SHORT).show();
        }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
            }
        });

    RequestQueue queue = Volley.newRequestQueue(this);
    queue.add(request);

}
</code>```

}

Error

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.dev.recycler_new, PID: 7965
                  java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.dev.recycler_new.MediaDetail com.example.dev.recycler_new.FeaturedImage.getMedia_details()' on a null object reference
                      at com.example.dev.recycler_new.ProgramingAdapter.onBindViewHolder(ProgramingAdapter.java:70)
                      at com.example.dev.recycler_new.ProgramingAdapter.onBindViewHolder(ProgramingAdapter.java:20)

答:
your error comes from ProgramingAdapter class Picasso.with(holder.ImgIcon.getContext()).load(FImage.getBetterFeaturedImage().getMedia_details().getSizes().getMedium().toString()).into(holder.ImgIcon);

this line you are loading wrong image data like

FImage.getBetterFeaturedImage().getMedia_details().getSizes().getMedium().toString()

so check this properly your picasso load image code like below

```<code>  Picasso.with(context).load(my_data.get(position).getPhoto())
           .into(holder.ImgIcon);
</code>```

pass context instead holder.ImgIcon.getContext()

Body:
REST API XML

posts[
  {
    "id": 16344,
    "date": "2017-11-29T12:45:58",
    "date_gmt": "2017-11-29T07:15:58",
    "modified": "2017-11-29T12:45:58",
    "modified_gmt": "2017-11-29T07:15:58",
    "type": "post",
    "title": {
      "rendered": "This is post from example.com"
    },
    "content": {
      "rendered": "
This is post from example.com
\n",
      "protected": false
    },
    "excerpt": {
      "rendered": "
This is post from example.com
\n",
      "protected": false
    },
    "featured_media": 0,
    "categories": [
      1
    ],

"better_featured_image": {
"id": 16221,
"alt_text": "",
"caption": "",
"description": "",
"media_type": "image",
"media_details": {
  "width": 1070,
  "height": 286,
  "sizes": {
    "thumbnail": {
      "file": "under_construction-e1509092603289-150x150.jpg",
      "width": 150,
      "height": 150,
      "mime-type": "image/jpeg",
      "source_url": "http://example.com/under_construction-    e1509092603289-150x150.jpg"
    }
    }
    }
    }

}
]

public class PostList {

@SerializedName("date")
@Expose
private String date;

@SerializedName("title")
@Expose
private Title title;

@SerializedName("excerpt")
@Expose
private Excerpt excerpt;

@SerializedName("better_featured_image")
@Expose
private FeaturedImage betterFeaturedImage;

@SerializedName("categories")
@Expose
private List<Integer> categories = null;

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

 public Title getTitle() {
    return title;
}

public void setTitle(Title title) {
    this.title = title;
}

 public Excerpt getExcerpt() {
    return excerpt;
}

public void setExcerpt(Excerpt excerpt) {
    this.excerpt = excerpt;
}

 public FeaturedImage getBetterFeaturedImage() {
    return betterFeaturedImage;
}

public void setBetterFeaturedImage(FeaturedImage betterFeaturedImage) {
    this.betterFeaturedImage = betterFeaturedImage;
}

public List<Integer> getCategories() {
    return categories;
}

public void setCategories(List<Integer> categories) {
    this.categories = categories;
}

public class FeaturedImage {

@SerializedName("media_details")
@Expose
private MediaDetail media_details = null;

public MediaDetail getMedia_details() {
    return media_details;
}

public void setMedia_details(MediaDetail media_details) {
    this.media_details = media_details;
}

}

public class MediaDetail {

@SerializedName("sizes")
@Expose
private Sizes sizes = null;

public Sizes getSizes() {
    return sizes;
}

public void setSizes(Sizes sizes) {
    this.sizes = sizes;
}

}

public class Sizes {

@SerializedName("medium")
@Expose
private Medium medium = null;

public Medium getMedium() {
    return medium;
}

public void setMedium(Medium medium) {
    this.medium = medium;
}

}

public class Medium {

@SerializedName("source_url")
@Expose
private String source_url;

public String getSource_url() {
    return source_url;
}

public void setSource_url(String source_url) {
    this.source_url = source_url;
}

}

public class ProgramingAdapter extends RecyclerView.Adapter {

Context context;
private PostList[] data;

public ProgramingAdapter(Context context, PostList[] data) {
    this.context = context;
    this.data = data;

}

@Override
public ProgramingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.list_item, parent, false);
    return new ProgramingViewHolder(view);
}

@Override
public void onBindViewHolder(ProgramingViewHolder holder, int position) {
    PostList FImage = data[position];

    final String Tit = FImage.getTitle().getRendered();

    if (Tit.length() <= 70) {
        holder.txtTitle.setText(Tit);
    } else {
        String TitNew = FImage.getTitle().getRendered().substring(0, 70);
        holder.txtTitle.setText(TitNew + "...");
    }

    String Cat = FImage.getCategories().toString();
    String Cat1 = Cat.replaceAll("\\[", "").replaceAll("\\]", "");
    holder.txtCat.setText(Cat1);

    String date = FImage.getDate().substring(0, 10);
    holder.txtDate.setText(date);

    String Exc = FImage.getExcerpt().getRendered();

    if (Exc.length() <= 80) {
        holder.txtExc.setText(Exc);
    } else {
        String ExcNew = FImage.getExcerpt().getRendered().substring(0, 80);
        holder.txtExc.setText(ExcNew + "...");
    }

    Picasso.with(holder.ImgIcon.getContext()).load(FImage.getBetterFeaturedImage().getMedia_details().getSizes().getMedium().toString()).into(holder.ImgIcon);

    holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Toast.makeText(context, Tit , Toast.LENGTH_SHORT).show();
            return false;
        }
    });
}

@Override
public int getItemCount() {
    return data.length;
}

public class ProgramingViewHolder extends RecyclerView.ViewHolder {
    ImageView ImgIcon;
    TextView txtTitle;
    TextView txtDate;
    TextView txtExc;
    TextView txtCat;

    public ProgramingViewHolder(View itemView) {
        super(itemView);
        ImgIcon =  itemView.findViewById(R.id.Img);
        txtTitle =  itemView.findViewById(R.id.Title);
        txtDate =  itemView.findViewById(R.id.Date);
        txtExc =  itemView.findViewById(R.id.Exc);
        txtCat =  itemView.findViewById(R.id.Cat);

    }
}

}

public class MainActivity extends AppCompatActivity {

ImageView imageView;
private static final String URL = "http://example.com/wp-json/wp/v2/posts";

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

    setContentView(R.layout.activity_main);

    imageView = (ImageView) findViewById(R.id.Img);
    final RecyclerView programingList = (RecyclerView) findViewById(R.id.progeramingList);
    programingList.setLayoutManager(new LinearLayoutManager(this));

        final StringRequest request = new StringRequest(Request.Method.GET,URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("PostList", response);
            GsonBuilder gsonBuilder = new GsonBuilder();
            Gson gson = gsonBuilder.create();
            PostList[] post = gson.fromJson(response, PostList[].class);
            programingList.setAdapter(new ProgramingAdapter(MainActivity.this, post));

            Toast.makeText(MainActivity.this, "Ok", Toast.LENGTH_SHORT).show();
        }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
            }
        });

    RequestQueue queue = Volley.newRequestQueue(this);
    queue.add(request);

}

}

Error

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.dev.recycler_new, PID: 7965
                  java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.dev.recycler_new.MediaDetail com.example.dev.recycler_new.FeaturedImage.getMedia_details()' on a null object reference
                      at com.example.dev.recycler_new.ProgramingAdapter.onBindViewHolder(ProgramingAdapter.java:70)
                      at com.example.dev.recycler_new.ProgramingAdapter.onBindViewHolder(ProgramingAdapter.java:20)

Body:
your error comes from ProgramingAdapter class Picasso.with(holder.ImgIcon.getContext()).load(FImage.getBetterFeaturedImage().getMedia_details().getSizes().getMedium().toString()).into(holder.ImgIcon);

this line you are loading wrong image data like

FImage.getBetterFeaturedImage().getMedia_details().getSizes().getMedium().toString()

so check this properly your picasso load image code like below

  Picasso.with(context).load(my_data.get(position).getPhoto())
           .into(holder.ImgIcon);

pass context instead holder.ImgIcon.getContext()


来源: stackexchange

问:
Html: Bullet list issue in firefox
I have list item like below with css styles as shown.

The list displays properly in Chrome and IE.

But in Firefox (v 43+), i get lists with in proper width and height.

.dropdown-content a {
  color: #2d73a9;
  padding: 12px 8px;
  text-decoration: none;
  display: inline-block;
  text-align: left;
}

.dropdown-content ul li:before {
  content: '\f0c8';
  color: #2d73a9;
  font-size: 4px;
  background-color: #2d73a9;
  margin-right: 5px;
  padding: 0px 2px;
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dropdown-content">
  <ul class="submenu-cont">
    <li class="sub-menu-links">
      Capacitors
    </li>
    <li class="sub-menu-links">
      Inductors
    </li>
    <li class="sub-menu-links">
      Resistors
    </li>
  </ul>
</div></code>```

The bullet list is not in exact square list type in firefox.

I m trying to add pseudo element for firefox something like:

/*The below element doesnt seem to show up in the inspect element especially in the firefox browser. */

I get 'No element selected' if i inspect for sub-menu-links

```<code>::-moz-list-bullet {
    content: '\f0c8';
    color: #2d73a9;
    font-size: 4px;
    background-color: #2d73a9;
    margin-right: 5px;
    padding: 0px 2px;
    vertical-align: middle;
}
</code>```

答:
If you want squares for bullets - just use list-style-type: square;
It produces perfectly square bullets, it's cross-browser compatible and there's less code.

More info: MDN - list-style-type

```<code>li {
 list-style-type: square;
 color: #2d73a9;
}
</code>```

.dropdown-content a {
  color: #2d73a9;
  padding: 12px 8px;
  text-decoration: none;
  display: inline-block;
  text-align: left;
}
li {
 list-style-type: square;
 color: #2d73a9;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dropdown-content">
  <ul class="submenu-cont">
    <li class="sub-menu-links">
      Capacitors
    </li>
    <li class="sub-menu-links">
      Inductors
    </li>
    <li class="sub-menu-links">
      Resistors
    </li>
  </ul>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: Html: Bullet list issue in firefox

Body:
I have list item like below with css styles as shown.

The list displays properly in Chrome and IE.

But in Firefox (v 43+), i get lists with in proper width and height.

.dropdown-content a {
  color: #2d73a9;
  padding: 12px 8px;
  text-decoration: none;
  display: inline-block;
  text-align: left;
}

.dropdown-content ul li:before {
  content: '\f0c8';
  color: #2d73a9;
  font-size: 4px;
  background-color: #2d73a9;
  margin-right: 5px;
  padding: 0px 2px;
  vertical-align: middle;
}

      Capacitors

      Inductors

      Resistors

The bullet list is not in exact square list type in firefox.

I m trying to add pseudo element for firefox something like:

/*The below element doesnt seem to show up in the inspect element especially in the firefox browser. */

I get 'No element selected' if i inspect for sub-menu-links

::-moz-list-bullet {
    content: '\f0c8';
    color: #2d73a9;
    font-size: 4px;
    background-color: #2d73a9;
    margin-right: 5px;
    padding: 0px 2px;
    vertical-align: middle;
}

Body:
If you want squares for bullets - just use list-style-type: square;
It produces perfectly square bullets, it's cross-browser compatible and there's less code.

More info: MDN - list-style-type

li {
 list-style-type: square;
 color: #2d73a9;
}

.dropdown-content a {
  color: #2d73a9;
  padding: 12px 8px;
  text-decoration: none;
  display: inline-block;
  text-align: left;
}
li {
 list-style-type: square;
 color: #2d73a9;
}

<div class="dropdown-content">
  <ul class="submenu-cont">
    <li class="sub-menu-links">
      <a href="#">Capacitors</a>
    </li>
    <li class="sub-menu-links">
      <a href="inductors.html">Inductors</a>
    </li>
    <li class="sub-menu-links">
      <a href="#">Resistors</a>
    </li>
  </ul>
</div>


问:
pan on chart.js also zoom on line charts
I want to pan and zoom on a line chart with chartjs-plugin-zoom. The problem is that when I use pan it also zoom on chart till just one label remains, there is no problem when chart model is bar. how can I solve this problem? I want pan just to pan not zoom.
this is a fiddle that works for bar chart but not works correctly for line chart:
     https://jsfiddle.net/pfd2on55/</p>

```<code>var ctx = document.getElementById("canvas").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
  labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept'],
  datasets: [{
     label: '# of Votes',
     data: [12, 19, 3, 5, 2, 5, 9, 4, 11]
  }]
},
options: {
  pan: {
     enabled: true,
     mode: 'x',
  },
  zoom: {
     enabled: true,
     mode: 'x',
   }
   }
  });
</code>```

答:
I solved this problem by editing function panIndexScale of file Chart.Zoom.js. I changed

var offsetAmt = Math.max((scale.ticks.length - ((scale.options.gridLines.offsetGridLines) ? 0 : 1)), 1); to

```<code>var offsetAmt = Math.max((scale.ticks.length - 0), 1);
</code>```

now pan and zoom work correctly.

Body:
I want to pan and zoom on a line chart with chartjs-plugin-zoom. The problem is that when I use pan it also zoom on chart till just one label remains, there is no problem when chart model is bar. how can I solve this problem? I want pan just to pan not zoom.
this is a fiddle that works for bar chart but not works correctly for line chart:
     https://jsfiddle.net/pfd2on55/

var ctx = document.getElementById("canvas").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
  labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept'],
  datasets: [{
     label: '# of Votes',
     data: [12, 19, 3, 5, 2, 5, 9, 4, 11]
  }]
},
options: {
  pan: {
     enabled: true,
     mode: 'x',
  },
  zoom: {
     enabled: true,
     mode: 'x',
   }
   }
  });

Body:
I solved this problem by editing function panIndexScale of file Chart.Zoom.js. I changed

var offsetAmt = Math.max((scale.ticks.length - ((scale.options.gridLines.offsetGridLines) ? 0 : 1)), 1); to

var offsetAmt = Math.max((scale.ticks.length - 0), 1);

now pan and zoom work correctly.


问:
Second subscription to a shared mapping from BehaviorSubject does not execute
When I subscribe to a shared mapping from BehaviorSubject instance (t), only first subscription is executed.

When the original BehaviorSubject (obj) emits second value, only the latest value is printed, and both subscriptions were executed.

Let check my code

```<code>const obj = new Rx.BehaviorSubject(1)
obj.subscribe(console.log)
const t = obj.map(u => {
  console.log("mapped")
  return u * 10
}).share()

t.subscribe(x => console.log("subscribe 1 " + x))
t.subscribe(x => console.log("subscribe 2 " + x))
//with the following line un-commented, both subscriptions print out new value
//obj.next(2)
</code>```

My expected result is

```<code>1
mapped
subscribe 1 10
subscribe 2 10
</code>```

but the actual result was

```<code>1
mapped
subscribe 1 10
</code>```

Sorry for the naive question. Is there anyone can explain this to me?

Thank you so much

答:
Any operator (including the share) actually creates a new Sub-Observable, which has it's own share/replay-properties that are detached from the source-observable.

So to have your result, you should use publishReplay(1) instead of share().
(With publishReplay you of course have to either use refCount() or connect())

const obj = new Rx.BehaviorSubject(1)
obj.subscribe(console.log)
const t = obj.map(u => {
  console.log("mapped")
  return u * 10
}).publishReplay(1)
.refCount();

t.subscribe(x => console.log("subscribe 1 " + x))
t.subscribe(x => console.log("subscribe 2 " + x))
//with the following line un-commented, both subscriptions print out new value
//obj.next(2)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script></code>```

Body:
When I subscribe to a shared mapping from BehaviorSubject instance (t), only first subscription is executed.

When the original BehaviorSubject (obj) emits second value, only the latest value is printed, and both subscriptions were executed.

Let check my code

const obj = new Rx.BehaviorSubject(1)
obj.subscribe(console.log)
const t = obj.map(u => {
  console.log("mapped")
  return u * 10
}).share()

t.subscribe(x => console.log("subscribe 1 " + x))
t.subscribe(x => console.log("subscribe 2 " + x))
//with the following line un-commented, both subscriptions print out new value
//obj.next(2)

My expected result is

1
mapped
subscribe 1 10
subscribe 2 10

but the actual result was

1
mapped
subscribe 1 10

Sorry for the naive question. Is there anyone can explain this to me?

Thank you so much

Body:
Any operator (including the share) actually creates a new Sub-Observable, which has it's own share/replay-properties that are detached from the source-observable.

So to have your result, you should use publishReplay(1) instead of share().
(With publishReplay you of course have to either use refCount() or connect())

const obj = new Rx.BehaviorSubject(1)
obj.subscribe(console.log)
const t = obj.map(u => {
  console.log("mapped")
  return u * 10
}).publishReplay(1)
.refCount();

t.subscribe(x => console.log("subscribe 1 " + x))
t.subscribe(x => console.log("subscribe 2 " + x))
//with the following line un-commented, both subscriptions print out new value
//obj.next(2)

<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>


问:
Change PDF title in browser window
I have a pdf file that I am putting on a website for a client. It is located here...
http://www.optiphysicaltherapy.com/dev/wp-content/uploads/2014/02/OPTI_NewPatientForms.pdf

The title should be OPTI New Patient Forms but if you look at the tab in the browser and the name at the top of the browser window it says "Coury And..."

Where can I go to change this?

The website is using Wordpress 3.8.1 and I am not sure if it is in Wordpress or in the actual pdf file.

Thank you,

Matt

答:
Open the PDF document in Adobe Acrobat Pro: (OR use google chrome extension)

(1) Go to Select File > Properties

(2) Select the Description tab to view the metadata in the document, including the document information dictionary

(3) Modify the Title field to add or change the document's Title entry

Title: Change PDF title in browser window

ContentLicense: CC BY-SA 4.0


问:
OMNeT++ .ini file parameters
I use OMNeT++ and I have this question about .ini files:

Why do we sometimes use * and sometimes we use ** to set parameters of NED modules?

答:
According to the OMNeT++ Manual (Section 3.6.1)

* means A wildcard for any substring not containing a dot

** means A wildard for any sequence of characters including dots, so it can match multiple path elements

Example:
Lets assume you have the following modules:
aaa.bbb.value and aaa.ddd.value and ccc.bbb.value

**.value = 0 would address all modules, the path before is not important.

aaa.*.value = 0 would address the value element of aaa.bbb.value and aaa.ddd.value. ccc.bbb.value is not addressed because the wildcard is only for the middle substring of the path, as it contains no dots.

Title: OMNeT++ .ini file parameters


问:
Access to a single pixel in C#
I'm working on a school project right now. It's meant to be a 3D editing software, (like a very minimized version of Maya). I have to write it in C#, using the 'Windows Application Project'.
I intend to implement all the 3D stuff myself, from projections to shading.
My question is, how can I get direct access to a single pixel in the C# windows application?
I know I'm going to have a main view port in the window. But I haven't decided yet how it will be made. Is there a built in object that I can use, that will let me define the boundaries of the view port, and then paint each pixel individually?
(I'm just shooting in the dark here, I don't know much about C#. I mostly program in C)

Thanks,
Malki.

答: If you are doing 3d it would make sense to make use of the hardware acceleration provided by almost every GPU under the sun these days. IF you are happy to stay with windows specific apis then DirectX's 3D API's are exposed via managed wrappers now. Also there is the XNA toolset designed primarily with games in mind but it provides a wealth of examples of how to do Direct-X 3D accelerated drawing from c#.</p>

OwnerDisplayName: Malki

ContentLicense: CC BY-SA 2.5

Title: Access to a single pixel in C#


问:
split string by commas, with exception
I have a string with color names, separated by commas or | characters:

```<code>$s = 'Blue | Red (light, dark) | Green, Yellow, Brown';
</code>```

I need to convert it to array:

```<code>$colors = preg_split('![\|,]!', $s);
</code>```

But the result is:

```<code>Array
(
    [0] => Blue
    [1] =>  Red (light
    [2] =>  dark)
    [3] =>  Green
    [4] =>  Yellow
    [5] =>  Brown
)
</code>```

It splits the "light, dark" string with comma. I'd like to split with commas not inside parentheses. Desired result:

```<code>Array
(
    [0] => Blue
    [1] =>  Red (light, dark)
    [2] =>  Green
    [3] =>  Yellow
    [4] =>  Brown
)
</code>```

How can I solve it?

答:
You need to mask the parenthesed portions of your input string before the replacement:

```<code>$s = 'Blue | Red (light, dark) | Green, Yellow, Brown';

// Mask the parenthesed sections.
// Replace the ',' character with a unique string which you can guarantee will not occur (here: '===')
$sr =
    preg_replace_callback(
       '!\([^\)]+\)!'
     , function ( $p_hit ) { return str_replace(',', '===', $p_hit[0]); }
     , $s
    );

// original split
$colors = preg_split('![\|,]!', $sr);

// undo masking
$colors = array_map (
    function ($elem) { return str_replace('===', ',', $elem); }
  , $colors
);

// Print result
print_r ($colors);
</code>```

Output:

```<code>Array
(
[0] => Blue
[1] => Red (light, dark)
[2] => Green
[3] => Yellow
[4] => Brown
)
</code>```

Note

This solution does not work for source string containing nested parentheses.

Title: split string by commas, with exception

Body:
I have a string with color names, separated by commas or | characters:

$s = 'Blue | Red (light, dark) | Green, Yellow, Brown';

I need to convert it to array:

$colors = preg_split('![\|,]!', $s);

But the result is:

Array
(
    [0] => Blue
    [1] =>  Red (light
    [2] =>  dark)
    [3] =>  Green
    [4] =>  Yellow
    [5] =>  Brown
)

It splits the "light, dark" string with comma. I'd like to split with commas not inside parentheses. Desired result:

Array
(
    [0] => Blue
    [1] =>  Red (light, dark)
    [2] =>  Green
    [3] =>  Yellow
    [4] =>  Brown
)

How can I solve it?

Body:
You need to mask the parenthesed portions of your input string before the replacement:

$s = 'Blue | Red (light, dark) | Green, Yellow, Brown';

// Mask the parenthesed sections.
// Replace the ',' character with a unique string which you can guarantee will not occur (here: '===')
$sr =
    preg_replace_callback(
       '!\([^\)]+\)!'
     , function ( $p_hit ) { return str_replace(',', '===', $p_hit[0]); }
     , $s
    );

// original split
$colors = preg_split('![\|,]!', $sr);

// undo masking
$colors = array_map (
    function ($elem) { return str_replace('===', ',', $elem); }
  , $colors
);

// Print result
print_r ($colors);

Output:

Array
(
[0] => Blue
[1] => Red (light, dark)
[2] => Green
[3] => Yellow
[4] => Brown
)

Note

This solution does not work for source string containing nested parentheses.


答:
I believe you are using the font-awesome icon set here. All you need to define the  font-family here.

This code is giving me perfect result in Firefox. Also, check for the other necessary icon files which are needed to bind here with correct path.

```<code>.dropdown-content ul li::before {
  content: '\f0c8';
  color: #2d73a9;
  font-size: 4px;
  background-color: #2d73a9;
  margin-right: 5px;
  padding: 0px 2px;
  vertical-align: middle;
  font-family: FontAwesome;
}
</code>```

And if you are not using font-awesome, than list-style-type: square; is enough to achieve the square bullet. This property will assigned to the li and ::before is not needed in that case for bullets.

Title: Html: Bullet list issue in firefox

Body:
I believe you are using the font-awesome icon set here. All you need to define the  font-family here.

This code is giving me perfect result in Firefox. Also, check for the other necessary icon files which are needed to bind here with correct path.

.dropdown-content ul li::before {
  content: '\f0c8';
  color: #2d73a9;
  font-size: 4px;
  background-color: #2d73a9;
  margin-right: 5px;
  padding: 0px 2px;
  vertical-align: middle;
  font-family: FontAwesome;
}

And if you are not using font-awesome, than list-style-type: square; is enough to achieve the square bullet. This property will assigned to the li and ::before is not needed in that case for bullets.


问:
Subversion, Hudson, Maven, Trac. What's good/bad?
Our project is soon migrating to these open source tools. In a proactive effort, I'm wondering from the experts - What you've found to be the good, bad, and uglies about these products?  What is less than intuitive? No need to comment on all of them, but feel free if you want!

If this should be a wiki or edited to be more "questiony," please advise or edit. Thanks yall!

答:
I'm going to concentrate on Hudson since that's what I know. First, some quick advice:

Subscribe to the Hudson blog. It's a good place to learn about important changes and best practices.

Hudson has an API so you can write scripts that integrate with the rest of your
environment. The most up to date documentation is in your Hudson server: http://your-hudson-server/api

For Hudson and Subversion integration, set up a Subversion commit hook to push notifications to Hudson.

Hudson is a moving target. There are frequent releases and a lot of plugins that extend the functionality. That has both advantages (there's always something new) and disadvantages (there's always something new!). It can be difficult to find the right plugin to handle the particulars of your build process. Currently, the best search tool is Ctrl-F on the Hudson Plugins page. I recommend installing just the plugins that you'll use because if you install everything, you'll end up with many, many configuration options that can make navigating your build setup confusing. Here are some generally useful plugins:

Warnings

Hudson Release

xUnit

Sectioned View

It's typically easy and relatively painless to upgrade (or install that new
plugin you want to use), but constant upgrades just to keep up with the most recent
release are unnecessary if everything is working for you. You'll want to come
up with an upgrade policy that works for you.

I've recommended this before (in the context of my answer about upgrading
Hudson), but I find it useful to have a Hudson playground that's
separate from the main Hudson that the team uses. That lets me do a sanity check on an
upgrade before performing it in on the "production" instance and it's an easy way to try out new features / plugins that provide better reporting.

For all of your tools, there will be a learning curve. Especially in the case
of Hudson, it pays off to experiment with it and learn to use it because it's
very powerful and it gives the whole team the kind of power that used to rest
in the hands of the "build guy."

Regarding Subversion, I totally agree with @Tom's "learn to branch and
merge" advice. Lately, I've been using git's svn integration to manage my
development work (see this popular blog post about git-svn). git makes it much
easier to work on a couple of topics at a time and keep them separate,
i.e. the bug fix that I need to make doesn't interfere with the feature I'm
working on. I recommend learning some of the tricks that DVCS's allow
because expanding your horizons is a good thing.


答: Your ::-moz-list-bullet won't work. It target the list bullet, and the square is your content attribute. You can try changing your list-style-type to square or using one specific style only for Firefox, you can search for @document: @-moz-document should work.

Title: Html: Bullet list issue in firefox


问:
Create a new string column on the table with laravel 5
Hope you're doing well, I actually have a php function who's Create a new integer (4-byte) column on the table, instead I would like my function create a string column on my MariaDB table.

Thanks (if you need more infos I stay around all the day long)

```<code>  /**
 * Create a new integer (4-byte) column on the table.
 *
 * @param  string  $column
 * @param  bool  $autoIncrement
 * @param  bool  $unsigned
 * @return \Illuminate\Support\Fluent
 */
    public function integer($column, $autoIncrement = false, $unsigned = false)
{
    return $this->addColumn('integer', $column, compact('autoIncrement', 'unsigned'));
}
</code>```

Here's the code reffering to the code under this post:

```<code> <?php

 use Illuminate\Support\Facades\Schema;
 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Database\Migrations\Migration;

  class CreateConsultantsTable extends Migration
 {
/**
 * Run the migrations.
 *
 * @return void
 */
    public function up()
    {
    Schema::create('consultants', function (Blueprint $table) {
        $table->increments('id');

        $table->integer('business_id')->unsigned()->nullable();
        $table->foreign('business_id')
            ->references('id')->on('businesses');

        $table->string('trigram')->unique();

        $table->date('availability')
            ->nullable();

        $table->integer('years_experience')->nullable();
</code>```

答:
So, with Laravel it's pretty easy.

Here you can see how to generate a migration for doing this approach

https://laravel.com/docs/5.5/migrations#generating-migrations

So let's say you'd like to add a shortname field to a users - table

```<code>php artisan make:migration add_shortname_to_users_table --table=users
</code>```

Open the 2017_12_04_104053_add_shortname_to_users_table.php (the date before will be another)

So, at last just update the up - method

```<code>$table->string('shortname');
</code>```

Run your normal migration and you're done

Body:
Hope you're doing well, I actually have a php function who's Create a new integer (4-byte) column on the table, instead I would like my function create a string column on my MariaDB table.

Thanks (if you need more infos I stay around all the day long)

  /**
 * Create a new integer (4-byte) column on the table.
 *
 * @param  string  $column
 * @param  bool  $autoIncrement
 * @param  bool  $unsigned
 * @return \Illuminate\Support\Fluent
 */
    public function integer($column, $autoIncrement = false, $unsigned = false)
{
    return $this->addColumn('integer', $column, compact('autoIncrement', 'unsigned'));
}

Here's the code reffering to the code under this post:

 <?php

 use Illuminate\Support\Facades\Schema;
 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Database\Migrations\Migration;

  class CreateConsultantsTable extends Migration
 {
/**
 * Run the migrations.
 *
 * @return void
 */
    public function up()
    {
    Schema::create('consultants', function (Blueprint $table) {
        $table->increments('id');

        $table->integer('business_id')->unsigned()->nullable();
        $table->foreign('business_id')
            ->references('id')->on('businesses');

        $table->string('trigram')->unique();

        $table->date('availability')
            ->nullable();

        $table->integer('years_experience')->nullable();

Body:
So, with Laravel it's pretty easy.

Here you can see how to generate a migration for doing this approach

https://laravel.com/docs/5.5/migrations#generating-migrations

So let's say you'd like to add a shortname field to a users - table

php artisan make:migration add_shortname_to_users_table --table=users

Open the 2017_12_04_104053_add_shortname_to_users_table.php (the date before will be another)

So, at last just update the up - method

$table->string('shortname');

Run your normal migration and you're done


问:
Wall detection on canvas JS
I made this script which moves a smaller div inside it's parent container, but I need it so that it doesn't go past the boundaries of the parent (represented by the 1px black line border). Could someone help me?

var guy = document.getElementById("guy");
var container = document.getElementById("container");
var guyLeft = 0;
var y = 0;

function anim(e) {
    if (e.keyCode == 39) {
        guyLeft += 2;
        guy.style.left = guyLeft + "px";
    }
    else if (e.keyCode == 37) {
        guyLeft -= 2;
        guy.style.left = guyLeft + "px";
    }
    else if (e.keyCode == 40) {
        y += 2;
        guy.style.top = y + "px";
    }
    else if (e.keyCode == 38) {
        y -= 2;
        guy.style.top = y + "px";
    }
}

document.onkeydown = anim;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
  height:300px;
  width:300px;
  outline: 2px solid black;
  position:relative;
}

#guy {
  position:absolute;
  height:20px;
  width:20px;
  outline: 1px solid black;
  background-color:red; left: 0;
}</code>```

```

答:
You could use an IF statement to detect when the character is at the edge.

With your example your JavaScript would become:

```<code>var guy = document.getElementById("guy");
var container = document.getElementById("container");
var guyLeft = 0;
var y = 0;
function anim(e) {
if (e.keyCode == 39 && guyLeft <= 278) {
guyLeft += 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 37 && guyLeft >= 2) {
guyLeft -= 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 40 && y <= 278) {
y += 2; guy.style.top = y + "px";
}
else if (e.keyCode == 38 && y >= 2) {
y -= 2; guy.style.top = y + "px";
}

} document.onkeydown = anim;
</code>```

Here's a working example:

var guy = document.getElementById("guy");
var container = document.getElementById("container");
var guyLeft = 0;
var y = 0;
function anim(e) {
if (e.keyCode == 39 && guyLeft <= 278) {
guyLeft += 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 37 && guyLeft >= 2) {
guyLeft -= 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 40 && y <= 278) {
y += 2; guy.style.top = y + "px";
}
else if (e.keyCode == 38 && y >= 2) {
y -= 2; guy.style.top = y + "px";
}

} document.onkeydown = anim;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
 height:300px;
 width:300px;
 outline: 2px solid black;
 position:relative; }

 #guy {
 position:absolute;
 height:20px;
 width:20px;
 outline: 1px solid black;
 background-color:red; left: 0;
 }</code>```

```

Title: Wall detection on canvas JS

Body:
I made this script which moves a smaller div inside it's parent container, but I need it so that it doesn't go past the boundaries of the parent (represented by the 1px black line border). Could someone help me?

var guy = document.getElementById("guy");
var container = document.getElementById("container");
var guyLeft = 0;
var y = 0;

function anim(e) {
    if (e.keyCode == 39) {
        guyLeft += 2;
        guy.style.left = guyLeft + "px";
    }
    else if (e.keyCode == 37) {
        guyLeft -= 2;
        guy.style.left = guyLeft + "px";
    }
    else if (e.keyCode == 40) {
        y += 2;
        guy.style.top = y + "px";
    }
    else if (e.keyCode == 38) {
        y -= 2;
        guy.style.top = y + "px";
    }
}

document.onkeydown = anim;

#container {
  height:300px;
  width:300px;
  outline: 2px solid black;
  position:relative;
}

#guy {
  position:absolute;
  height:20px;
  width:20px;
  outline: 1px solid black;
  background-color:red; left: 0;
}

Body:
You could use an IF statement to detect when the character is at the edge.

With your example your JavaScript would become:

var guy = document.getElementById("guy");
var container = document.getElementById("container");
var guyLeft = 0;
var y = 0;
function anim(e) {
if (e.keyCode == 39 && guyLeft <= 278) {
guyLeft += 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 37 && guyLeft >= 2) {
guyLeft -= 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 40 && y <= 278) {
y += 2; guy.style.top = y + "px";
}
else if (e.keyCode == 38 && y >= 2) {
y -= 2; guy.style.top = y + "px";
}

} document.onkeydown = anim;

Here's a working example:

var guy = document.getElementById("guy");
var container = document.getElementById("container");
var guyLeft = 0;
var y = 0;
function anim(e) {
if (e.keyCode == 39 && guyLeft <= 278) {
guyLeft += 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 37 && guyLeft >= 2) {
guyLeft -= 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 40 && y <= 278) {
y += 2; guy.style.top = y + "px";
}
else if (e.keyCode == 38 && y >= 2) {
y -= 2; guy.style.top = y + "px";
}

} document.onkeydown = anim;

#container {
 height:300px;
 width:300px;
 outline: 2px solid black;
 position:relative; }

 #guy {
 position:absolute;
 height:20px;
 width:20px;
 outline: 1px solid black;
 background-color:red; left: 0;
 }

<div id="container"> <div id="guy"></div></div>


问:
How do you find the average of a dictionary?
So let's say I have this dictionary

```<code>{'Taylor Swift': ['Kanye West']}
</code>```

I would expect 1.0 from this as there is one value (which is 'Kanye West') divided by one key (which is 'Taylor Swift') to get the average of 1.0.

And let's say I have this dictionary

```<code>{'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler': ['Johnny Depp', 'Tom Hanks']}
</code>```

I would expect the average of 2.0 from this as there are 4 values divided by 2 keys.

This is the code I have tried:

```<code>average = 0
sum = 0
for n in data:
    sum = sum + n
average = sum / len(data)
</code>```

I have tried many other ways too through online search and the common error I get is this:

```<code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code>```

答:
Here you go</p>

```<code>#some dictionary
d={'Taylor Swift': ['Kanye',' West', 'Elvis',' Presley','l'], 'Adam Sandler': ['Johnny',' Depp', 'Tom',' Hanks']}
#Sum function gets the sum of all values in dictionary
#Len function gets the total number of keys in dictionary
#Multiplying with 1.0 to get exact division, else import division function from _future_ library
avg = sum(len(v) for v in d.itervalues())*1.0/len(d)
print avg
</code>```

Body:
So let's say I have this dictionary

{'Taylor Swift': ['Kanye West']}

I would expect 1.0 from this as there is one value (which is 'Kanye West') divided by one key (which is 'Taylor Swift') to get the average of 1.0.

And let's say I have this dictionary

{'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler': ['Johnny Depp', 'Tom Hanks']}

I would expect the average of 2.0 from this as there are 4 values divided by 2 keys.

This is the code I have tried:

average = 0
sum = 0
for n in data:
    sum = sum + n
average = sum / len(data)

I have tried many other ways too through online search and the common error I get is this:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Body:
Here you go

#some dictionary
d={'Taylor Swift': ['Kanye',' West', 'Elvis',' Presley','l'], 'Adam Sandler': ['Johnny',' Depp', 'Tom',' Hanks']}
#Sum function gets the sum of all values in dictionary
#Len function gets the total number of keys in dictionary
#Multiplying with 1.0 to get exact division, else import division function from _future_ library
avg = sum(len(v) for v in d.itervalues())*1.0/len(d)
print avg


问:
Most Efficient Many-t-Many Query
Let's say I'm implementing articles with article tags. I'm using SQL Server 2008.

```<code>TABLE Articles
ArtID INT
...

TABLE Tags
TagID INT
TagText VARCHAR(10)

TABLE ArticleTags
ArtID INT
TagID INT
</code>```

I'm trying to figure out the most efficient way to query all articles with a specific tags. Here's two options, both of which I've read are most efficient.

Method A:

```<code>SELECT a.* FROM Articles
WHERE EXISTS (
    SELECT * FROM ArticleTags at
    INNER JOIN Tags t ON at.TagID = t.TagID
    WHERE at.ArtID = a.ID
    AND t.TagText IN ('abc', 'def')
)
</code>```

Method B:

```<code>SELECT a.* FROM Articles a
INNER JOIN ArticleTags at ON a.ArtID = at.ArtID
INNER JOIN Tags t ON at.TagID = t.TagID
WHERE t.TagText IN ('abc', 'def')
GROUP BY a.ArtID
</code>```

Can any SQL experts suggest which is more efficient and why? Or maybe I'm on the wrong track.

答:
As with almost all SQL performance questions, the answer is not the query, the answer is the data schema. What indexes you have, that is what drives the performance of your queries.

Usually many-to-many relations require two complementary indexes, one as (ID1, ID2) and the other as (ID2, ID1). One of them is clustered, it doesn't really matter which one. So lets create a test DB (100k articles, 1K tags, 1-10 tags per article):

```<code>:setvar dbname testdb
:setvar articles 1000000
:setvar tags 1000
:setvar articletags 10
:on error exit

set xact_abort on;
go

use master;
go

if db_id('$(dbname)') is not null
begin
    alter database [$(dbname)] set single_user with rollback immediate;
    drop database [$(dbname)];
end
go

create database [$(dbname)];
go

use [$(dbname)];
go

create TABLE Articles (
    ArtID INT not null identity(1,1),
    name varchar(100) not null,
    filler char(500) not null default replicate('X', 500),
    constraint pk_Articles primary key clustered (ArtID));
go

create table Tags (
    TagID INT not null identity(1,1),
    TagText VARCHAR(10) not null,
    constraint pk_Tags primary key clustered (TagID),
    constraint unq_Tags_Text unique (TagText));
go

create TABLE ArticleTags (
    ArtID INT not null,
    TagID INT not null,
    constraint fk_Articles
        foreign key (ArtID)
        references Articles (ArtID),
    constraint fk_Tags
        foreign key (TagID)
        references Tags (TagID),
    constraint pk_ArticleTags
        primary key clustered (ArtID, TagID));
go

create nonclustered index ndxArticleTags_TagID
    on ArticleTags (TagID, ArtID);
go

-- populate articles
set nocount on;
declare @i int =0, @name varchar(100);
begin transaction
while @i < $(articles)
begin
    set @name = 'Name ' + cast(@i as varchar(10));
    insert into Articles (name) values (@name);
    set @i += 1;
    if @i %1000 = 0
    begin
        commit;
        raiserror (N'Inserted %d articles', 0, 1, @i);
        begin transaction;
    end
end
commit
go

-- populate tags
set nocount on;
declare @i int =0, @text varchar(100);
begin transaction
while @i < $(tags)
begin
    set @text = 'Tag ' + cast(@i as varchar(10));
    insert into Tags (TagText) values (@text);
    set @i += 1;
    if @i %1000 = 0
    begin
        commit;
        raiserror (N'Inserted %d tags', 0, 1, @i);
        begin transaction;
    end
end
commit
go

-- populate article-tags
set nocount on;
declare @i int =0, @a int = 1, @cnt int, @tag int;
set @cnt = rand() * $(articletags) + 1;
set @tag = rand() * $(tags) + 1;
begin transaction
while @a < $(articles)
begin
    insert into ArticleTags (ArtID, TagID) values (@a, @tag);
    set @cnt -= 1;
    set @tag += rand()*10+1;
    if $(tags)<=@tag
    begin
        set @tag = 1;
    end
    if @cnt = 0
    begin
        set @cnt = rand() * $(articletags) + 1;
        set @tag = rand() * $(tags) + 1;
        set @a += 1;
    end
    set @i += 1;
    if @i %1000 = 0
    begin
        commit;
        raiserror (N'Inserted %d article-tags', 0, 1, @i);
        begin transaction;
    end
end
commit
raiserror (N'Final: %d article-tags', 0, 1, @i);
go
</code>```

Now lets compare the two queries:

```<code>set statistics io on;
set statistics time on;

select a.ArtID
from Articles a
where exists (
    select *
    from ArticleTags at
    join Tags t on at.TagID = t.TagID
    where at.ArtID = a.ArtID
    and t.TagText in ('Tag 10', 'Tag 12'));

SELECT a.ArtID FROM Articles a
INNER JOIN ArticleTags at ON a.ArtID = at.ArtID
INNER JOIN Tags t ON at.TagID = t.TagID
WHERE t.TagText IN ('Tag 10', 'Tag 12')
GROUP BY a.ArtID
</code>```

Result:

```<code>Table 'Articles'. Scan count 0, logical reads 3561, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'ArticleTags'. Scan count 2, logical reads 13, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Tags'. Scan count 2, logical reads 4, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Articles'. Scan count 0, logical reads 3561, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'ArticleTags'. Scan count 2, logical reads 13, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Tags'. Scan count 2, logical reads 4, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
</code>```

Surprise! (well, not really). They're IDENTICAL. In fact, they have exactly the same execution plan.

Title: Most Efficient Many-t-Many Query

Body:
Let's say I'm implementing articles with article tags. I'm using SQL Server 2008.

TABLE Articles
ArtID INT
...

TABLE Tags
TagID INT
TagText VARCHAR(10)

TABLE ArticleTags
ArtID INT
TagID INT

I'm trying to figure out the most efficient way to query all articles with a specific tags. Here's two options, both of which I've read are most efficient.

Method A:

SELECT a.* FROM Articles
WHERE EXISTS (
    SELECT * FROM ArticleTags at
    INNER JOIN Tags t ON at.TagID = t.TagID
    WHERE at.ArtID = a.ID
    AND t.TagText IN ('abc', 'def')
)

Method B:

SELECT a.* FROM Articles a
INNER JOIN ArticleTags at ON a.ArtID = at.ArtID
INNER JOIN Tags t ON at.TagID = t.TagID
WHERE t.TagText IN ('abc', 'def')
GROUP BY a.ArtID

Can any SQL experts suggest which is more efficient and why? Or maybe I'm on the wrong track.

Body:
As with almost all SQL performance questions, the answer is not the query, the answer is the data schema. What indexes you have, that is what drives the performance of your queries.

Usually many-to-many relations require two complementary indexes, one as (ID1, ID2) and the other as (ID2, ID1). One of them is clustered, it doesn't really matter which one. So lets create a test DB (100k articles, 1K tags, 1-10 tags per article):

:setvar dbname testdb
:setvar articles 1000000
:setvar tags 1000
:setvar articletags 10
:on error exit

set xact_abort on;
go

use master;
go

if db_id('$(dbname)') is not null
begin
    alter database [$(dbname)] set single_user with rollback immediate;
    drop database [$(dbname)];
end
go

create database [$(dbname)];
go

use [$(dbname)];
go

create TABLE Articles (
    ArtID INT not null identity(1,1),
    name varchar(100) not null,
    filler char(500) not null default replicate('X', 500),
    constraint pk_Articles primary key clustered (ArtID));
go

create table Tags (
    TagID INT not null identity(1,1),
    TagText VARCHAR(10) not null,
    constraint pk_Tags primary key clustered (TagID),
    constraint unq_Tags_Text unique (TagText));
go

create TABLE ArticleTags (
    ArtID INT not null,
    TagID INT not null,
    constraint fk_Articles
        foreign key (ArtID)
        references Articles (ArtID),
    constraint fk_Tags
        foreign key (TagID)
        references Tags (TagID),
    constraint pk_ArticleTags
        primary key clustered (ArtID, TagID));
go

create nonclustered index ndxArticleTags_TagID
    on ArticleTags (TagID, ArtID);
go

-- populate articles
set nocount on;
declare @i int =0, @name varchar(100);
begin transaction
while @i < $(articles)
begin
    set @name = 'Name ' + cast(@i as varchar(10));
    insert into Articles (name) values (@name);
    set @i += 1;
    if @i %1000 = 0
    begin
        commit;
        raiserror (N'Inserted %d articles', 0, 1, @i);
        begin transaction;
    end
end
commit
go

-- populate tags
set nocount on;
declare @i int =0, @text varchar(100);
begin transaction
while @i < $(tags)
begin
    set @text = 'Tag ' + cast(@i as varchar(10));
    insert into Tags (TagText) values (@text);
    set @i += 1;
    if @i %1000 = 0
    begin
        commit;
        raiserror (N'Inserted %d tags', 0, 1, @i);
        begin transaction;
    end
end
commit
go

-- populate article-tags
set nocount on;
declare @i int =0, @a int = 1, @cnt int, @tag int;
set @cnt = rand() * $(articletags) + 1;
set @tag = rand() * $(tags) + 1;
begin transaction
while @a < $(articles)
begin
    insert into ArticleTags (ArtID, TagID) values (@a, @tag);
    set @cnt -= 1;
    set @tag += rand()*10+1;
    if $(tags)<=@tag
    begin
        set @tag = 1;
    end
    if @cnt = 0
    begin
        set @cnt = rand() * $(articletags) + 1;
        set @tag = rand() * $(tags) + 1;
        set @a += 1;
    end
    set @i += 1;
    if @i %1000 = 0
    begin
        commit;
        raiserror (N'Inserted %d article-tags', 0, 1, @i);
        begin transaction;
    end
end
commit
raiserror (N'Final: %d article-tags', 0, 1, @i);
go

Now lets compare the two queries:

set statistics io on;
set statistics time on;

select a.ArtID
from Articles a
where exists (
    select *
    from ArticleTags at
    join Tags t on at.TagID = t.TagID
    where at.ArtID = a.ArtID
    and t.TagText in ('Tag 10', 'Tag 12'));

SELECT a.ArtID FROM Articles a
INNER JOIN ArticleTags at ON a.ArtID = at.ArtID
INNER JOIN Tags t ON at.TagID = t.TagID
WHERE t.TagText IN ('Tag 10', 'Tag 12')
GROUP BY a.ArtID

Result:

Table 'Articles'. Scan count 0, logical reads 3561, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'ArticleTags'. Scan count 2, logical reads 13, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Tags'. Scan count 2, logical reads 4, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Articles'. Scan count 0, logical reads 3561, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'ArticleTags'. Scan count 2, logical reads 13, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Tags'. Scan count 2, logical reads 4, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Surprise! (well, not really). They're IDENTICAL. In fact, they have exactly the same execution plan.


问:
jQuery dynamically add selected value with its parent data like formatted
I have my html code looks like this

```<code><input type="hidden" value="" id="shortcode_selected_package" name="shortcode_selected_package">

    <div class="selected-packages-wrap">
      <div class="shortcode-wrap">
        <a href="#" class="data-remove" data-id="220" data-name="New custom pack">-</a><label>New custom pack</label>
        <span class="package-cats">
                    <span><input class="package-cat" data-parent="220" value="5" type="checkbox">10 GB</span>
        <span><input class="package-cat" data-parent="220" value="6" type="checkbox">6 GB</span>
        <span><input class="package-cat" data-parent="220" value="26" type="checkbox">Sony</span>
        <span><input class="package-cat" data-parent="220" value="25" type="checkbox">Unlimited Calls</span></span>
      </div>

      <div class="shortcode-wrap">
        <a href="#" class="data-remove" data-id="417" data-name="Test New Packs">-</a><label>Test New Packs</label>
        <span class="package-cats">
                    <span><input class="package-cat" data-parent="417" value="5" type="checkbox">10 GB</span>
        </span>
      </div>

      <div class="shortcode-wrap">
        <a class="data-remove" href="#" data-id="219" data-cat-id="7|6|24" data-cat-name="12 - 20 GB|6 GB|Unlimited Messages" data-name="Test package">-</a><label>Test package</label>
        <span class="package-cats">
                    <span><input class="package-cat" type="checkbox" data-parent="219" value="7">12 - 20 GB</span>
        <span><input class="package-cat" type="checkbox" data-parent="219" value="6">6 GB</span>
        <span><input class="package-cat" type="checkbox" data-parent="219" value="24">Unlimited Messages</span>
        </span>
      </div>
    </div>
</code>```

In my code when someone checks the 10 GB, Unlimited Calls checkbox for the first div then the value should be assigned to the shortcode_selected_package div. So let's say someone if checks to the first element of the top div which is data-id="220" then the value should be assigned to the div is like

```<code>220[5|6]
</code>```

again when someone clicks to the 10 GB of the second div then the value should be like

```<code>220[5|6],417[5]
</code>```

In the same if someone checks to the Unlimited Messages of the last div then the value should be like this

```<code>220[5|6],417[5],219[24]
</code>```

If someone unchecks the checkbox then the respective value should be remove as well from the value

So can someone tell me how to do this.

In the following code is always showing only one single data. Not updating the older one which was checked.

```<code>$('div.selected-packages-wrap').find('input.package-cat').change(function() {
      var Parent = $(this).attr('data-parent');
      var Selected = $(this).val();
      var SelectedPackages = $('#shortcode_selected_package').val();
      if (SelectedPackages !== '' || SelectedPackages !== undefined) {
        tmp = SelectedPackages.split(',');

        var index = tmp.indexOf(Parent);

        if (index !== -1) {
          tmp.splice(index, 1);
          data = tmp.join('[' + Selected + '],');
          console.log(data);
        }
      }

    });
</code>```

答:
So you need to start by thinking of how to structure your data, As I understood a user can select mutliple packages from different categories so you might have something like this

```<code>{
  [categoryId]: Array<PackageId>,
}
</code>```

for example

```<code>{
  244: [100, 200],
  500: [6, 7]
}
</code>```

Then you need to find a way to convert this data to this string format: 244[100|200],500[6|7], This is one way to do it

```<code>function formatPackages(data) {
  var arr = [];
  for(var key in data) {
    if(data.hasOwnProperty(key) &&
      data[key] &&
      data[key].constructor === Array) {
      arr.push(key + '[' + data[key].join('|') + ']');
    }
  }
  return arr.join(',');
}
</code>```

Now you need functions to select and unselect packages

```<code>var selectedPackages = {};

function selectPackage(parent, value) {
  if(selectedPackages[parent]) {
    selectedPackages[parent].push(value);
  } else {
    selectedPackages[parent] = [value];
  }
}

function unselectPackage(parent, value) {
  if(selectedPackages[parent]) {
    var index = selectedPackages[parent].indexOf(value);
    if(index > -1) {
      selectedPackages[parent].splice(index, 1);
    }
    if(selectedPackages[parent].length === 0) {
      delete selectedPackages[parent];
    }
  }
}
</code>```

Once you have all the pieces together, you can add user handling

```<code>$('div.selected-packages-wrap').find('input.package-cat').change(function() {
  var parent = $(this).attr('data-parent');
  var value = $(this).val();

  if(this.checked) {
    selectPackage(parent, value);
  } else {
    unselectPackage(parent, value);
  }

$('#shortcode_selected_package').val(formatPackages(selectedPackages));
});
</code>```

Here's a link to jsfiddle: https://jsfiddle.net/bitriddler/eL9L8wxj/1/

Body:
I have my html code looks like this

<input type="hidden" value="" id="shortcode_selected_package" name="shortcode_selected_package">

        -New custom pack

                    <input class="package-cat" data-parent="220" value="5" type="checkbox">10 GB
        <input class="package-cat" data-parent="220" value="6" type="checkbox">6 GB
        <input class="package-cat" data-parent="220" value="26" type="checkbox">Sony
        <input class="package-cat" data-parent="220" value="25" type="checkbox">Unlimited Calls

        -Test New Packs

                    <input class="package-cat" data-parent="417" value="5" type="checkbox">10 GB

        -Test package

                    <input class="package-cat" type="checkbox" data-parent="219" value="7">12 - 20 GB
        <input class="package-cat" type="checkbox" data-parent="219" value="6">6 GB
        <input class="package-cat" type="checkbox" data-parent="219" value="24">Unlimited Messages

In my code when someone checks the 10 GB, Unlimited Calls checkbox for the first div then the value should be assigned to the shortcode_selected_package div. So let's say someone if checks to the first element of the top div which is data-id="220" then the value should be assigned to the div is like

220[5|6]

again when someone clicks to the 10 GB of the second div then the value should be like

220[5|6],417[5]

In the same if someone checks to the Unlimited Messages of the last div then the value should be like this

220[5|6],417[5],219[24]

If someone unchecks the checkbox then the respective value should be remove as well from the value

So can someone tell me how to do this.

In the following code is always showing only one single data. Not updating the older one which was checked.

$('div.selected-packages-wrap').find('input.package-cat').change(function() {
      var Parent = $(this).attr('data-parent');
      var Selected = $(this).val();
      var SelectedPackages = $('#shortcode_selected_package').val();
      if (SelectedPackages !== '' || SelectedPackages !== undefined) {
        tmp = SelectedPackages.split(',');

        var index = tmp.indexOf(Parent);

        if (index !== -1) {
          tmp.splice(index, 1);
          data = tmp.join('[' + Selected + '],');
          console.log(data);
        }
      }

    });

Body:
So you need to start by thinking of how to structure your data, As I understood a user can select mutliple packages from different categories so you might have something like this

{
  [categoryId]: Array<PackageId>,
}

for example

{
  244: [100, 200],
  500: [6, 7]
}

Then you need to find a way to convert this data to this string format: 244[100|200],500[6|7], This is one way to do it

function formatPackages(data) {
  var arr = [];
  for(var key in data) {
    if(data.hasOwnProperty(key) &&
      data[key] &&
      data[key].constructor === Array) {
      arr.push(key + '[' + data[key].join('|') + ']');
    }
  }
  return arr.join(',');
}

Now you need functions to select and unselect packages

var selectedPackages = {};

function selectPackage(parent, value) {
  if(selectedPackages[parent]) {
    selectedPackages[parent].push(value);
  } else {
    selectedPackages[parent] = [value];
  }
}

function unselectPackage(parent, value) {
  if(selectedPackages[parent]) {
    var index = selectedPackages[parent].indexOf(value);
    if(index > -1) {
      selectedPackages[parent].splice(index, 1);
    }
    if(selectedPackages[parent].length === 0) {
      delete selectedPackages[parent];
    }
  }
}

Once you have all the pieces together, you can add user handling

$('div.selected-packages-wrap').find('input.package-cat').change(function() {
  var parent = $(this).attr('data-parent');
  var value = $(this).val();

  if(this.checked) {
    selectPackage(parent, value);
  } else {
    unselectPackage(parent, value);
  }

$('#shortcode_selected_package').val(formatPackages(selectedPackages));
});

Here's a link to jsfiddle: https://jsfiddle.net/bitriddler/eL9L8wxj/1/


问:
How to create methods in Jenkins Declarative pipeline?
In Jenkins scripted pipeline we are able to create methods and can call them.

Is it possible also in the Jenkins declarative pipeline? And how?

答:
Newer versions of the declarative pipelines support this, while this was not possible before (~mid 2017). You can just declare functions as you'd expect it from a groovy script:

pipeline {
    agent any
    stages {
        stage('Test') {
            steps {
                whateverFunction()
            }
        }
    }
}

void whateverFunction() {
    sh 'ls /'
}
```


问:
Is there any way to inspect RabbitMQ messages that are persisted? Where those are stored?
Just doing some testing on local machine, would like somewhere to inspect messages that are published and persisted by RabbitMQ (deliveryMode = 2). Or at least to have a time when messages was actually persisted. First try was RabbitMQ admin management, went trough all options and closest what i have found is following:

Database directory:    /usr/local/var/lib/rabbitmq/mnesia/rabbit@localhost

There i can found many files with rdq extenstions and many logs file, but can't actually see nothing.

答:
you can't, RabbitMQ uses a custom database and it is not possible to browse it.

you can only browse the RabbitMQ definitions as "queues", "users", "exchanges" etc.. but not the messages.

By default, the messages index is inside:

/usr/local/var/lib/rabbitmq/mnesia/rabbit@localhost/queues/HASHQUEUE

The only way it is as suggested by @Johansson


问:
use post html after rending html
Using flask and WT forms I am trying to get the user input in a form and  redirecting user input to another route, there using the input in functions which will get some dict of data.

I want this data to use in a WT form. Once I saw the data and checked all fine. I want to save it as new entry for database.

Problem: after rending the form this I am not able to process to as post request.

```<code>@app.route('/', method =[POST,GET])
def home():
    forms = inputForms(request.form)
    if form_validate() and request.POST:
         value=forms.input.data
         redirect(url_for(/edit, value=value)
    return render_template('input.html')  -- Initial page where getting user input
  @app.route('/edit', method =[POST,GET])
   def edit(value):
       data= getdata(value)
       if data == 'error':
            return render_template('error.html')
       else:
          form=request.form(data=data)
          return render_template('data.html', form=form
          if form_validate() and request.POST:
               save ()
</code>```

I'd like to see that once render the form how can I use it submit.

I am able to get the forms but once return I am not able to move ahead on the save options

答:
Based on your comment, you can change your post action. so your form is POSTed to another route.

```<code><form method="POST" action="{{url_for('edit')}}">
{{ form.csrf_token }}
{{ form.name.label }} {{ form.name(size=20) }}
<input type="submit" value="Go">
</code>```

Using the above in your template, then you can move your functionality for validation to that route.

```<code>@app.route('/edit', method =[POST,GET])
def edit():
   if request.method == 'POST' and form.validate():
      pass
</code>```

this way, you can handle everything within the edit route.
then your home route can change to just rendering the form.

```<code>@app.route('/', method =[POST,GET])
def home():
    forms = inputForms(request.form)
    return render_template('input.html')
</code>```

and you should have a trailing slash for your routes. so it's better to have your routes as:

```<code>@app.route('/edit/', method =[POST,GET])
def edit():
    pass
</code>```

Title: use post html after rending html

Body:
Using flask and WT forms I am trying to get the user input in a form and  redirecting user input to another route, there using the input in functions which will get some dict of data.

I want this data to use in a WT form. Once I saw the data and checked all fine. I want to save it as new entry for database.

Problem: after rending the form this I am not able to process to as post request.

@app.route('/', method =[POST,GET])
def home():
    forms = inputForms(request.form)
    if form_validate() and request.POST:
         value=forms.input.data
         redirect(url_for(/edit, value=value)
    return render_template('input.html')  -- Initial page where getting user input
  @app.route('/edit', method =[POST,GET])
   def edit(value):
       data= getdata(value)
       if data == 'error':
            return render_template('error.html')
       else:
          form=request.form(data=data)
          return render_template('data.html', form=form
          if form_validate() and request.POST:
               save ()

I'd like to see that once render the form how can I use it submit.

I am able to get the forms but once return I am not able to move ahead on the save options

Body:
Based on your comment, you can change your post action. so your form is POSTed to another route.

<form method="POST" action="{{url_for('edit')}}">
{{ form.csrf_token }}
{{ form.name.label }} {{ form.name(size=20) }}
<input type="submit" value="Go">

Using the above in your template, then you can move your functionality for validation to that route.

@app.route('/edit', method =[POST,GET])
def edit():
   if request.method == 'POST' and form.validate():
      pass

this way, you can handle everything within the edit route.
then your home route can change to just rendering the form.

@app.route('/', method =[POST,GET])
def home():
    forms = inputForms(request.form)
    return render_template('input.html')

and you should have a trailing slash for your routes. so it's better to have your routes as:

@app.route('/edit/', method =[POST,GET])
def edit():
    pass


问:
When retrieving value from arraylist stores in POJO , it returns me the last value stored
IN my Json 2017 is the year , 11 is the month, and next is date

```<code>  Well this is my  json

    {
        "2017": {
            "11": {
                "8": {
                    "status": "P"
                },
                "10": {
                    "status": "A"
                },
                "24": {
                    "status": "A"
                }
            },
            "12": {
                "1": {
                    "status": "P"
                },
                "2": {
                    "status": "A"
                }
            }
        }
    }
</code>```

Here I am fetching values from Json and storing in some variables

```<code>  try {
        JSONObject object = new JSONObject(response);
        Iterator iterator = object.keys();
        attendance_pojo pojo= new attendance_pojo();

        while (iterator.hasNext()) {
            String year = (String) iterator.next();

            /*Log.d("year", year);*/
            JSONObject obj = object.getJSONObject(year);
            Iterator iterator2 = obj.keys();

            while (iterator2.hasNext()) {

                String month = (String) iterator2.next();

                /*Log.d("month", month);*/
                JSONObject ob = obj.getJSONObject(month);

                Iterator iterator3 = ob.keys();

                    int datecntr=0;
                while (iterator3.hasNext()) {
                    datecntr++;
                    String date = (String) iterator3.next();
                    pojo.setYear(year);
                    pojo.setMonth(month);
                    pojo.setDate(date);

                    JSONObject ob1 = ob.getJSONObject(date);
                    /*Log.d("16", date);*/
                    String status = ob1.getString("status");
                    if (status.equals("P"))
                    {
                        present++;
                    }
                    else
                        absent++;
                   /* Log.d("title", status);*/

                }
                pojo.setDatecounter(datecntr);

                Log.d("counter",""+datecntr);
                Log.d("kuqw",present+" "+absent);
                pojo.setPresent(""+present);
                pojo.setAbsent(""+absent);

                present=0;
                absent=0;
                arrayList.add(pojo);
                adapter.notifyDataSetChanged();
            }

        }
</code>```

And here i am retrieving value from pojo  so that i can set those in some textviews

```<code>     attendance_pojo pojo= arrayList.get(position);
            String months= pojo.getMonth();
            Log.d("months",months);
            months= checkmonth(months);
            Log.d("datess",""+pojo.getDate());
            month.setText(months+" "+pojo.getYear());
            workdays.setText(""+pojo.getDatecounter());

But i am always getting 12 when I am getting Log of datess

    12-04 15:27:25.220 2523-2523/rock.school_hub D/months: 12
    12-04 15:27:25.226 2523-2523/rock.school_hub D/months: 12
    12-04 15:27:25.229 2523-2523/rock.school_hub D/months: 12
    12-04 15:27:25.236 2523-2523/rock.school_hub D/months: 12
</code>```

As per my json First i should get 11 then 12, but in variable months, it is always showing 12

答:
```<code> pojo.setDatecounter(datecntr);

                Log.d("counter",""+datecntr);
                Log.d("kuqw",present+" "+absent);
                pojo.setPresent(""+present);
                pojo.setAbsent(""+absent);
</code>```

put this code inside while{ }

Body:
IN my Json 2017 is the year , 11 is the month, and next is date

  Well this is my  json

    {
        "2017": {
            "11": {
                "8": {
                    "status": "P"
                },
                "10": {
                    "status": "A"
                },
                "24": {
                    "status": "A"
                }
            },
            "12": {
                "1": {
                    "status": "P"
                },
                "2": {
                    "status": "A"
                }
            }
        }
    }

Here I am fetching values from Json and storing in some variables

  try {
        JSONObject object = new JSONObject(response);
        Iterator iterator = object.keys();
        attendance_pojo pojo= new attendance_pojo();

        while (iterator.hasNext()) {
            String year = (String) iterator.next();

            /*Log.d("year", year);*/
            JSONObject obj = object.getJSONObject(year);
            Iterator iterator2 = obj.keys();

            while (iterator2.hasNext()) {

                String month = (String) iterator2.next();

                /*Log.d("month", month);*/
                JSONObject ob = obj.getJSONObject(month);

                Iterator iterator3 = ob.keys();

                    int datecntr=0;
                while (iterator3.hasNext()) {
                    datecntr++;
                    String date = (String) iterator3.next();
                    pojo.setYear(year);
                    pojo.setMonth(month);
                    pojo.setDate(date);

                    JSONObject ob1 = ob.getJSONObject(date);
                    /*Log.d("16", date);*/
                    String status = ob1.getString("status");
                    if (status.equals("P"))
                    {
                        present++;
                    }
                    else
                        absent++;
                   /* Log.d("title", status);*/

                }
                pojo.setDatecounter(datecntr);

                Log.d("counter",""+datecntr);
                Log.d("kuqw",present+" "+absent);
                pojo.setPresent(""+present);
                pojo.setAbsent(""+absent);

                present=0;
                absent=0;
                arrayList.add(pojo);
                adapter.notifyDataSetChanged();
            }

        }

And here i am retrieving value from pojo  so that i can set those in some textviews

     attendance_pojo pojo= arrayList.get(position);
            String months= pojo.getMonth();
            Log.d("months",months);
            months= checkmonth(months);
            Log.d("datess",""+pojo.getDate());
            month.setText(months+" "+pojo.getYear());
            workdays.setText(""+pojo.getDatecounter());

But i am always getting 12 when I am getting Log of datess

    12-04 15:27:25.220 2523-2523/rock.school_hub D/months: 12
    12-04 15:27:25.226 2523-2523/rock.school_hub D/months: 12
    12-04 15:27:25.229 2523-2523/rock.school_hub D/months: 12
    12-04 15:27:25.236 2523-2523/rock.school_hub D/months: 12

As per my json First i should get 11 then 12, but in variable months, it is always showing 12

Body:
 pojo.setDatecounter(datecntr);

                Log.d("counter",""+datecntr);
                Log.d("kuqw",present+" "+absent);
                pojo.setPresent(""+present);
                pojo.setAbsent(""+absent);

put this code inside while{ }


问:
Filter EWS mailbox by recipient address using exchangelib
I'm writing a monitoring solution using python3 with exchangelib and trying to count messages in our team's mailbox. One of the criteria: recipient list must contain specific email address.

When i use filter() with author or subject arguments script is working fine and return correct results.

But when i tried to filter by to_recipients or to_recipients__contains (which is list-type field), script throws an exception:

```<code>ValueError: EWS does not support filtering on field 'to_recipients'
</code>```

Is there a way to filter mailbox by recipient email_address, avoiding to fetch all messages and than filtering it on the client side?

答:
[exchangelib maintainer here]

I don't think there is. You could try to flip the is_searchable flag on that field and search anyway, but I never could get filtering to work in my tests. I can't remember if it throws server errors, returns all items anyway, or returns an empty list.

I'm happy to accept patches it you do find a solution.

Body:
I'm writing a monitoring solution using python3 with exchangelib and trying to count messages in our team's mailbox. One of the criteria: recipient list must contain specific email address.

When i use filter() with author or subject arguments script is working fine and return correct results.

But when i tried to filter by to_recipients or to_recipients__contains (which is list-type field), script throws an exception:

ValueError: EWS does not support filtering on field 'to_recipients'

Is there a way to filter mailbox by recipient email_address, avoiding to fetch all messages and than filtering it on the client side?


问:
Are parentheses around the result significant in a return statement?
Is there a difference between these two statements inside a function?

```<code>bool returnValue = true;
// Code that does something
return(returnValue);
</code>```

and this?

```<code>bool returnValue = true;
// Code
return returnValue;
</code>```

The former has parentheses around returnValue.

答:
You're abusively slowing down the compiler!

The presence of parenthesis not only slow down the preprocessing phase, but they generate a more complicated Abstract Syntax Tree too: more memory, more computation.

From a semantic point of view ? They are exactly identical. Whether there are parenthesis or not the return statement will fully evaluate the expression before returning it.

Body:
Is there a difference between these two statements inside a function?

bool returnValue = true;
// Code that does something
return(returnValue);

and this?

bool returnValue = true;
// Code
return returnValue;

The former has parentheses around returnValue.


问:
Add before and after the string
```<code>$variable = 'for linebreak add 2 spaces at end';
</code>```

Value of this variable everytime changes.

How to add some text or html before and after this string?

E.g. if we want to add '
' before and '
' after, string should look like:

```<code>$variable = '<div>for linebreak add 2 spaces at end</div>';
</code>```

Title: Add before and after the string

Body:
$variable = 'for linebreak add 2 spaces at end';

Value of this variable everytime changes.

How to add some text or html before and after this string?

E.g. if we want to add '
' before and '
' after, string should look like:

$variable = '
for linebreak add 2 spaces at end
';

Body:
What is the faster ways?

1. Join arrays?

1.1 Join arrays (with unset)

The code below :

for($i=1;$i<1000;$i++){
    $string[]='lorem_';
    $string[]= $i;
    $string[]='_ipsum';
    $string = join('',$string);
    var_dump($string);
    unset($string);
}

generate this average performance:

.---------.----------------.--------------.--------------.
| Version | System time(s) | User time(s) | Memory (MiB) |
|---------|----------------|--------------|--------------|
|   5.6   |      0.016     |     0.061    |    20.60     |
|   7.0   |      0.009     |     0.010    |    16.69     |
|   7.1   |      0.011     |     0.011    |    24.18     |
|   7.2   |      0.003     |     0.017    |    19.41     |
'---------'----------------'--------------'--------------'

source: https://3v4l.org/8YK1H/perf#output

1.2 Join arrays (without unset)

The code below :

for($i=1;$i<1000;$i++){
    $string = [];
    $string[]='lorem_';
    $string[]= $i;
    $string[]='_ipsum';
    $string = join('',$string);
    var_dump($string);
    // unset($string);
}

generate this average performance:

.---------.----------------.--------------.--------------.
| Version | System time(s) | User time(s) | Memory (MiB) |
|---------|----------------|--------------|--------------|
|   5.6   |      0.017     |     0.068    |    20.58     |
|   7.0   |      0.012     |     0.013    |    16.13     |
|   7.1   |      0.021     |     0.012    |    23.23     |
|   7.2   |      0.013     |     0.010    |    17.65     |
'---------'----------------'--------------'--------------'

source: https://3v4l.org/kU4QG/perf#output

2. Shorthand operator?

2.1 Shorthand operator (with unset)

The code below :

for($i=1;$i<1000;$i++){
    $string = 'lorem_';
    $string .= $i;
    $string .= '_ipsum';
    // $string = join('',$string);
    var_dump($string);
    unset($string);
}

generate this average performance:

.---------.----------------.--------------.--------------.
| Version | System time(s) | User time(s) | Memory (MiB) |
|---------|----------------|--------------|--------------|
|   5.6   |      0.012     |     0.059    |    20.60     |
|   7.0   |      0.008     |     0.011    |    16.65     |
|   7.1   |      0.014     |     0.012    |    24.22     |
|   7.2   |      0.012     |     0.009    |    19.08     |
'---------'----------------'--------------'--------------'

source: https://3v4l.org/cCoSC/perf#output

2.2 Shorthand operator (without unset)

The code below :

for($i=1;$i<1000;$i++){
    $string = 'lorem_';
    $string .= $i;
    $string .= '_ipsum';
    // $string = join('',$string);
    var_dump($string);
    // unset($string);
}

generate this average performance:

.---------.----------------.--------------.--------------.
| Version | System time(s) | User time(s) | Memory (MiB) |
|---------|----------------|--------------|--------------|
|   5.6   |      0.011     |     0.059    |    20.60     |
|   7.0   |      0.008     |     0.011    |    16.70     |
|   7.1   |      0.014     |     0.011    |    24.22     |
|   7.2   |      0.010     |     0.010    |    19.33     |
'---------'----------------'--------------'--------------'

source: https://3v4l.org/iKnaV/perf#output

3. One line concat?

3.1 One line concatenation (with unset)

The code below :

for($i=1;$i<1000;$i++){
    $string = 'lorem_' . $i . '_ipsum';
    // $string .= $i;
    // $string .= '_ipsum';
    // $string = join('',$string);
    var_dump($string);
    unset($string);
}

generate this average performance:

.---------.----------------.--------------.--------------.
| Version | System time(s) | User time(s) | Memory (MiB) |
|---------|----------------|--------------|--------------|
|   5.6   |      0.015     |     0.066    |    20.60     |
|   7.0   |      0.008     |     0.012    |    16.68     |
|   7.1   |      0.014     |     0.014    |    24.23     |
|   7.2   |      0.010     |     0.014    |    19.45     |
'---------'----------------'--------------'--------------'

source: https://3v4l.org/tv4X0/perf#output

3.2 One line concatenation (without unset)

The code below :

for($i=1;$i<1000;$i++){
    $string = 'lorem_' . $i . '_ipsum';
    // $string .= $i;
    // $string .= '_ipsum';
    // $string = join('',$string);
    var_dump($string);
    // unset($string);
}

generate this average performance:

.---------.----------------.--------------.--------------.
| Version | System time(s) | User time(s) | Memory (MiB) |
|---------|----------------|--------------|--------------|
|   5.6   |      0.012     |     0.056    |    20.65     |
|   7.0   |      0.008     |     0.008    |    16.69     |
|   7.1   |      0.014     |     0.010    |    24.17     |
|   7.2   |      0.007     |     0.011    |    19.39     |
'---------'----------------'--------------'--------------'

source: https://3v4l.org/mF0YW/perf#output

If merge all results by PHP version:

PHP 5.6

.-------------.----------------.--------------.--------------.
|     Code    | System time(s) | User time(s) | Memory (MiB) |
|-------------|----------------|--------------|--------------|
|         1.1 |      0.016     |     0.061    |    20.60     |
|         1.2 |      0.017     |     0.068    | >> 20.58     |
|             |-- -- -- -- -- -|-- -- -- -- --|-- -- -- -- --|
| (average) 1 |      0.0165    |     0.0645   | >> 20.59     |
|-------------|----------------|--------------|--------------|
|         2.1 |      0.012     |     0.059    |    20.60     |
|         2.2 |   >> 0.011     |     0.059    |    20.60     |
|             |-- -- -- -- -- -|-- -- -- -- --|-- -- -- -- --|
| (average) 2 |   >> 0.0115    |  >> 0.059    |    20.60     |
|-------------|----------------|--------------|--------------|
|         3.1 |      0.015     |     0.066    |    20.60     |
|         3.2 |      0.012     |  >> 0.056    |    20.65     |
|             |-- -- -- -- -- -|-- -- -- -- --|-- -- -- -- --|
| (average) 3 |      0.0135    |     0.061    |    20.625    |
'-------------'----------------'--------------'--------------'

PHP 7.0

.-------------.----------------.--------------.--------------.
|     Code    | System time(s) | User time(s) | Memory (MiB) |
|-------------|----------------|--------------|--------------|
|         1.1 |      0.009     |     0.010    |    16.69     |
|         1.2 |      0.012     |     0.013    | >> 16.13     |
|             |-- -- -- -- -- -|-- -- -- -- --|-- -- -- -- --|
| (average) 1 |      0.0105    |     0.0115   | >> 16.41     |
|-------------|----------------|--------------|--------------|
|         2.1 |   >> 0.008     |     0.011    |    16.65     |
|         2.2 |   >> 0.008     |     0.011    |    16.70     |
|             |-- -- -- -- -- -|-- -- -- -- --|-- -- -- -- --|
| (average) 2 |   >> 0.008     |     0.011    |    16.675    |
|-------------|----------------|--------------|--------------|
|         3.1 |   >> 0.008     |     0.012    |    16.68     |
|         3.2 |   >> 0.008     |  >> 0.008    |    16.69     |
|             |-- -- -- -- -- -|-- -- -- -- --|-- -- -- -- --|
| (average) 3 |   >> 0.008     |  >> 0.010    |    16.685    |
'-------------'----------------'--------------'--------------'

PHP 7.1

.-------------.----------------.--------------.--------------.
|     Code    | System time(s) | User time(s) | Memory (MiB) |
|-------------|----------------|--------------|--------------|
|         1.1 |   >> 0.011     |     0.011    |    24.18     |
|         1.2 |      0.021     |     0.012    | >> 23.23     |
|             |-- -- -- -- -- -|-- -- -- -- --|-- -- -- -- --|
| (average) 1 |      0.016     |  >> 0.0115   | >> 23.705    |
|-------------|----------------|--------------|--------------|
|         2.1 |      0.014     |     0.012    |    24.22     |
|         2.2 |      0.014     |     0.011    |    24.22     |
|             |-- -- -- -- -- -|-- -- -- -- --|-- -- -- -- --|
| (average) 2 |   >> 0.014     |  >> 0.0115   |    24.22     |
|-------------|----------------|--------------|--------------|
|         3.1 |      0.014     |     0.014    |    24.23     |
|         3.2 |      0.014     |  >> 0.010    |    24.17     |
|             |-- -- -- -- -- -|-- -- -- -- --|-- -- -- -- --|
| (average) 3 |   >> 0.014     |     0.012    |    24.20     |
'-------------'----------------'--------------'--------------'

PHP 7.2

.-------------.----------------.--------------.--------------.
|     Code    | System time(s) | User time(s) | Memory (MiB) |
|-------------|----------------|--------------|--------------|
|         1.1 |   >> 0.003     |     0.017    |    19.41     |
|         1.2 |      0.013     |     0.010    | >> 17.65     |
|             |-- -- -- -- -- -|-- -- -- -- --|-- -- -- -- --|
| (average) 1 |   >> 0.008     |     0.0135   | >> 18.53     |
|-------------|----------------|--------------|--------------|
|         2.1 |      0.012     |  >> 0.009    |    19.08     |
|         2.2 |      0.010     |     0.010    |    19.33     |
|             |-- -- -- -- -- -|-- -- -- -- --|-- -- -- -- --|
| (average) 2 |      0.011     |  >> 0.0905   |    19.205    |
|-------------|----------------|--------------|--------------|
|         3.1 |      0.010     |     0.014    |    19.45     |
|         3.2 |      0.007     |     0.011    |    19.39     |
|             |-- -- -- -- -- -|-- -- -- -- --|-- -- -- -- --|
| (average) 3 |      0.0085    |     0.0125   |    19.42     |
'-------------'----------------'--------------'--------------'

Conclusion

For the system time, the faster way (0.003 second) is to use join arrays (with unset) in PHP 7.2.0.

For the user time, the faster way (0.003 second) is to use oneline concatenation without unset in PHP 7.0.22.

For memory usage, the "most ecomonical" (14.47 MiB) way is to use join array without unset in PHP 7.0.14.


问:
Facebook Ads, possible to add dynamic parameters in URL for FB to populate later?
I need to add ad_group id to ad's URL. However, I can only obtain the id after creating the ad, not before. Is it possible for me to specify a parameter in the URL so that it can be populated by FB when the ad is created? I know double click of Google supports this.</p>

答:
Update: Facebook has recently published a list of dynamic parameters that will be populated in your URL's.
The list is available on their site</p>


问:
How to dynamically add a class to manual class names?
I need to add a dynamic class to a list of regular classes, but have no idea how (I'm using babel), something like this:

```<code><div className="wrapper searchDiv {this.state.something}">
...
</div>
</code>```

Any ideas?

答:
You can use this npm package. It handles everything and has options for static and dynamic classes based on a variable or a function.</p>

```<code>// Support for string arguments
getClassNames('class1', 'class2');

// support for Object
getClassNames({class1: true, class2 : false});

// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], {
    class5 : function() { return false; },
    class6 : function() { return true; }
});

<div className={getClassNames({class1: true, class2 : false})} />
</code>```

Body:
I need to add a dynamic class to a list of regular classes, but have no idea how (I'm using babel), something like this:

...

Any ideas?

Body:
You can use this npm package. It handles everything and has options for static and dynamic classes based on a variable or a function.

// Support for string arguments
getClassNames('class1', 'class2');

// support for Object
getClassNames({class1: true, class2 : false});

// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], {
    class5 : function() { return false; },
    class6 : function() { return true; }
});

<div className={getClassNames({class1: true, class2 : false})} />