问:
HTML extend height of div

div.div1 {
  position: relative;
  border: 1px solid black;
  height: 100px;
  width: 100px;
  padding: 10px;
}

div.div2 {
  background-color: gray;
  border: 1px solid black;
  padding: 10px;
}

div.div3 {
  position: absolute;
  border: 1px solid red;
  height: 20px;
  width: 20px;
  bottom: 10px;
  left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="div1">
  <div class="div2">Test 123</div>
  <div class="div3">A</div>
</div></code>```

I use the above code to display a big div with two divs in it. For the first one I use position: absolute to place it on bottom left of the div.

How can I extend the height of the second gray one so that it's 5 pixels above the first, but without having to measure its exact height in pixel (like the pic below)? I can set height: 50px; for example but is there another way?

答:
EDIT: I suggest that, if you can focus on the modern browser features, going the flexbox way as shown by Pete is definitely a cleaner approach than the ones I've shown bellow. That being said, here are the alternatives:

You can use calc to dynamically determine the height of div2:

div.div1 {
  position: relative;
  border: 1px solid black;
  height: 100px;
  width: 100px;
  padding: 10px;
}

div.div2 {
  background-color: gray;
  border: 1px solid black;
  padding: 10px;
  height: calc(
    100%
    - 20px /* div1: padding top and bottom */
    - 2px  /* div1: border top and bottom */
    - 20px /* div3: height */
    - 2px  /* div3: border top and bottom*/
    - 5px  /* desired separation*/
  );
}

div.div3 {
  position: absolute;
  border: 1px solid red;
  height: 20px;
  width: 20px;
  bottom: 10px;
  left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="div1">
  <div class="div2">Test 123</div>
  <div class="div3">A</div>
</div></code>```

You can avoid including padding and border width in your calculations if you set the box-sizing for your divs to border-box (You might want to set this for all elements):

div {
  box-sizing: border-box;
}

div.div1 {
  position: relative;
  border: 1px solid black;
  height: 100px;
  width: 100px;
  padding: 10px;
}

div.div2 {
  background-color: gray;
  border: 1px solid black;
  padding: 10px;
  height: calc(
    100%
    - 20px /* div3: height */
    - 5px  /* desired separation */
  );
}

div.div3 {
  position: absolute;
  border: 1px solid red;
  height: 20px;
  width: 20px;
  bottom: 10px;
  left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="div1">
  <div class="div2">Test 123</div>
  <div class="div3">A</div>
</div></code>```

Title: HTML extend height of div

Body:
div.div1 {
  position: relative;
  border: 1px solid black;
  height: 100px;
  width: 100px;
  padding: 10px;
}

div.div2 {
  background-color: gray;
  border: 1px solid black;
  padding: 10px;
}

div.div3 {
  position: absolute;
  border: 1px solid red;
  height: 20px;
  width: 20px;
  bottom: 10px;
  left: 10px;
}

Test 123

A

I use the above code to display a big div with two divs in it. For the first one I use position: absolute to place it on bottom left of the div.

How can I extend the height of the second gray one so that it's 5 pixels above the first, but without having to measure its exact height in pixel (like the pic below)? I can set height: 50px; for example but is there another way?

Body:
EDIT: I suggest that, if you can focus on the modern browser features, going the flexbox way as shown by Pete is definitely a cleaner approach than the ones I've shown bellow. That being said, here are the alternatives:

You can use calc to dynamically determine the height of div2:

div.div1 {
  position: relative;
  border: 1px solid black;
  height: 100px;
  width: 100px;
  padding: 10px;
}

div.div2 {
  background-color: gray;
  border: 1px solid black;
  padding: 10px;
  height: calc(
    100%
    - 20px /* div1: padding top and bottom */
    - 2px  /* div1: border top and bottom */
    - 20px /* div3: height */
    - 2px  /* div3: border top and bottom*/
    - 5px  /* desired separation*/
  );
}

div.div3 {
  position: absolute;
  border: 1px solid red;
  height: 20px;
  width: 20px;
  bottom: 10px;
  left: 10px;
}

<div class="div1">
  <div class="div2">Test 123</div>
  <div class="div3">A</div>
</div>

You can avoid including padding and border width in your calculations if you set the box-sizing for your divs to border-box (You might want to set this for all elements):

div {
  box-sizing: border-box;
}

div.div1 {
  position: relative;
  border: 1px solid black;
  height: 100px;
  width: 100px;
  padding: 10px;
}

div.div2 {
  background-color: gray;
  border: 1px solid black;
  padding: 10px;
  height: calc(
    100%
    - 20px /* div3: height */
    - 5px  /* desired separation */
  );
}

div.div3 {
  position: absolute;
  border: 1px solid red;
  height: 20px;
  width: 20px;
  bottom: 10px;
  left: 10px;
}

<div class="div1">
  <div class="div2">Test 123</div>
  <div class="div3">A</div>
</div>


来源: stackexchange

问:
Good books on Silverlight and WCF
Can anyone suggest some good books that practically describe Silverlight and WCF?</p>

答: If you're looking for info of how to use SL for business apps (WCF RIA services...) this one is a good one</p>

ContentLicense: CC BY-SA 2.5

Title: Good books on Silverlight and WCF


问:
How to remove item from recyclerView in android
In my application I should use recyclerView and remove some items.

I want remove some items from recyclerview and for this I write below code in Adapter :

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

    private Context context;
    private List<TvTonightResult> model;

    public MyAdapter (Context context, List<TvTonightResult> model) {
        this.context = context;
        this.model = model;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_tv_tonight, parent, false);

        return new ViewHolder(view);
    }

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

        holder.tvTonightTitle.setText(Html.fromHtml(model.get(position).getName()));
        Glide.with(context)
                .load(model.get(position).getImageUrl())
                .placeholder(R.drawable.default_image)
                .override(600, 900)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                                                   Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(holder.tvTonightImage);

        long time = 5 * 1000;
        holder.tvTonightTimeCounter.start(time);
        holder.tvTonightTimeCounter.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
            @Override
            public void onEnd(CountdownView cv) {
                removeItem(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return 4;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private ImageView tvTonightImage, tvTonightChannel;
        private TextView tvTonightTitle, tvTonightDate;
        private CountdownView tvTonightTimeCounter;

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

            tvTonightImage = (ImageView) itemView.findViewById(R.id.row_tvTonightImage);
            tvTonightChannel = (ImageView) itemView.findViewById(R.id.row_tvTonightChannelImage);
            tvTonightTitle = (TextView) itemView.findViewById(R.id.row_tvTonightTitle);
            tvTonightTimeCounter = (CountdownView) itemView.findViewById(R.id.row_tvTonightTime);

        }
    }

    private void removeItem(int position) {
        model.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, model.size());
    }
}
</code>```

I want when run this code, remove item :

```<code>holder.tvTonightTimeCounter.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
                @Override
                public void onEnd(CountdownView cv) {
                    removeItem(position);
                }
            });
</code>```

But show me this error :

```<code>FATAL EXCEPTION: main
Process: com.example.app, PID: 9711
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.remove(ArrayList.java:477)
    at com.example.app.Adapters.TvTonightAdapter.removeItem(TvTonightAdapter.java:102)
    at com.example.app.Adapters.TvTonightAdapter.access$300(MyAdapter.java:29)
    at com.example.app.Adapters.TvTonightAdapter$2.onEnd(MyAdapter.java:74)
    at com.example.app.Utils.Componenets.CountDownTimer.CountdownView$1.onFinish(CountdownView.java:129)
    at com.example.app.Utils.Componenets.CountDownTimer.CustomCountDownTimer$1.handleMessage(CustomCountDownTimer.java:74)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6247)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
</code>```

How can I fix this error and remove item from recyclerview?

答:
I think you should call remove(holder.getAdapterPosition()) instead of remove(position) because, when the holder's countdown finishes, it might have changed its position.

Suppose the following situation:

1º holder -> 5 seconds countdown

2º holder -> 10 seconds countdown

Since the second holder finishes after the first one, after 10 seconds,  remove(1) will be called but, since the first holder has already been removed, the second holder's position will be 0. Hence, it should call remove(0) instead of remove(1) (which will cause an IndexOutOfBoundsException).

ContentLicense: CC BY-SA 3.0

Body:
In my application I should use recyclerView and remove some items.

I want remove some items from recyclerview and for this I write below code in Adapter :

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

    private Context context;
    private List<TvTonightResult> model;

    public MyAdapter (Context context, List<TvTonightResult> model) {
        this.context = context;
        this.model = model;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_tv_tonight, parent, false);

        return new ViewHolder(view);
    }

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

        holder.tvTonightTitle.setText(Html.fromHtml(model.get(position).getName()));
        Glide.with(context)
                .load(model.get(position).getImageUrl())
                .placeholder(R.drawable.default_image)
                .override(600, 900)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                                                   Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(holder.tvTonightImage);

        long time = 5 * 1000;
        holder.tvTonightTimeCounter.start(time);
        holder.tvTonightTimeCounter.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
            @Override
            public void onEnd(CountdownView cv) {
                removeItem(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return 4;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private ImageView tvTonightImage, tvTonightChannel;
        private TextView tvTonightTitle, tvTonightDate;
        private CountdownView tvTonightTimeCounter;

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

            tvTonightImage = (ImageView) itemView.findViewById(R.id.row_tvTonightImage);
            tvTonightChannel = (ImageView) itemView.findViewById(R.id.row_tvTonightChannelImage);
            tvTonightTitle = (TextView) itemView.findViewById(R.id.row_tvTonightTitle);
            tvTonightTimeCounter = (CountdownView) itemView.findViewById(R.id.row_tvTonightTime);

        }
    }

    private void removeItem(int position) {
        model.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, model.size());
    }
}

I want when run this code, remove item :

holder.tvTonightTimeCounter.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
                @Override
                public void onEnd(CountdownView cv) {
                    removeItem(position);
                }
            });

But show me this error :

FATAL EXCEPTION: main
Process: com.example.app, PID: 9711
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.remove(ArrayList.java:477)
    at com.example.app.Adapters.TvTonightAdapter.removeItem(TvTonightAdapter.java:102)
    at com.example.app.Adapters.TvTonightAdapter.access$300(MyAdapter.java:29)
    at com.example.app.Adapters.TvTonightAdapter$2.onEnd(MyAdapter.java:74)
    at com.example.app.Utils.Componenets.CountDownTimer.CountdownView$1.onFinish(CountdownView.java:129)
    at com.example.app.Utils.Componenets.CountDownTimer.CustomCountDownTimer$1.handleMessage(CustomCountDownTimer.java:74)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6247)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)

How can I fix this error and remove item from recyclerview?


问:
Customize a bar plot - aligning bars with a table below the chart
Hope this is not out of topic.

I try to customize the code from this great answer using additional data:

```<code>df <- structure(list(year = 1998:2007, work = c(0L, 4L, 0L, 1L, 0L, 0L, 1L, 2L, 2L, 3L), confid = c(0L, 0L, 0L, 0L, 0L, 2L, 0L, 0L, 3L, 0L), jrs = c(0L, 1L, 0L, 0L, 1L, 9L, 6L, 4L, 21L, 2L)), .Names = c("year", "work", "confid", "jrs"), class = "data.frame", row.names = c(NA, -10L))

library(ggplot2)
library(reshape)
md <- melt(df, id=(c("year")))

library(grid)
library(gridExtra)

# Function to extract legend
# https://stackoverflow.com/a/13650878/496488
g_legend <- function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}

p = ggplot(data=md, aes(x=year, y=value, fill=variable) ) +
  geom_bar(stat="identity")+
  #theme(axis.text.x=element_text(angle=90, vjust=0.5, hjust=0.5))+
  ggtitle("Score Distribution") +
  labs(fill="")

# Extract the legend as a separate grob
leg = g_legend(p)

# Create a table grob
tab = t(df)
tab = tableGrob(tab, rows=NULL)
tab$widths <- unit(rep(1/ncol(tab), ncol(tab)), "npc")

# Lay out plot, legend, and table grob
grid.arrange(arrangeGrob(nullGrob(),
                         p + guides(fill=FALSE) +
                           theme(axis.text.x=element_blank(),
                                 axis.title.x=element_blank(),
                                 axis.ticks.x=element_blank()),
                         widths=c(1,8)),
             arrangeGrob(arrangeGrob(nullGrob(),leg,heights=c(1,10)),
                         tab, nullGrob(), widths=c(6,20,1)),
             heights=c(4,1))
</code>```

I tried to change the numbers at the end but I receive again the same results. The table is smaller than the graph and the bars at the graph are not in the right position.

How could I customize the numbers at the end?

Here a screenshot of what I see:

In the image 1 I checked because should the bar be in the same line with 1999. As it is now it seems to 2 years. 2 in image shows the table with must have the same width with the plot and the years should be down from every corresponded bar.

答:
This would be achieved by modifying widths. I modified them as I wanted but you can get the idea that how it works by looking at modification below and also by playing with the numbers.

```<code># Lay out plot, legend, and table grob
grid.arrange(arrangeGrob(nullGrob(),
                     p + guides(fill=FALSE) +
                       theme(axis.text.x=element_blank(),
                             axis.title.x=element_blank(),
                             axis.ticks.x=element_blank()),
                     widths=c(1,8)),
         arrangeGrob(arrangeGrob(nullGrob(),leg,heights=c(1,10)), #Can ignore this change
                     tab, nullGrob(), widths=c(10,45,2)), #'6' to '10' is the vital change
         heights=c(5,1)) #Modified this to improve spacing between table and graph
</code>```

This would be the graph applying these changes at the end of your code:

Body:
Hope this is not out of topic.

I try to customize the code from this great answer using additional data:

df <- structure(list(year = 1998:2007, work = c(0L, 4L, 0L, 1L, 0L, 0L, 1L, 2L, 2L, 3L), confid = c(0L, 0L, 0L, 0L, 0L, 2L, 0L, 0L, 3L, 0L), jrs = c(0L, 1L, 0L, 0L, 1L, 9L, 6L, 4L, 21L, 2L)), .Names = c("year", "work", "confid", "jrs"), class = "data.frame", row.names = c(NA, -10L))

library(ggplot2)
library(reshape)
md <- melt(df, id=(c("year")))

library(grid)
library(gridExtra)

# Function to extract legend
# https://stackoverflow.com/a/13650878/496488
g_legend <- function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}

p = ggplot(data=md, aes(x=year, y=value, fill=variable) ) +
  geom_bar(stat="identity")+
  #theme(axis.text.x=element_text(angle=90, vjust=0.5, hjust=0.5))+
  ggtitle("Score Distribution") +
  labs(fill="")

# Extract the legend as a separate grob
leg = g_legend(p)

# Create a table grob
tab = t(df)
tab = tableGrob(tab, rows=NULL)
tab$widths <- unit(rep(1/ncol(tab), ncol(tab)), "npc")

# Lay out plot, legend, and table grob
grid.arrange(arrangeGrob(nullGrob(),
                         p + guides(fill=FALSE) +
                           theme(axis.text.x=element_blank(),
                                 axis.title.x=element_blank(),
                                 axis.ticks.x=element_blank()),
                         widths=c(1,8)),
             arrangeGrob(arrangeGrob(nullGrob(),leg,heights=c(1,10)),
                         tab, nullGrob(), widths=c(6,20,1)),
             heights=c(4,1))

I tried to change the numbers at the end but I receive again the same results. The table is smaller than the graph and the bars at the graph are not in the right position.

How could I customize the numbers at the end?

Here a screenshot of what I see:

In the image 1 I checked because should the bar be in the same line with 1999. As it is now it seems to 2 years. 2 in image shows the table with must have the same width with the plot and the years should be down from every corresponded bar.

Body:
This would be achieved by modifying widths. I modified them as I wanted but you can get the idea that how it works by looking at modification below and also by playing with the numbers.

# Lay out plot, legend, and table grob
grid.arrange(arrangeGrob(nullGrob(),
                     p + guides(fill=FALSE) +
                       theme(axis.text.x=element_blank(),
                             axis.title.x=element_blank(),
                             axis.ticks.x=element_blank()),
                     widths=c(1,8)),
         arrangeGrob(arrangeGrob(nullGrob(),leg,heights=c(1,10)), #Can ignore this change
                     tab, nullGrob(), widths=c(10,45,2)), #'6' to '10' is the vital change
         heights=c(5,1)) #Modified this to improve spacing between table and graph

This would be the graph applying these changes at the end of your code:


问:
Keep 2 <select> in sync when value changes
I have two <select>s with the same <option>s.

If a user selects a value in the first one, the value on the second one should change as well to keep both in sync.

This is what I tried so far:

function data_copy() {
  if (document.form1.copy[0].checked) {
    for (i = document.form1.state.options.length-1; i >= 0; i--) {
      if (document.form1.state.options[i].selected)
        document.form1.state2.options[i].selected = true;
    }
  } else {
    document.form1.state2.options[0].selected = true;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000">
  <table width='400' border='0' cellspacing='1' cellpadding='0'>
    <form name=form1 method=post action='http://www.plus2net.com'>

      <tr><td >State</td><td>
        <SELECT NAME="state" onchange="data_copy()">
          <Option value="One">One</option>
          <Option value="Two">Two</option>
          <Option value="Three">Three</option>
          <Option value="Four">Four</option>
        </SELECT>
      </td></tr>

      <tr><td >
      <tr><td >State</td><td>
        <SELECT NAME="state2" >
          <Option value="One">One</option>
          <Option value="Two">Two</option>
          <Option value="Three">Three</option>
          <Option value="Four">Four</option>
        </SELECT>
      </td></tr>

      <tr><td colspan=2 align=center><input type=submit value=Submit>
    </form></td></tr>
  </table>
</body></code>```

答:
```<code>$("select[name='state']").on("change",function(){
    $("select[name='state2']").val($("select[name='state']").val());
}
</code>```

This will change the second select to the value of the first select when the first has its value changed

Body:
I have two <select>s with the same <option>s.

If a user selects a value in the first one, the value on the second one should change as well to keep both in sync.

This is what I tried so far:

function data_copy() {
  if (document.form1.copy[0].checked) {
    for (i = document.form1.state.options.length-1; i >= 0; i--) {
      if (document.form1.state.options[i].selected)
        document.form1.state2.options[i].selected = true;
    }
  } else {
    document.form1.state2.options[0].selected = true;
  }
}

    <form name=form1 method=post action='http://www.plus2net.com'>

State
        <SELECT NAME="state" onchange="data_copy()">
          <Option value="One">One</option>
          <Option value="Two">Two</option>
          <Option value="Three">Three</option>
          <Option value="Four">Four</option>
        </SELECT>

State
        <SELECT NAME="state2" >
          <Option value="One">One</option>
          <Option value="Two">Two</option>
          <Option value="Three">Three</option>
          <Option value="Four">Four</option>
        </SELECT>

<input type=submit value=Submit>
    </form>

Body:
$("select[name='state']").on("change",function(){
    $("select[name='state2']").val($("select[name='state']").val());
}

This will change the second select to the value of the first select when the first has its value changed


问:
Hyperledger Fabric 1.0 CA in different hosts
I already read de hyperledger read docs about the CA in Fabric 1.0, http://hyperledger-fabric.readthedocs.io/en/latest/Setup/ca-setup.html?highlight=ca, but I can't understand how will work the CA if I need to run tow CAs, in same Blockchain, in different organizations. All docker file that I sow don't have a example that run in different hosts, in different organizations.

Any can help me?

答:
There can be more than one CA Server. For example, each organization can have it's own CA Server.

Once you have initialized all your CA servers you need, you have to get the root certificates. That's possible thanks to the fabric-ca-client getcacerts command.

More info at: http://hyperledger-fabric-ca.readthedocs.io/en/latest/users-guide.html#getting-a-ca-certificate-chain-from-another-fabric-ca-server


问:
Eclipse Setting verbose:class Flag for Launch Configuration
The java.exe command supports a 'verbose' flag which enables things like seeing from which file a class loads.  Does Eclipse supporting setting this flag for a launch configuration?

Here's a site that explains the 'verbose' flag about which I'm speaking

答:
Does Eclipse supporting setting this flag for a launch configuration?

Yes! Eclipse supports

Goto Run configurations

select Arguments tab

click VM Arguments and type -verbose flag

Click Run

Boom!!!!

Check out the screen shots below.

1)

2)

3)

4)


问:
Impersonation to install application c#
I am trying to install windows update patch(patch.msu) in a non admin account using impersonation class provided here http://stackoverflow.com/questions/125341/how-do-you-do-impersonation-in-net
I am hardcoding the username,passowrd and domain of that of Administrator .
I tried several LogonTypes but no impact and i get the following error/exception.

"Either a required impersonation level was not provided, or the provided impersonation" .

I have no clue how to proceed further ,we need to install certain patches on our customer systems with out sharing admin details to them.
Your guidance on this is highly appreciated.

My code sample

```<code>    try
    {

        using (Impersonation impersonate = new Impersonation(Environment.UserDomainName,
                "administrator", "XXXXXX"))
        {
                Process proc = new Process();
                proc.StartInfo.FileName = "wusa.exe";
                proc.StartInfo.Arguments = strPath;
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.Verb = "runas";
                proc.Start();
                proc.WaitForExit();
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.Message);
    }
</code>```

答:
This is due to a security update long ago.

The "Impersonate a client after authentication" and "Create global objects" user rights were first introduced in Windows 2000 Service Pack 4 to help to increase security in Windows.

Overview of the "Impersonate a Client After Authentication" and the "Create Global Objects" Security Settings (821546.KB.EN-US.2.2)

When you assign the "Impersonate a client after authentication" user right to a user, you permit programs that run on behalf of that user to impersonate a client. This security setting helps to prevent unauthorized servers from impersonating clients that connect to it through methods such as remote procedure calls (RPC) or named pipes.

As you want to impersonate an domain administrator you need to add those user rights.

By default, members of the device's local Administrators group and the device's local Service account are assigned the "Impersonate a client after authentication" user right.

Solution

IMPORTANT: This does not give full administrator permissions to the user to install other applications.

The action for the first step is dependent on the environment:

If you are using Active Directory Group Policies edit the Domain Security Policy on the Domain Controller:

Click Start -> Programs -> Administrative Tools -> Domain Security Policy

If you are not using Active Directory Group Policies, change the configuration on the local computer

Click Start -> Settings -> Control Panel -> Administrative Tools -> Local Security Policies

Then

Expand Local Policies and select User Rights Assignment.

In the right pane, double-click Impersonate a client after authentication.

In the Security Policy Setting dialog box, click Add User or Group.

In the Select Users, Computers or Groups dialog box, type the name of the Group or User who will run the application.

Select Check Names and verify the name is correct.

Repeat the steps applied to the Impersonate a client after authentication setting to the Create global objects setting.

Title: Impersonation to install application c#

Body:
I am trying to install windows update patch(patch.msu) in a non admin account using impersonation class provided here http://stackoverflow.com/questions/125341/how-do-you-do-impersonation-in-net
I am hardcoding the username,passowrd and domain of that of Administrator .
I tried several LogonTypes but no impact and i get the following error/exception.

"Either a required impersonation level was not provided, or the provided impersonation" .

I have no clue how to proceed further ,we need to install certain patches on our customer systems with out sharing admin details to them.
Your guidance on this is highly appreciated.

My code sample

    try
    {

        using (Impersonation impersonate = new Impersonation(Environment.UserDomainName,
                "administrator", "XXXXXX"))
        {
                Process proc = new Process();
                proc.StartInfo.FileName = "wusa.exe";
                proc.StartInfo.Arguments = strPath;
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.Verb = "runas";
                proc.Start();
                proc.WaitForExit();
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.Message);
    }


问:
How can I dynamically load and stream large video files to IE which doesn't send a range header?
A while back I found this function in some tutorial for streaming video so that the whole file doesn't need to be loaded into RAM for the file to be served (so you can serve big video files without crashing due to exceeding the memory cap of Node.js - which isn't hard to exceed with a movie-length video file, and increasing memory allocation is just a band-aid solution).

```<code>var fs = require("fs"),
    http = require("http"),
    url = require("url"),
    path = require("path");
var dirPath = process.cwd();
var videoReqHandler = function(req, res, pathname) {
    var file = dirPath + "/client" + pathname;
    var range = req.headers.range;
    var positions = range.replace(/bytes=/, "").split("-");
    var start = parseInt(positions[0], 10);
    fs.stat(file, function(err, stats) {
        if (err) {
            throw err;
        } else {
            var total = stats.size;
            var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
            var chunksize = (end - start) + 1;
            res.writeHead(206, {
                "Content-Range" : "bytes " + start + "-" + end + "/" + total,
                "Accept-Ranges" : "bytes",
                "Content-Length" : chunksize,
                "Content-Type" : "video/mp4"
            });
            var stream = fs.createReadStream(file, {
                start : start,
                end : end
            }).on("open", function() {
                stream.pipe(res);
            }).on("error", function(err) {
                res.end(err);
            });
        }
    });
};
module.exports.handle = videoReqHandler;
</code>```

It works fine in Chrome and FF, however, when Internet Explorer, or Edge, if you will, (new name, same pathetic feature support) requests an mp4, it crashes the server.

```<code>var positions = range.replace(/bytes=/, "").split("-");
                     ^
TypeError: Cannot read property 'replace' of undefined
</code>```

I suspect that's because of the fact that range headers aren't mandatory, and this function requires them.

My question is, how can I modify this function to avoid crashing when the range header isn't sent? I don't know much about headers or video streaming, and I'm pretty iffy on my understanding of reading files in chunks, so I could really use some help on this function which involves all three.

What I've Tried Based on Comments

So far, based on the answer @AndréDion linked:

Figured it out. IE11 does support pseudo streaming but it wants the
  "Accept-Ranges: bytes" header before it will bother requesting a
  range, so the server needs to respond with that regardless of whether
  it is actually sending a byte range. I had to modify my vid-streamer
  module to do that.

I tried wrapping the handler code in:

```<code>if (req.headers.range) {
    console.log('Video request sent WITH range header!');
    // ... handler code ...
} else {
    console.log('Video request sent without range header!');
    res.writeHead(206, {
        "Accept-Ranges": "bytes"
    });
    res.end();
}
</code>```

but nothing seems to happen - the server stops crashing, and continues to work on other browsers, but IE doesn't seem to be loading the video. I was expecting for IE to wait for that response then send another request, this time including a range header, but that doesnt appear to be happening.

Maybe I need to send a different response code than 206 when sending IE the accept-ranges header? I have no idea what it would be, but when I respond with the accept-rages header, IE seems to repeat the request twice (but not with the range header included, which is what I need).

As it stands now, if I run the server with the conditional as shown above, then try to load the video once in IE, then try to load it in Chrome, I get these logs:

```<code>Video request sent without range header!
Video request sent without range header!
Video request sent without range header!
Video request sent WITH range header!
</code>```

IE sends three requests without range headers, Chrome of course always sends the range header as expected, sending one request and successfully loading the video. And I'm just not sure where to go from here.

答:
I understand that Viziionary wants to stick to vanilla Node.js, but for anyone else who sees this and isn't so particular about sticking to Node, here are a few alternatives that don't involve manually serving static files.

If you want to stick to Node but you're fine with adding a framework, the Express framework has functions for serving static files and directories. With Express one or two lines of code will let you serve static files with range request and etag support. It's a lot easier than programming your own request handler.

If you're fine with stepping outside of Node, you can pair Node and Nginx together. In this configuration Nginx is a frontend that serves static files and proxies web requests to your Node server. In fact, Nginx was designed to work this way. Note that you can proxy to any number of entirely different servers and

You can also do this with Apache on the frontend, I leave it to you to look up how. I've never done it, so all I could do would be to direct you towards a helpful tutorial.

I'm sure there are other configurations, but this should give you some food for thought. For most small to mid size websites you'll be hard pressed to notice any negative effects of using one system or the other. If you're running a large website or service, then you'd better do your homework because there are lots of other options and factors to consider: CDNs, other scripting languages, caching, scalability, etc., etc.

Body:
A while back I found this function in some tutorial for streaming video so that the whole file doesn't need to be loaded into RAM for the file to be served (so you can serve big video files without crashing due to exceeding the memory cap of Node.js - which isn't hard to exceed with a movie-length video file, and increasing memory allocation is just a band-aid solution).

var fs = require("fs"),
    http = require("http"),
    url = require("url"),
    path = require("path");
var dirPath = process.cwd();
var videoReqHandler = function(req, res, pathname) {
    var file = dirPath + "/client" + pathname;
    var range = req.headers.range;
    var positions = range.replace(/bytes=/, "").split("-");
    var start = parseInt(positions[0], 10);
    fs.stat(file, function(err, stats) {
        if (err) {
            throw err;
        } else {
            var total = stats.size;
            var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
            var chunksize = (end - start) + 1;
            res.writeHead(206, {
                "Content-Range" : "bytes " + start + "-" + end + "/" + total,
                "Accept-Ranges" : "bytes",
                "Content-Length" : chunksize,
                "Content-Type" : "video/mp4"
            });
            var stream = fs.createReadStream(file, {
                start : start,
                end : end
            }).on("open", function() {
                stream.pipe(res);
            }).on("error", function(err) {
                res.end(err);
            });
        }
    });
};
module.exports.handle = videoReqHandler;

It works fine in Chrome and FF, however, when Internet Explorer, or Edge, if you will, (new name, same pathetic feature support) requests an mp4, it crashes the server.

var positions = range.replace(/bytes=/, "").split("-");
                     ^
TypeError: Cannot read property 'replace' of undefined

I suspect that's because of the fact that range headers aren't mandatory, and this function requires them.

My question is, how can I modify this function to avoid crashing when the range header isn't sent? I don't know much about headers or video streaming, and I'm pretty iffy on my understanding of reading files in chunks, so I could really use some help on this function which involves all three.

What I've Tried Based on Comments

So far, based on the answer @AndréDion linked:

Figured it out. IE11 does support pseudo streaming but it wants the
  "Accept-Ranges: bytes" header before it will bother requesting a
  range, so the server needs to respond with that regardless of whether
  it is actually sending a byte range. I had to modify my vid-streamer
  module to do that.

I tried wrapping the handler code in:

if (req.headers.range) {
    console.log('Video request sent WITH range header!');
    // ... handler code ...
} else {
    console.log('Video request sent without range header!');
    res.writeHead(206, {
        "Accept-Ranges": "bytes"
    });
    res.end();
}

but nothing seems to happen - the server stops crashing, and continues to work on other browsers, but IE doesn't seem to be loading the video. I was expecting for IE to wait for that response then send another request, this time including a range header, but that doesnt appear to be happening.

Maybe I need to send a different response code than 206 when sending IE the accept-ranges header? I have no idea what it would be, but when I respond with the accept-rages header, IE seems to repeat the request twice (but not with the range header included, which is what I need).

As it stands now, if I run the server with the conditional as shown above, then try to load the video once in IE, then try to load it in Chrome, I get these logs:

Video request sent without range header!
Video request sent without range header!
Video request sent without range header!
Video request sent WITH range header!

IE sends three requests without range headers, Chrome of course always sends the range header as expected, sending one request and successfully loading the video. And I'm just not sure where to go from here.


问:
What is the best way to cast from ArrayList to List in .Net 2.0
I have a ArrayList of type BookingData to List<BookingData> ?

I am using .net 2.0 so i cannot use arrayList.Cast<int>().ToList() , and I dont want to make here foreach loop , do you have better ideas ?

Thanks.

答:
Do note that something is going to have to enumerate the array-list to construct the List<T>; its only a matter of whether you do it yourself or leave it to some other (framework / utility) method.

If this is a one-off, the solution that you wish to avoid  (using an "in-place" foreach loop to do the conversion) is a perfectly reasonable option. If you find yourself doing this quite often, you could extract that out into a generic utility method, as in cdhowie's answer.

If your restriction is only that you must target .NET 2.0 (but can use C# 3), consider LINQBridge, which is a reimplementation of LINQ to Objects for .NET 2.0. This will let you use the Cast sample you've provided without change. It will work on C# 2 too, but you won't get the benefits of the extension-method syntax, better type-inference etc.

If you don't care about performance, nor do you want to go to the trouble of writing a utility method, you could use the in-built ArrayList.ToArray method to help out, by creating an intermediary array that plays well with List<T> (this isn't all that shorter than a foreach):

```<code>ArrayList arrayList = ...

// Create intermediary array
BookingData[] array = (BookingData[]) arrayList.ToArray(typeof(BookingData));

// Create the List<T> using the constructor that takes an IEnumerable<T>
List<BookingData> list = new List<BookingData>(array);
</code>```

Finally, I would suggest, if possible to abandon using the obsolete non-generic collection-classes altogether.

Body:
Do note that something is going to have to enumerate the array-list to construct the List<T>; its only a matter of whether you do it yourself or leave it to some other (framework / utility) method.

If this is a one-off, the solution that you wish to avoid  (using an "in-place" foreach loop to do the conversion) is a perfectly reasonable option. If you find yourself doing this quite often, you could extract that out into a generic utility method, as in cdhowie's answer.

If your restriction is only that you must target .NET 2.0 (but can use C# 3), consider LINQBridge, which is a reimplementation of LINQ to Objects for .NET 2.0. This will let you use the Cast sample you've provided without change. It will work on C# 2 too, but you won't get the benefits of the extension-method syntax, better type-inference etc.

If you don't care about performance, nor do you want to go to the trouble of writing a utility method, you could use the in-built ArrayList.ToArray method to help out, by creating an intermediary array that plays well with List<T> (this isn't all that shorter than a foreach):

ArrayList arrayList = ...

// Create intermediary array
BookingData[] array = (BookingData[]) arrayList.ToArray(typeof(BookingData));

// Create the List<T> using the constructor that takes an IEnumerable<T>
List<BookingData> list = new List<BookingData>(array);

Finally, I would suggest, if possible to abandon using the obsolete non-generic collection-classes altogether.


问:
How include 3rd party jars in maven project (compile, build, package) where adding local maven repo is not an option?
We have a git project that has some 3rd party jars which are not available in any Maven repo and are in a "lib" folder in the project. I need to include them for compiling, building and then package them into the WAR in WEB-INF/lib.

I cannot add them as a local maven repo from the command line because this projects needs to be buildable for anyone cloning the repo without requiring them to run extra commands (I have no way around this requirement).

I saw some people suggesting System scope but that then Maven won't package them into your WAR:

```<code><dependency>
    <groupId>com.roufid.tutorials</groupId>
    <artifactId>example-app</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${basedir}/lib/yourJar.jar</systemPath>
</dependency>
</code>```

How do I get these jars to be used for compiling/inspection, building and then packaged into the WAR?

答:
You can use :

System scope but make the packaging yourself via assembly plugin

A maven repo along with your project (i.e. maven repo on-the-fly, basically same as local repo but without having a extra moving part to worry about because this repo follows your project).

For Maven repo on-the-fly option, you can do as described here (which is, take any already existing Maven repo, which already contains your needed jars, such as your local one, put it in your project, and then reference this repo from your project using relative paths).

Body:
We have a git project that has some 3rd party jars which are not available in any Maven repo and are in a "lib" folder in the project. I need to include them for compiling, building and then package them into the WAR in WEB-INF/lib.

I cannot add them as a local maven repo from the command line because this projects needs to be buildable for anyone cloning the repo without requiring them to run extra commands (I have no way around this requirement).

I saw some people suggesting System scope but that then Maven won't package them into your WAR:

<dependency>
    <groupId>com.roufid.tutorials</groupId>
    <artifactId>example-app</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${basedir}/lib/yourJar.jar</systemPath>
</dependency>

How do I get these jars to be used for compiling/inspection, building and then packaged into the WAR?


问:
How to retrieve data from Realm's Results instance?
I just start to learn Realm data persistence, I start it from a iOS test project.
The realm object is declared like this:

```<code>class AchievementRecord: Object {

    dynamic var dateID:String = "1111-00-00"
    dynamic var date:String = "0000-00-00"
    dynamic var apple:Int = Int(0)

    override static func primaryKey() -> String? {
        return "dateID"
    }
}
</code>```

I initialise the object in View Controller's viewDidLoad() method as this:

```<code>class AchievementRecord: Object {

dynamic var dateID:String = "1111-00-00"
dynamic var date:String = "0000-00-00"
dynamic var apple:Int = Int(0)

override static func primaryKey() -> String? {
    return "dateID"
}
}
</code>```

then I declare another function to obtain the save data as:

```<code>let appleOn_05 = defaultRealm.objects(AchievementRecord.self).filter("dateID = '05-06-2017'")
print(appleOn_05)
</code>```

In the console, Xcode says:

Because I need to retrieve the apple's number, which is 22 in the console. How can I retrieve the apple's number to demo it on the screen, how can I do it? Thanks in advance.

答:
Results works like native Swift collections in many ways. If you are fetching a single object, you can just access it with Results.first let appleOn_05 = defaultRealm.objects(AchievementRecord.self).filter("dateID = '05-06-2017'").first

Subclasses of Object work like any other native class instance in Swift, so you can access their properties using the dot syntax.
let apple = appleOn_05.apple

Combining the two:

```<code>if let appleOn_05 = defaultRealm.objects(AchievementRecord.self).filter("dateID = '05-06-2017'").first {
    let apple = appleOn_05.apple
}
</code>```

Body:
I just start to learn Realm data persistence, I start it from a iOS test project.
The realm object is declared like this:

class AchievementRecord: Object {

    dynamic var dateID:String = "1111-00-00"
    dynamic var date:String = "0000-00-00"
    dynamic var apple:Int = Int(0)

    override static func primaryKey() -> String? {
        return "dateID"
    }
}

I initialise the object in View Controller's viewDidLoad() method as this:

class AchievementRecord: Object {

dynamic var dateID:String = "1111-00-00"
dynamic var date:String = "0000-00-00"
dynamic var apple:Int = Int(0)

override static func primaryKey() -> String? {
    return "dateID"
}
}

then I declare another function to obtain the save data as:

let appleOn_05 = defaultRealm.objects(AchievementRecord.self).filter("dateID = '05-06-2017'")
print(appleOn_05)

In the console, Xcode says:

Because I need to retrieve the apple's number, which is 22 in the console. How can I retrieve the apple's number to demo it on the screen, how can I do it? Thanks in advance.

Body:
Results works like native Swift collections in many ways. If you are fetching a single object, you can just access it with Results.first let appleOn_05 = defaultRealm.objects(AchievementRecord.self).filter("dateID = '05-06-2017'").first

Subclasses of Object work like any other native class instance in Swift, so you can access their properties using the dot syntax.
let apple = appleOn_05.apple

Combining the two:

if let appleOn_05 = defaultRealm.objects(AchievementRecord.self).filter("dateID = '05-06-2017'").first {
    let apple = appleOn_05.apple
}


问:
Unable to find explicit activity class and force close application
When I launch my application, it force closes and when I debug my program I kept getting error messages. I have 2 activities, the Authentication (where User log in) and Mainpage (this is the page when the user is logged in).

The problem here is when i'm not logged in, I can still log in. If i'm logged in it should take me to Mainpage (Activity), but now the error [see below] shows up.

This is from the stack trace:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blocktrekacademy.officialblocktrek/com.blocktrekacademy.officialblocktrek.Authentication}: android.content.ActivityNotFoundException: Unable to find explicit activity class {/com.blocktrekacademy.officialblocktrek.Mainpage}; have you declared this activity in your AndroidManifest.xml?
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {/com.blocktrekacademy.officialblocktrek.Mainpage}; have you declared this activity in your AndroidManifest.xml?
</code>```

This is the Application tag in my AndroidManifest.xml:

```<code><application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".Authentication"
            android:label="@string/title_activity_authentication"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Mainpage"
            android:label="@string/title_activity_mainpage"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait"></activity>
    </application>
</code>```

Note:

My classes extends AppCompatActivity

Tried Solutions:

I tried adding android:name=".Authentication" on Application, but that gives me this error:

```<code>'com.blocktrekacademy.officialblocktrek.Authentication' is not assignable to 'android.app.Application'
</code>```

on AndroidManifest.xml, and these errors on logcat:

```<code>java.lang.RuntimeException: Unable to instantiate application com.blocktrekacademy.officialblocktrek.Authentication: java.lang.ClassCastException: com.blocktrekacademy.officialblocktrek.Authentication cannot be cast to android.app.Application
Caused by: java.lang.ClassCastException: com.blocktrekacademy.officialblocktrek.Authentication cannot be cast to android.app.Application
</code>```

I'm really a newbie on Android Development :(

答:
If you want to start an activity from another activity with an explicit intent this should work like this (you should probably do the following after having having checked the login credentials):

```<code> Intent intent = new Intent(this, Mainpage.class);
 startActivity(intent);
</code>```

Make sure the activities are in the same package or otherwise adjust the path to MainActivity.class, so that it can be found.

Body:
When I launch my application, it force closes and when I debug my program I kept getting error messages. I have 2 activities, the Authentication (where User log in) and Mainpage (this is the page when the user is logged in).

The problem here is when i'm not logged in, I can still log in. If i'm logged in it should take me to Mainpage (Activity), but now the error [see below] shows up.

This is from the stack trace:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blocktrekacademy.officialblocktrek/com.blocktrekacademy.officialblocktrek.Authentication}: android.content.ActivityNotFoundException: Unable to find explicit activity class {/com.blocktrekacademy.officialblocktrek.Mainpage}; have you declared this activity in your AndroidManifest.xml?
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {/com.blocktrekacademy.officialblocktrek.Mainpage}; have you declared this activity in your AndroidManifest.xml?

This is the Application tag in my AndroidManifest.xml:

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".Authentication"
            android:label="@string/title_activity_authentication"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Mainpage"
            android:label="@string/title_activity_mainpage"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait"></activity>
    </application>

Note:

My classes extends AppCompatActivity

Tried Solutions:

I tried adding android:name=".Authentication" on Application, but that gives me this error:

'com.blocktrekacademy.officialblocktrek.Authentication' is not assignable to 'android.app.Application'

on AndroidManifest.xml, and these errors on logcat:

java.lang.RuntimeException: Unable to instantiate application com.blocktrekacademy.officialblocktrek.Authentication: java.lang.ClassCastException: com.blocktrekacademy.officialblocktrek.Authentication cannot be cast to android.app.Application
Caused by: java.lang.ClassCastException: com.blocktrekacademy.officialblocktrek.Authentication cannot be cast to android.app.Application

I'm really a newbie on Android Development :(

Body:
If you want to start an activity from another activity with an explicit intent this should work like this (you should probably do the following after having having checked the login credentials):

 Intent intent = new Intent(this, Mainpage.class);
 startActivity(intent);

Make sure the activities are in the same package or otherwise adjust the path to MainActivity.class, so that it can be found.


问:
Fill matrix randomly without row-repetitions
Please help. I'm new to matlab scripting and need a bit of help. I have a series of numbers:

A=[1 1 1 2 2 2 3 3 3 4 4 4 5]

which I want to fill randomly into an 8x12 matrix without having the same number in the same row. At the end I want all the "empty" cells of the 8x12 matrix being filled with 0's or nan.

an example could be:

result=

3 1 5 2 4 5 0 0 0 0 0 0

4 1 3 2 0 0 0 0 0 0 0 0

1 3 4 2 0 0 0 0 0 0 0 0

答:
make sure A is sorted. A = sort(A)more info

make an empty matrix.

For each number in A: more info

find out how many repetitions of the number there are -> for loop in A, start is the first occurance of the number, end is the last, n = last-first+1

find all rows that have space for an extra number, just do a double for loop and keep track of elements that are zero

randomly pick n rows -> more info. To do this, make an array R of all available row indixes. Then take a random sample between 1..size(R,2) with the provided function and get all the values, you now have your row indixes.

randomly pick one of the empty spots in each of the selected rows and assign the number


问:
VB script to format excel
I have a excel file which is generated by another program. for this reason it is a Microsoft Excel Workbook and not a Macro-enabled workbook.

I am wanting to write a VB script which does basic formatting to the excel file without having to call an embedded macro.

Is this possible? I have been searching for a while but only found a VB script which calls the embedded macro (as below):

VB Script:

```<code>Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("test.xls")

objExcel.Application.Visible = True
objExcel.Workbooks.Add
objExcel.Cells(1, 1).Value = "Test value"

objExcel.Application.Run "Macro.TestMacro()"
objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit
</code>```

Calling macro:

```<code>Sub TestMacro()
'example
End Sub
</code>```

答:
A common trick is to use two workbooks:

Master.xlsm

test.xls

The Master will contain the macros(s) to:

create or open test.xls

modify and format test.xls

save and close test,xls

Title: VB script to format excel

Body:
I have a excel file which is generated by another program. for this reason it is a Microsoft Excel Workbook and not a Macro-enabled workbook.

I am wanting to write a VB script which does basic formatting to the excel file without having to call an embedded macro.

Is this possible? I have been searching for a while but only found a VB script which calls the embedded macro (as below):

VB Script:

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("test.xls")

objExcel.Application.Visible = True
objExcel.Workbooks.Add
objExcel.Cells(1, 1).Value = "Test value"

objExcel.Application.Run "Macro.TestMacro()"
objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit

Calling macro:

Sub TestMacro()
'example
End Sub


问:
Clear browser cache for load renamed file
I have some images in a folder that I rename (like 1000.jpg 2000.jpg...) with PHP script and when PHP return to html the images don't have been reloaded in the right order, instead of what's happened in directory. How can i clear browser cache from file and image without using Chrome standard function in PHP or javascript?

something like this

```<code>header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
</code>```

or like

```<code>location.reload(true)
</code>```

doesn't work

答:
You can try something like this:</p>

```<code><img src="1000.jpg?<?php echo(time());?>">
</code>```

Body:
I have some images in a folder that I rename (like 1000.jpg 2000.jpg...) with PHP script and when PHP return to html the images don't have been reloaded in the right order, instead of what's happened in directory. How can i clear browser cache from file and image without using Chrome standard function in PHP or javascript?

something like this

header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

or like

location.reload(true)

doesn't work

Body:
You can try something like this:

<img src="1000.jpg?<?php echo(time());?>">


问:
how to solve Exception:Call was rejected by callee. (Exception from HRESULT: 0x80010001 (RPC_E_CALL_REJECTED)) in C#?
I have written a C# code in console application to open two excels and copy and paste data from one excel to another excel. It was working fine until the destination excel's visibility was true. But I need to hide the excel at the time of execution. So I changed the visibility to false. Like,

```<code>  _destExcelApp = new Excel.ApplicationClass();
  _destExcelApp.Visible = false;
</code>```

Now its showing an exception like

Call was rejected by callee. (Exception from HRESULT: 0x80010001 (RPC_E_CALL_REJECTED))

How to solve this one?

答:
I was facing the same error and many solutions suggested were not working for me.
I had an application running in windows 8 and I found that the problem was Excel always asking to choose default application for "xlsx" extensions.
When executing the application no window dialog appeared, just the error was shown.

I solved the problem going to Control Panel > Programs > Default Programs and setting Microsoft Office Excel 2016 as default program for xlsx files.

Body:
I have written a C# code in console application to open two excels and copy and paste data from one excel to another excel. It was working fine until the destination excel's visibility was true. But I need to hide the excel at the time of execution. So I changed the visibility to false. Like,

  _destExcelApp = new Excel.ApplicationClass();
  _destExcelApp.Visible = false;

Now its showing an exception like

Call was rejected by callee. (Exception from HRESULT: 0x80010001 (RPC_E_CALL_REJECTED))

How to solve this one?


问:
SSIS rounding number to 2
I have a column of type DT_NUMERIC(16,4). How can I round to number to 2 digits is SSIs in derived column?
I tried sound(column,2) and it doesnt work for me.

I have also tried (DT_NUMERIC,16,4)ROUND([Column],2) , it doesnt work either

Currently I have = 21.7000
I want = 21.70

答:
Just try casting to (DT_NUMERIC,16,2), use the following expression:

```<code>(DT_NUMERIC,16,2)ROUND([Column],2)
</code>```

Also you can try this:

```<code>ROUND(((DT_NUMERIC)([Column])), 2)
</code>```

Or

```<code>(DT_DECIMAL,2)[Column]
</code>```

Title: SSIS rounding number to 2

Body:
Just try casting to (DT_NUMERIC,16,2), use the following expression:

(DT_NUMERIC,16,2)ROUND([Column],2)

Also you can try this:

ROUND(((DT_NUMERIC)([Column])), 2)

Or

(DT_DECIMAL,2)[Column]


问:
Making os independent configure file which checks for curl dependency
I am making a configure.ac file which checks for library dependency.

The complete code is,

```<code>AC_CONFIG_AUX_DIR([build-aux])

AC_INIT([myprogram], [0.1], [])

AM_INIT_AUTOMAKE

AC_PROG_CC

AC_CHECK_LIB([curl], [curl_easy_setopt], [echo "libcurl library is present"  > /dev/tty], [echo "libcurl library is not present" > /dev/tty] )

AC_CHECK_LIB([sqlite3], [sqlite3_open], [echo "sqlite3 library is present"  > /dev/tty], [echo "sqlite library is not present" > /dev/tty] )

AC_CHECK_LIB([pthread], [pthread_create], [echo "pthread library is present"  > /dev/tty], [echo "pthread library is not present" > /dev/tty] )

AC_CHECK_LIB([crypto], [SHA256], [echo "crypto library is present"  > /dev/tty], [echo "crypto library is not present" > /dev/tty] )

AC_CONFIG_FILES([Makefile])

AC_OUTPUT
</code>```

"myprogram" is a program which needs to be installed in numerous user pcs.So, dependency check needs to be done in the begining, to find whether those four libraries are installed.

In the systems where, /usr/lib/i386-linux-gnu/libcurl.so is there, it is giving the message "libcurl library is present", when I run the configure file. But, in the systems where /usr/lib/i386-linux-gnu/libcurl.so.1.0 or something similar is present, it is telling that libcurl is not present. If I create a soft link to libcurl.so , then it is telling correctly that libcurl is present.
ln -s /usr/lib/i386-linux-gnu/libcurl.so.1.0.0  /usr/lib/i386-linux-gnu/libcurl.so.Same holds good for other libraries as well.

Actually, I want to automate this process. Is there a way to do this, without manually making a soft link?.I mean, by making changes in the configure.ac file itself, so that configure will run in any machine without the need for making soft link.

While installing a library, the installer program will typically create a symbolic link from the library's real name(libcurl.so.1.0.0) to its linker name(libcurl.so) to allow the linker to find the actual library file.But it is not always true.Sometimes it will not create the linker name.That is why these complications are happening.So the program which checks for the linker name, thinks that the library is not installed.

答:
In systems where, /usr/lib/i386-linux-gnu/libcurl.so is there, it is giving the message "libcurl library is present", when I run the configure file. But, in the systems where /usr/lib/i386-linux-gnu/libcurl.so.1.0 or something similar is present, it is telling that libcurl is not present.

Right, this is the behavior I would expect.  What's going on here is that AC_CHECK_LIB emits a program with the symbol you gave it to try and link (in this case curl_easy_setopt), does a compilation step and a link step to make sure the linker can link.  On a typical Linux distro you'll want to make sure that some package called libcurl-dev (or something like that) is installed, so you'll have the header files and the libcurl.so symlink installed.

But I want to automate this process. Is there a way to do this, without manually making a soft link?

Installation of the libcurl-dev package can be easily automated. It can be accomplished several ways, depending on how you want to do it. Linux packaging systems (e.g. rpmbuild, debhelper, etc.) have ways of pulling in build dependencies before building if they aren't installed.   Configuration management tools that you use to set up the build machine (e.g. ansible, SaltStack, etc.) could install it.  The dependency should be listed in the release documentation at a minimum, so that if someone who has no access to these tools (or doesn't care to use them) can figure it out and build.

I wouldn't create a symlink in configure.ac -- it would likely break any future install of libcurl-dev.  Furthermore you would have to run configure with elevated privileges (e.g. sudo) to create the link.

While installing a library, the installer program will typically create a symbolic link from the library's real name(libcurl.so.1.0.0) to its linker name(libcurl.so) to allow the linker to find the actual library file.But it is not always true.

Actually, I don't ever remember seeing anything like this.  Typically when a DSO gets installed to the ldconfig "trusted directories" (e.g. /usr/lib, etc.) ldconfig gets run so the real library (e.g. libcurl.so.1.0.0) gets a symlink (libcurl.so.1) in the same directory, but not the development symlink (libcurl.so).

EDIT:  Adding responses to comments

But why ./configure also expects development symlink s(libcurl.so, libcrypto.so etc)

Because configure can be told to run the linker, as you discovered with AC_CHECK_LIB, and if those symlinks aren't there, the link will fail.

configure checks whether the binary can run in the system, and not whether a program which uses these libraries can be build.

configure also has runtime tests as well as compile and link time tests, so it can to some limited testing if the output of compilation can run.  configure's primary role is to ensure that prerequisites are installed/configured so make will work, so testing that tools, headers, libraries are installed and work in some fashion is what configure mostly does.  The runtime tests will not work in some environments (cross-compilation), so lots of packages don't use them.

If I am not wrong, ./configure cannot be used for checking whether a binary can run in a system, as it is used in the case of building a program only.

configure can do some runtime testing of things configure has built as mentioned in the link above (e.g. AC_RUN_IFELSE).

If ./configure succeeds, then the binary can run in the machine.
  But reverse is not true. That is , evenif ./configure fails, the binary may run, as it does not depened on development symlink(eg: libcurl.so).Am I right ?

Which binary are you referring to?  The test created as part of AC_RUN_IFELSE or the output of make?  If configure suceeeds, the output of make still might not work.  That's what make check is for.  If configure fails, it's likely make won't work, and you won't get to the part where you can test the output of make.

If the scenario is a missing libcurl.so, and configure fails to link the AC_TRY_LINK test, how's that same link step going to work for your executable then, because it's also going to depend on libcurl.so for the link step?  It does depend on that file (just for the link step), because you may have multiple libcurl.so.x libraries installed.

By binary...I mean the program that has been successfully build in some other system having all the dependencies installed.What I was telling is that the binary will run in a machine even if the development symlink(libcurl.so) is not there.

Sure, it's already gone past the link step and is linked to say libcurl.so.x and whatever other dependencies it may have.

Body:
I am making a configure.ac file which checks for library dependency.

The complete code is,

AC_CONFIG_AUX_DIR([build-aux])

AC_INIT([myprogram], [0.1], [])

AM_INIT_AUTOMAKE

AC_PROG_CC

AC_CHECK_LIB([curl], [curl_easy_setopt], [echo "libcurl library is present"  > /dev/tty], [echo "libcurl library is not present" > /dev/tty] )

AC_CHECK_LIB([sqlite3], [sqlite3_open], [echo "sqlite3 library is present"  > /dev/tty], [echo "sqlite library is not present" > /dev/tty] )

AC_CHECK_LIB([pthread], [pthread_create], [echo "pthread library is present"  > /dev/tty], [echo "pthread library is not present" > /dev/tty] )

AC_CHECK_LIB([crypto], [SHA256], [echo "crypto library is present"  > /dev/tty], [echo "crypto library is not present" > /dev/tty] )

AC_CONFIG_FILES([Makefile])

AC_OUTPUT

"myprogram" is a program which needs to be installed in numerous user pcs.So, dependency check needs to be done in the begining, to find whether those four libraries are installed.

In the systems where, /usr/lib/i386-linux-gnu/libcurl.so is there, it is giving the message "libcurl library is present", when I run the configure file. But, in the systems where /usr/lib/i386-linux-gnu/libcurl.so.1.0 or something similar is present, it is telling that libcurl is not present. If I create a soft link to libcurl.so , then it is telling correctly that libcurl is present.
ln -s /usr/lib/i386-linux-gnu/libcurl.so.1.0.0  /usr/lib/i386-linux-gnu/libcurl.so.Same holds good for other libraries as well.

Actually, I want to automate this process. Is there a way to do this, without manually making a soft link?.I mean, by making changes in the configure.ac file itself, so that configure will run in any machine without the need for making soft link.

While installing a library, the installer program will typically create a symbolic link from the library's real name(libcurl.so.1.0.0) to its linker name(libcurl.so) to allow the linker to find the actual library file.But it is not always true.Sometimes it will not create the linker name.That is why these complications are happening.So the program which checks for the linker name, thinks that the library is not installed.


问:
Read contents of an Excel file using PowerShell and store it in a SQL Server database
I am trying to write the contents of an Excel file (on tab 5) to a database but it keeps failing.

Here is my code:

```<code> $dir = "\\server\files\"
    $latest = Get-ChildItem -Path $dir | Where-Object {$_.name -like "*Data Notes*"} | Sort-Object LastWriteTime -Descending | Select-Object -First 1
    Write-Output "The latest file is: $latest"
    Write-SqlTableData -ServerInstance "sql server" -DatabaseName "sql5" -SchemaName dbo -TableName Temptable100 -InputData $latest.FullName -Force
</code>```

The table gets created fine but its empty. Can anyone please help me??

I have attached the contents of the Excel file here:

答: Write-SQLTableData won't be able to read an Excel file so you will need to use something like OLEDB to first read the Excel table into a DataTable and then pass that DataTable to Write-SQLTableData.</p>

Body:
I am trying to write the contents of an Excel file (on tab 5) to a database but it keeps failing.

Here is my code:

 $dir = "\\server\files\"
    $latest = Get-ChildItem -Path $dir | Where-Object {$_.name -like "*Data Notes*"} | Sort-Object LastWriteTime -Descending | Select-Object -First 1
    Write-Output "The latest file is: $latest"
    Write-SqlTableData -ServerInstance "sql server" -DatabaseName "sql5" -SchemaName dbo -TableName Temptable100 -InputData $latest.FullName -Force

The table gets created fine but its empty. Can anyone please help me??

I have attached the contents of the Excel file here:


问:
iphone UITableView Custom Cell selected image
I have a custom UITableViewCell which fills the cell with a background PNG and a label.

When the user selected the cell, I wish to have the back ground change for an instant to visually give them indication that the row was selected. Similar to the default behavior when a custom cell is not used.

How is that done?

答:
You can try this tutorial:

http://cocoawithlove.com/2009/04/easy-custom-uitableview-drawing.html


问:
Unable to call to main Method
I'm attempting to call a method from my 'Clicker' class to my 'Main' class however I keep getting errors, which vary depending on the method I call.
This is the main class. The current error is "Syntax error on token (XYZ) identifier expected after this token."

```<code>package me.removed.clicker;

public class Main
{
  public static void main(String[] args) {}

}
</code>```

This is the clicker class.

```<code>package me.removed.clicker;

import java.awt.EventQueue;
import java.awt.Robot;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.FloatControl.Type;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import me.dewgs.clicker.handler.KeyboardHandler;
import me.dewgs.clicker.handler.MouseHandler;
import me.dewgs.clicker.util.Time;
import org.jnativehook.GlobalScreen;

public class Clicker
{
  public static Clicker instance;
  private boolean LEFT_held;
  private boolean LEFT_skip;
  private Time LEFT_pressTime;
  private boolean toggled;
  private Random random;
  private ClickerFrame clickerFrame;
  private MouseHandler clickerHandler;
  private KeyboardHandler keyHandler;
  private Robot robot;
  private Thread thread;

  public boolean isToggled()
  {
    return this.toggled;
  }

  public void setToggled(boolean toggled)
  {
    this.toggled = toggled;
  }

  public Clicker()
  {
    this.LEFT_held = false;
    this.LEFT_skip = false;
    this.toggled = false;
    this.random = new Random();
    try
    {
      GlobalScreen.registerNativeHook();
      this.clickerHandler = new MouseHandler();
      this.keyHandler = new KeyboardHandler();
      GlobalScreen.addNativeMouseListener(this.clickerHandler);
      GlobalScreen.addNativeKeyListener(this.keyHandler);
      this.robot = new Robot();
      LogManager.getLogManager().reset();
      Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
      logger.setLevel(Level.OFF);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    this.thread = new Thread(new Runnable()
    {
      public void run()
      {
        try
        {
          for (;;)
          {
            Thread.sleep(1L);
            if ((Clicker.this.isToggled()) &&

              (Clicker.this.isLeftHeld()))
            {
              long CPSDelay = Clicker.this.generateCPSDelay();
              if (Clicker.this.getLeftPressTime() != null)
              {
                if (Clicker.this.getLeftPressTime().hasPassed())
                {
                  Clicker.this.setLeftPressTime(new Time(CPSDelay));
                  Clicker.this.setLeftSkip(true);
                  Clicker.this.robot.mousePress(16);
                  Clicker.this.robot.mouseRelease(16);

                  Thread runThread = new Thread(new Runnable()
                  {
                    public void run()
                    {
                      try
                      {
                        AudioInputStream audioInputStream =
                          AudioSystem.getAudioInputStream(Clicker.class.getClassLoader().getResource("left_click.wav"));

                        Clip clip = AudioSystem.getClip();

                        clip.open(audioInputStream);

                        float volume = -9.0F - Clicker.this.random.nextFloat() * 11.0F;

                        FloatControl gainControl =
                          (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
                        gainControl.setValue(volume);

                        clip.start();
                      }
                      catch (Exception localException) {}
                    }
                  });
                  runThread.start();
                }
              }
              else
              {
                Clicker.this.setLeftPressTime(new Time(CPSDelay));
                Clicker.this.setLeftSkip(true);
              }
            }
          }
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
      }
    });
    this.thread.start();
  }

  public boolean isLeftHeld()
  {
    return this.LEFT_held;
  }

  public void setLeftHeld(boolean LEFT_held)
  {
    this.LEFT_held = LEFT_held;
  }

  public void destroy()
  {
    try
    {

    }
    catch (Throwable e)
    {
      e.printStackTrace();
    }
    System.exit(0);
  }

  public void openUI()
  {
    EventQueue.invokeLater(new Runnable()
    {
      public void run()
      {
        try
        {
          UIManager.LookAndFeelInfo[] installedLookAndFeels;
          int length = (installedLookAndFeels = UIManager.getInstalledLookAndFeels()).length;
          for (int i = 0; i < length; i++)
          {
            UIManager.LookAndFeelInfo info = installedLookAndFeels[i];
            if ("Windows".equals(info.getName()))
            {
              UIManager.setLookAndFeel(info.getClassName());
              break;
            }
          }
          Clicker.this.clickerFrame = new ClickerFrame();
          Clicker.this.clickerFrame.setVisible(true);
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
      }
    });
  }

  public boolean getLeftSkip()
  {
    return this.LEFT_skip;
  }

  public void setLeftSkip(boolean LEFT_skip)
  {
    this.LEFT_skip = LEFT_skip;
  }

  public Time getLeftPressTime()
  {
    return this.LEFT_pressTime;
  }

  public void setLeftPressTime(Time LEFT_pressTime)
  {
    this.LEFT_pressTime = LEFT_pressTime;
  }

  public ClickerFrame getClickerFrame()
  {
    return this.clickerFrame;
  }

  public long generateCPSDelay()
  {
    int minCPS = 12;
    int maxCPS = 15;
    double minDiff = 83.0D;
    double maxDiff = 66.0D;
    double randomDiff = this.random.nextDouble() * 17.0D;
    return (long) (66.0D + randomDiff);
  }

  public static void setupClicker()
  {
    (Clicker.instance = new Clicker()).openUI();
  }

  public static Clicker getClicker()
  {
    return instance;
  }
}
</code>```

I attempt to call setupClicker and even when I follow steps from other pages nothing works,

```<code>Clicker click = new Clicker();
click.setupClicker.
</code>```

Is what I tried and using other methods also to no avail.

FYI: I'm trying to open the GUI and start the clicker itself.

答:
I attempt to call setupClicker and even when I follow steps from
  other pages nothing works,

```<code>Clicker click = new Clicker();
click.setupClicker.
</code>```

You miss to add bracket

```<code>public class Main
{
  public static void main(String[] args) {

          Clicker click = new Clicker();
          click.setupClicker();
  }

}
</code>```

Title: Unable to call to main Method

Body:
I'm attempting to call a method from my 'Clicker' class to my 'Main' class however I keep getting errors, which vary depending on the method I call.
This is the main class. The current error is "Syntax error on token (XYZ) identifier expected after this token."

package me.removed.clicker;

public class Main
{
  public static void main(String[] args) {}

}

This is the clicker class.

package me.removed.clicker;

import java.awt.EventQueue;
import java.awt.Robot;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.FloatControl.Type;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import me.dewgs.clicker.handler.KeyboardHandler;
import me.dewgs.clicker.handler.MouseHandler;
import me.dewgs.clicker.util.Time;
import org.jnativehook.GlobalScreen;

public class Clicker
{
  public static Clicker instance;
  private boolean LEFT_held;
  private boolean LEFT_skip;
  private Time LEFT_pressTime;
  private boolean toggled;
  private Random random;
  private ClickerFrame clickerFrame;
  private MouseHandler clickerHandler;
  private KeyboardHandler keyHandler;
  private Robot robot;
  private Thread thread;

  public boolean isToggled()
  {
    return this.toggled;
  }

  public void setToggled(boolean toggled)
  {
    this.toggled = toggled;
  }

  public Clicker()
  {
    this.LEFT_held = false;
    this.LEFT_skip = false;
    this.toggled = false;
    this.random = new Random();
    try
    {
      GlobalScreen.registerNativeHook();
      this.clickerHandler = new MouseHandler();
      this.keyHandler = new KeyboardHandler();
      GlobalScreen.addNativeMouseListener(this.clickerHandler);
      GlobalScreen.addNativeKeyListener(this.keyHandler);
      this.robot = new Robot();
      LogManager.getLogManager().reset();
      Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
      logger.setLevel(Level.OFF);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    this.thread = new Thread(new Runnable()
    {
      public void run()
      {
        try
        {
          for (;;)
          {
            Thread.sleep(1L);
            if ((Clicker.this.isToggled()) &&

              (Clicker.this.isLeftHeld()))
            {
              long CPSDelay = Clicker.this.generateCPSDelay();
              if (Clicker.this.getLeftPressTime() != null)
              {
                if (Clicker.this.getLeftPressTime().hasPassed())
                {
                  Clicker.this.setLeftPressTime(new Time(CPSDelay));
                  Clicker.this.setLeftSkip(true);
                  Clicker.this.robot.mousePress(16);
                  Clicker.this.robot.mouseRelease(16);

                  Thread runThread = new Thread(new Runnable()
                  {
                    public void run()
                    {
                      try
                      {
                        AudioInputStream audioInputStream =
                          AudioSystem.getAudioInputStream(Clicker.class.getClassLoader().getResource("left_click.wav"));

                        Clip clip = AudioSystem.getClip();

                        clip.open(audioInputStream);

                        float volume = -9.0F - Clicker.this.random.nextFloat() * 11.0F;

                        FloatControl gainControl =
                          (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
                        gainControl.setValue(volume);

                        clip.start();
                      }
                      catch (Exception localException) {}
                    }
                  });
                  runThread.start();
                }
              }
              else
              {
                Clicker.this.setLeftPressTime(new Time(CPSDelay));
                Clicker.this.setLeftSkip(true);
              }
            }
          }
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
      }
    });
    this.thread.start();
  }

  public boolean isLeftHeld()
  {
    return this.LEFT_held;
  }

  public void setLeftHeld(boolean LEFT_held)
  {
    this.LEFT_held = LEFT_held;
  }

  public void destroy()
  {
    try
    {

    }
    catch (Throwable e)
    {
      e.printStackTrace();
    }
    System.exit(0);
  }

  public void openUI()
  {
    EventQueue.invokeLater(new Runnable()
    {
      public void run()
      {
        try
        {
          UIManager.LookAndFeelInfo[] installedLookAndFeels;
          int length = (installedLookAndFeels = UIManager.getInstalledLookAndFeels()).length;
          for (int i = 0; i < length; i++)
          {
            UIManager.LookAndFeelInfo info = installedLookAndFeels[i];
            if ("Windows".equals(info.getName()))
            {
              UIManager.setLookAndFeel(info.getClassName());
              break;
            }
          }
          Clicker.this.clickerFrame = new ClickerFrame();
          Clicker.this.clickerFrame.setVisible(true);
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
      }
    });
  }

  public boolean getLeftSkip()
  {
    return this.LEFT_skip;
  }

  public void setLeftSkip(boolean LEFT_skip)
  {
    this.LEFT_skip = LEFT_skip;
  }

  public Time getLeftPressTime()
  {
    return this.LEFT_pressTime;
  }

  public void setLeftPressTime(Time LEFT_pressTime)
  {
    this.LEFT_pressTime = LEFT_pressTime;
  }

  public ClickerFrame getClickerFrame()
  {
    return this.clickerFrame;
  }

  public long generateCPSDelay()
  {
    int minCPS = 12;
    int maxCPS = 15;
    double minDiff = 83.0D;
    double maxDiff = 66.0D;
    double randomDiff = this.random.nextDouble() * 17.0D;
    return (long) (66.0D + randomDiff);
  }

  public static void setupClicker()
  {
    (Clicker.instance = new Clicker()).openUI();
  }

  public static Clicker getClicker()
  {
    return instance;
  }
}

I attempt to call setupClicker and even when I follow steps from other pages nothing works,

Clicker click = new Clicker();
click.setupClicker.

Is what I tried and using other methods also to no avail.

FYI: I'm trying to open the GUI and start the clicker itself.

Body:
I attempt to call setupClicker and even when I follow steps from
  other pages nothing works,

Clicker click = new Clicker();
click.setupClicker.

You miss to add bracket

public class Main
{
  public static void main(String[] args) {

          Clicker click = new Clicker();
          click.setupClicker();
  }

}


问:
Quickly checking if arrays intersect
I want to check if two arrays a and b intersect. Given a = [3, 21] and b = [15, 26530, 21, 3], the answer should be true. Given
If a = [3, 21] and b = [15, 26530], the answer should be false.

I tried:

```<code>a.to_set.intersect?(b.to_set)
</code>```

but this method takes a long time. How can I do it quickly?

答:
You can also use

```<code>[a-(a-b)].empty?
</code>```

or

```<code>[b-(b-a)].empty?
</code>```

Title: Quickly checking if arrays intersect

Body:
I want to check if two arrays a and b intersect. Given a = [3, 21] and b = [15, 26530, 21, 3], the answer should be true. Given
If a = [3, 21] and b = [15, 26530], the answer should be false.

I tried:

a.to_set.intersect?(b.to_set)

but this method takes a long time. How can I do it quickly?

Body:
You can also use

[a-(a-b)].empty?

or

[b-(b-a)].empty?


问:
AWS Redshift DEFAULT TIMESTAMP
I am moving some data from old system to AWS -- and I am following the current protocol:

Create new tables

Load data in buckets

Copy from bucket to table

This works great so far, but I am having an issue with empty TIMESTAMPS (some versions of my dates are unavailable -- so I have them set to a default date on my old version, but on the new version, they are being loaded as NULL)

For each time NULL appears in my aws date column, I want to replace it with '0000-00-00 00:00:00' for example.  This is crucial so that I can run an EXCEPT function on the two tables (old & new) to verify the robustness of the process.

I have tried explicit commands like REPLACE, INSERT,

I have rebuilt the table with date column default '0000-00-00 00:00:00'

No luck so far.  Any help would be great!  Thanks!

答:
If you specify the column as NOT NULL then Redshift's COPY will replace the NULLs with the default value specified on the column (and fail if no default is specified).

Have a look at the section Load Data from a File with Default Values in the Redshift docs:  http://docs.aws.amazon.com/redshift/latest/dg/r_COPY_command_examples.html

Title: AWS Redshift DEFAULT TIMESTAMP


问:
How to reset only when the switch is moved?
I have a switch in my setting dialog. I want to call reset() only when the switch is moved. How can I do it?

```<code>if (showSwitch.isChecked()) {
    show = true;
    editor.putBoolean("show", true);
    reset();
} else {
    show = false;
    editor.putBoolean("show", false);
    reset();
}
</code>```

答:
If show is different from the switch value, do something. No if-else is required.

```<code>if (show != showSwitch.isChecked()) {
    show = showSwitch.isChecked();
    editor.putBoolean("show", show);
    reset();
}
</code>```

Body:
I have a switch in my setting dialog. I want to call reset() only when the switch is moved. How can I do it?

if (showSwitch.isChecked()) {
    show = true;
    editor.putBoolean("show", true);
    reset();
} else {
    show = false;
    editor.putBoolean("show", false);
    reset();
}

Body:
If show is different from the switch value, do something. No if-else is required.

if (show != showSwitch.isChecked()) {
    show = showSwitch.isChecked();
    editor.putBoolean("show", show);
    reset();
}


问:
Kohana 3 ORM: Saving relationships
```<code><?php
class Model_Cliente extends ORM {
protected $_table_name = 'clientes';
protected $_primary_key = 'id';
protected $_has_one = array('loja' => array());
}
?>

<?php
class Model_Loja extends ORM {
protected $_table_name = 'lojas';
protected $_primary_key = 'id';
}
?>

<?php
// code here ...
public function action_index()
{
$loja = ORM::Factory('loja');
$loja->nome = 'Foo Bar Store';
$loja->endereco = 'foobar';
$loja->senha = '123456';

$cliente = ORM::Factory('cliente');
$cliente->empresa = 'Foo Bar Ltda.';
$cliente->responsavel = 'João da Silva Foo Bar';
$cliente->email = 'foobar@foobar.com';
$cliente->telefone = '123456789';
$cliente->novidades = true;
$cliente->loja = $loja;

$cliente->save();
}
// code here ...
?>
</code>```

I get the error: "Kohana_Exception [ 0 ]: The loja property does not exist in the Model_Cliente class".

Why cannot I add loja to cliente ($cliente->loja = $loja) and save then?

答:
ORM model can set only belongs_to relations. So, you should reorder your code:

```<code>$cliente = ORM::Factory('cliente');
$cliente->empresa = 'Foo Bar Ltda.';
$cliente->responsavel = 'João da Silva Foo Bar';
$cliente->email = 'foobar@foobar.com';
$cliente->telefone = '123456789';
$cliente->novidades = true;
$cliente->save();  // save parent model before linking

$loja = ORM::Factory('loja');
$loja->nome = 'Foo Bar Store';
$loja->endereco = 'foobar';
$loja->senha = '123456';
$loja->cliente = $cliente; // the same as $loja->cliente_id = $client->id;

$loja->save();
</code>```

And dont forget to define $_belongs_to property in Model_Loja!

Title: Kohana 3 ORM: Saving relationships

Body:
<?php
class Model_Cliente extends ORM {
protected $_table_name = 'clientes';
protected $_primary_key = 'id';
protected $_has_one = array('loja' => array());
}
?>

<?php
class Model_Loja extends ORM {
protected $_table_name = 'lojas';
protected $_primary_key = 'id';
}
?>

<?php
// code here ...
public function action_index()
{
$loja = ORM::Factory('loja');
$loja->nome = 'Foo Bar Store';
$loja->endereco = 'foobar';
$loja->senha = '123456';

$cliente = ORM::Factory('cliente');
$cliente->empresa = 'Foo Bar Ltda.';
$cliente->responsavel = 'João da Silva Foo Bar';
$cliente->email = 'foobar@foobar.com';
$cliente->telefone = '123456789';
$cliente->novidades = true;
$cliente->loja = $loja;

$cliente->save();
}
// code here ...
?>

I get the error: "Kohana_Exception [ 0 ]: The loja property does not exist in the Model_Cliente class".

Why cannot I add loja to cliente ($cliente->loja = $loja) and save then?

Body:
ORM model can set only belongs_to relations. So, you should reorder your code:

$cliente = ORM::Factory('cliente');
$cliente->empresa = 'Foo Bar Ltda.';
$cliente->responsavel = 'João da Silva Foo Bar';
$cliente->email = 'foobar@foobar.com';
$cliente->telefone = '123456789';
$cliente->novidades = true;
$cliente->save();  // save parent model before linking

$loja = ORM::Factory('loja');
$loja->nome = 'Foo Bar Store';
$loja->endereco = 'foobar';
$loja->senha = '123456';
$loja->cliente = $cliente; // the same as $loja->cliente_id = $client->id;

$loja->save();

And dont forget to define $_belongs_to property in Model_Loja!


问:
Angular 1.4 - reuse same controller in $routeProvider
I am trying to use same controller on both full and mobile views using $routeProvider. Code below does not work out of the box. What am i missing?

Also i could use another idea - same controller, but different templateUrl based on user agent. Can i do that?

```<code>   $routeProvider
        .when("/details/:id", {
            templateUrl: "views/details.html",
            controller: "detailsController"
        })
        .when("/mdetails/:id", {
            templateUrl:  "views/mobiledetails.html",
            controller: "detailsController"
        })

}])
</code>```

答:
if moderator sees it, please - delete question

i do not know what the heck happened, but everything works.

```<code>  $routeProvider
        .when("/details/:id", {
            templateUrl: "views/details.html",
            controller: "detailsController"
        })
        .when("/mdetails/:id", {
            templateUrl:  "views/mobiledetails.html",
            controller: "detailsController"
        })

}])
</code>```

inside of controller i made variable is mobile (ism) and i am using it for extra logic

thanks everyone

```<code> $scope.ism = $location.path().indexOf('/mflights') === 0;
</code>```

Body:
I am trying to use same controller on both full and mobile views using $routeProvider. Code below does not work out of the box. What am i missing?

Also i could use another idea - same controller, but different templateUrl based on user agent. Can i do that?

   $routeProvider
        .when("/details/:id", {
            templateUrl: "views/details.html",
            controller: "detailsController"
        })
        .when("/mdetails/:id", {
            templateUrl:  "views/mobiledetails.html",
            controller: "detailsController"
        })

}])

Body:
if moderator sees it, please - delete question

i do not know what the heck happened, but everything works.

  $routeProvider
        .when("/details/:id", {
            templateUrl: "views/details.html",
            controller: "detailsController"
        })
        .when("/mdetails/:id", {
            templateUrl:  "views/mobiledetails.html",
            controller: "detailsController"
        })

}])

inside of controller i made variable is mobile (ism) and i am using it for extra logic

thanks everyone

 $scope.ism = $location.path().indexOf('/mflights') === 0;


问:
Implementation of BEGAN (Boundary Equilibrium GAN) Using CNTK Python API
I found an implementation for BEGAN using CNTK.
(https://github.com/2wins/BEGAN-cntk)

This uses MNIST dataset instead of Celeb A which was used in the original paper.
However, I don't understand the result images, which looks quite deterministic:
Output images of the trained generator (iter: 30000)

For different noise samples, I expect different outputs come from it. But it doesn't do that regardless of any hyper-parameters. Which part of the code does make the problem?

Please explain it.

答:
Use higher gamma (for example gamma=1 or 1.3, more than 1 actually). Then it will improve certainly but would not make it perfect. Take enough iterations like 200k.

Please look at the paper carefully. It says the parameter gamma controls diversity.

One of the results that I obtained is .

I'm also looking for the best parameters and best results, but haven't yet.


问:
How to Iterate through arithmetic operators across a static, excecutable formula in Python?
I'm trying to use itertools to iterate through mathematical operators.
Typically with an array of [1, 2, 3], using combinations I can get the results:

```<code>1
1,2
1,3
2,3
1,2,3
</code>```

etc.

I want to use this on an array of [1, 2, 3] in such a way that:

```<code>1+2+3
1+2-3
1+2/3
1+2*3
1-2+3
1-2-3
1-2/3
1-2*3
...
</code>```

arises and gives results of the equation.

How might I go about doing this?

答:
A solution generalized to any number of operands, and preserving normal precedence of operators:</p>

```<code>from itertools import product

operands = [1, 2, 3, 4]
operators = [ '+', '*', '-', '//' ] # change '//' to '/' for floating point division
for opers in product(operators, repeat=len(operands)-1):
    formula = [ str(operands[0]) ]
    for op, operand in zip(opers, operands[1:]):
        formula.extend([op, str(operand)])
    formula = ' '.join(formula)
    print('{} = {}'.format(formula, eval(formula)))
</code>```

Body:
I'm trying to use itertools to iterate through mathematical operators.
Typically with an array of [1, 2, 3], using combinations I can get the results:

1
1,2
1,3
2,3
1,2,3

etc.

I want to use this on an array of [1, 2, 3] in such a way that:

1+2+3
1+2-3
1+2/3
1+2*3
1-2+3
1-2-3
1-2/3
1-2*3
...

arises and gives results of the equation.

How might I go about doing this?

Body:
A solution generalized to any number of operands, and preserving normal precedence of operators:

from itertools import product

operands = [1, 2, 3, 4]
operators = [ '+', '*', '-', '//' ] # change '//' to '/' for floating point division
for opers in product(operators, repeat=len(operands)-1):
    formula = [ str(operands[0]) ]
    for op, operand in zip(opers, operands[1:]):
        formula.extend([op, str(operand)])
    formula = ' '.join(formula)
    print('{} = {}'.format(formula, eval(formula)))