问:
how to redirect index.html#/abc/ to newpage.aspx
I have a problem with trying to make some redirections from an old HTML page which was reading some parameters from the URL to feed some flash components to a new ASPX page.

The issue is that the page URLs are of the form: http://www.mysite.com/index.html#/abc/
and that needs to redirect to something like: http://www.mysite.com/new-abc.aspx

There are several different values following the # but in essence they are all the same html page. Other problem is that the values are not even passed in a query string.

I'm using Windows Server 2008, IIS 7 (not R2) and I have installed the URL Rewrite module but so far my rules have not worked.

Any ideas?

Thanks so much!!
Jose

答:
As I know, please someone corrects me if I am wrong, you cannot get anchors (#...) from back-end. So if you have a URL rewriting module it won't work.

But you can use javascript to do that. Get the anchor value from the javascript, and then redirect your document from javascript. here is an example:

```<code>var anc = location.hash;
if (anc )
   document.location = "/blabla/" + anc + "/test.aspx";
</code>```

Body:
As I know, please someone corrects me if I am wrong, you cannot get anchors (#...) from back-end. So if you have a URL rewriting module it won't work.

But you can use javascript to do that. Get the anchor value from the javascript, and then redirect your document from javascript. here is an example:

var anc = location.hash;
if (anc )
   document.location = "/blabla/" + anc + "/test.aspx";


来源: stackexchange

问:
Back to top link flashes twice before dissappearing
As per the fiddle below I have a scroll back to top link, but upon clicking the link to scroll back to the top it flashes twice.

I have tried the usual suspects such as the $(body,html), but it still occurs even when I use one of those.

stop() before the fadeIn and fadeOut does help prevent this but causes the fadeIn to be incredibly slow.

Therefore, I was wondering if anyone could explain why this flash of the element is happening and how I could stop it from occurring?

jQuery(function() {
  jQuery(window).scroll(function() {
    if (jQuery(this).scrollTop() > 50) {
      jQuery('#back_top').fadeIn();
    } else {
      jQuery('#back_top').fadeOut();
    }
  });
  jQuery('#back_top').click(function() {
    jQuery('body,html').animate({
      scrollTop: 0
    }, 500);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#back_top {
  background-color: #447282;
  /* button color */
  color: white;
  /* text/arrow color */
  display: none;
  z-index: 999;
  /* float in bottom right corner */
  /* 20 pixels from edge */
  position: fixed;
  right: 10px;
  bottom: 10px;
  /* size of button is 50 pixels*/
  width: 54px;
  height: 54px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  opacity: 0.9;
}

a#back_top {
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 12px;
  text-transform: uppercase;
  text-align: center;
  line-height: 1.6;
  padding-left: 2px;
  padding-top: 8px;
}

a#back_top .arrow:before {
  content: "\e902";
  font-family: 'vishIcon';
  font-style: normal;
  font-weight: 600;
  font-size: 18px;
  line-height: 1;
  speak: none;
  -webkit-font-smoothing: antialiased;
  content: "\e902";
  text-align: center;
  display: block;
  vertical-align: middle;
  cursor: pointer;
  /*     margin-left: -4px; */
}</code>```

What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using
Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default
model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary
to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the
more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
(The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The
standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions
from the 1914 translation by H. Rackham. Where can I get some? There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly
believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this
the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition,
injected humour, or non-characteristic words etc.
Top```

答:
Your problem : Your fadeIn and fadeOut is being called simultaneously when Back to Top is pressed.

How to avoid it?
How about you use jQuery's inbuilt function to check whether the element you are trying to animate is already being animated?

By using this : $(elem).is(':animated')
This will tell you whether the element in question is already being animated or not. If not, only then animate it. Else let it be.

jQuery(function() {
  jQuery(window).scroll(function() {
    if (!jQuery('#back_top').is(':animated')) {
    if (jQuery(this).scrollTop() > 50) {
      jQuery('#back_top').fadeIn();
    } else {
      jQuery('#back_top').fadeOut();
    }
  }
  });
  jQuery('#back_top').click(function() {
    jQuery('body,html').animate({
      scrollTop: 0
    }, 500);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#back_top {
  background-color: #447282;
  /* button color */
  color: white;
  /* text/arrow color */
  display: none;
  z-index: 999;
  /* float in bottom right corner */
  /* 20 pixels from edge */
  position: fixed;
  right: 10px;
  bottom: 10px;
  /* size of button is 50 pixels*/
  width: 54px;
  height: 54px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  opacity: 0.9;
}

a#back_top {
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 12px;
  text-transform: uppercase;
  text-align: center;
  line-height: 1.6;
  padding-left: 2px;
  padding-top: 8px;
}

a#back_top .arrow:before {
  content: "\e902";
  font-family: 'vishIcon';
  font-style: normal;
  font-weight: 600;
  font-size: 18px;
  line-height: 1;
  speak: none;
  -webkit-font-smoothing: antialiased;
  content: "\e902";
  text-align: center;
  display: block;
  vertical-align: middle;
  cursor: pointer;
  /*     margin-left: -4px; */
}</code>```

What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using
Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default
model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary
to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the
more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
(The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The
standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions
from the 1914 translation by H. Rackham. Where can I get some? There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly
believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this
the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition,
injected humour, or non-characteristic words etc.
Top```

ContentLicense: CC BY-SA 3.0

Body:
As per the fiddle below I have a scroll back to top link, but upon clicking the link to scroll back to the top it flashes twice.

I have tried the usual suspects such as the $(body,html), but it still occurs even when I use one of those.

stop() before the fadeIn and fadeOut does help prevent this but causes the fadeIn to be incredibly slow.

Therefore, I was wondering if anyone could explain why this flash of the element is happening and how I could stop it from occurring?

jQuery(function() {
  jQuery(window).scroll(function() {
    if (jQuery(this).scrollTop() > 50) {
      jQuery('#back_top').fadeIn();
    } else {
      jQuery('#back_top').fadeOut();
    }
  });
  jQuery('#back_top').click(function() {
    jQuery('body,html').animate({
      scrollTop: 0
    }, 500);
  });
});

#back_top {
  background-color: #447282;
  /* button color */
  color: white;
  /* text/arrow color */
  display: none;
  z-index: 999;
  /* float in bottom right corner */
  /* 20 pixels from edge */
  position: fixed;
  right: 10px;
  bottom: 10px;
  /* size of button is 50 pixels*/
  width: 54px;
  height: 54px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  opacity: 0.9;
}

a#back_top {
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 12px;
  text-transform: uppercase;
  text-align: center;
  line-height: 1.6;
  padding-left: 2px;
  padding-top: 8px;
}

a#back_top .arrow:before {
  content: "\e902";
  font-family: 'vishIcon';
  font-style: normal;
  font-weight: 600;
  font-size: 18px;
  line-height: 1;
  speak: none;
  -webkit-font-smoothing: antialiased;
  content: "\e902";
  text-align: center;
  display: block;
  vertical-align: middle;
  cursor: pointer;
  /*     margin-left: -4px; */
}

What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using
Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default
model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary
to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the
more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
(The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The
standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions
from the 1914 translation by H. Rackham. Where can I get some? There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly
believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this
the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition,
injected humour, or non-characteristic words etc.
Top

Body:
Your problem : Your fadeIn and fadeOut is being called simultaneously when Back to Top is pressed.

How to avoid it?
How about you use jQuery's inbuilt function to check whether the element you are trying to animate is already being animated?

By using this : $(elem).is(':animated')
This will tell you whether the element in question is already being animated or not. If not, only then animate it. Else let it be.

jQuery(function() {
  jQuery(window).scroll(function() {
    if (!jQuery('#back_top').is(':animated')) {
    if (jQuery(this).scrollTop() > 50) {
      jQuery('#back_top').fadeIn();
    } else {
      jQuery('#back_top').fadeOut();
    }
  }
  });
  jQuery('#back_top').click(function() {
    jQuery('body,html').animate({
      scrollTop: 0
    }, 500);
  });
});

#back_top {
  background-color: #447282;
  /* button color */
  color: white;
  /* text/arrow color */
  display: none;
  z-index: 999;
  /* float in bottom right corner */
  /* 20 pixels from edge */
  position: fixed;
  right: 10px;
  bottom: 10px;
  /* size of button is 50 pixels*/
  width: 54px;
  height: 54px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  opacity: 0.9;
}

a#back_top {
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 12px;
  text-transform: uppercase;
  text-align: center;
  line-height: 1.6;
  padding-left: 2px;
  padding-top: 8px;
}

a#back_top .arrow:before {
  content: "\e902";
  font-family: 'vishIcon';
  font-style: normal;
  font-weight: 600;
  font-size: 18px;
  line-height: 1;
  speak: none;
  -webkit-font-smoothing: antialiased;
  content: "\e902";
  text-align: center;
  display: block;
  vertical-align: middle;
  cursor: pointer;
  /*     margin-left: -4px; */
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using
Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default
model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary
to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the
more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
(The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The
standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions
from the 1914 translation by H. Rackham. Where can I get some? There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly
believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this
the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition,
injected humour, or non-characteristic words etc.
<a href="#" id="back_top" style="display: none;"><span class="arrow"></span>Top</a>


问:
Google Analytics reports no active users on site even though tag properly implemented
According to the Google Tag Assistant Chrome extension, Google Analytics is properly implemented on this site. However, when I log into Google Analytics, it reports 0 active users on the site. What might account for this issue?

EDIT: A single user was tracked 6 hours after the code was added but I still cannot see anything in real-time nor do I know if other users were missed.

答:
I would check a number of things in the following order:

Use of correct Google Analytics (GA) account and web property:
The GA tag is sending data to the web property with ID UA-109633103-1. Ensure that you are accessing the view from the right account UA-109633103 and web property UA-109633103-1.

Wait up to 48 hours for new accounts: If you just recently created the account, you may need to wait up to 48 hours to see the first pieces of your data.

Check the filters applied to your view: Your view may have include or exclude filters that are excluding the hits from your testing.


问:
android image size scale
I need to add an image to the screen in a table row and have text over the image.

The image is a calendar with the date displayed on top. It work fine for the first device... see image here:

But get too small on the larger device... see image here:

the code is

```<code>RelativeLayout calender_image_text = new RelativeLayout(getActivity());
        ImageView imageview1 = new ImageView(getActivity());
        imageview1.setBackgroundResource(R.mipmap.calendar);
        imageview1.setPadding(00,00,00,00);
        //imageview1.setMaxHeight(150);
        //imageview1.setMaxWidth(150);
        LinearLayout.LayoutParams imageview2param = new LinearLayout.LayoutParams(120, 80);
        imageview1param.addRule(RelativeLayout.CENTER_IN_PARENT);
        calender_image_text.addView(imageview1,imageview2param);
        //linearh1.addView(calender_image_text,tablerowparam00);

        TextView textview0 = new TextView(getActivity());
        textview0.setId(id_textview0);
        textview0.setText("Dec 0" + i);
        //textview0.setTextSize(12);
        textview0.setPadding(00,00,00,00);
        textview0.setSingleLine(false);
        textview0.setTextColor(Color.BLACK);
        //textview0.setGravity(Gravity.LEFT);
        //textview0param.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        //textview0param.addRule(RelativeLayout.LEFT_OF,imageview1.getId());
        //textview0param.addRule(RelativeLayout.RIGHT_OF,imageview1.getId());
        //textview0param.addRule(RelativeLayout.ALIGN_TOP,imageview1.getId());
        textview0param.addRule(RelativeLayout.CENTER_IN_PARENT,imageview1.getId());
        textview0.setGravity(Gravity.CENTER);
        textview0.setLayoutParams(textview0param);
        calender_image_text.addView(textview0,textview0param);
        linearh1.addView(calender_image_text,tablerowparam00);
</code>```

答:
This layout should help you out ...</p>

```<code><RelativeLayout
    android:layout_width="100dp"
    android:layout_height="100dp"
    >
    <ImageView
        android:id="@+id/image_view"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="centerCrop"
        android:src="@drawable/img_calendar" />

    <TextView
        android:id="@+id/text_view_date"
        android:padding="4dp"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/colorBlack"
        android:gravity="center"
        android:text="Dec 4"
        android:textAlignment="center"
        android:textSize="32sp"
        />
</RelativeLayout>
</code>```

Title: android image size scale

Body:
I need to add an image to the screen in a table row and have text over the image.

The image is a calendar with the date displayed on top. It work fine for the first device... see image here:

But get too small on the larger device... see image here:

the code is

RelativeLayout calender_image_text = new RelativeLayout(getActivity());
        ImageView imageview1 = new ImageView(getActivity());
        imageview1.setBackgroundResource(R.mipmap.calendar);
        imageview1.setPadding(00,00,00,00);
        //imageview1.setMaxHeight(150);
        //imageview1.setMaxWidth(150);
        LinearLayout.LayoutParams imageview2param = new LinearLayout.LayoutParams(120, 80);
        imageview1param.addRule(RelativeLayout.CENTER_IN_PARENT);
        calender_image_text.addView(imageview1,imageview2param);
        //linearh1.addView(calender_image_text,tablerowparam00);

        TextView textview0 = new TextView(getActivity());
        textview0.setId(id_textview0);
        textview0.setText("Dec 0" + i);
        //textview0.setTextSize(12);
        textview0.setPadding(00,00,00,00);
        textview0.setSingleLine(false);
        textview0.setTextColor(Color.BLACK);
        //textview0.setGravity(Gravity.LEFT);
        //textview0param.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        //textview0param.addRule(RelativeLayout.LEFT_OF,imageview1.getId());
        //textview0param.addRule(RelativeLayout.RIGHT_OF,imageview1.getId());
        //textview0param.addRule(RelativeLayout.ALIGN_TOP,imageview1.getId());
        textview0param.addRule(RelativeLayout.CENTER_IN_PARENT,imageview1.getId());
        textview0.setGravity(Gravity.CENTER);
        textview0.setLayoutParams(textview0param);
        calender_image_text.addView(textview0,textview0param);
        linearh1.addView(calender_image_text,tablerowparam00);

Body:
This layout should help you out ...

<RelativeLayout
    android:layout_width="100dp"
    android:layout_height="100dp"
    >
    <ImageView
        android:id="@+id/image_view"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="centerCrop"
        android:src="@drawable/img_calendar" />

    <TextView
        android:id="@+id/text_view_date"
        android:padding="4dp"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/colorBlack"
        android:gravity="center"
        android:text="Dec 4"
        android:textAlignment="center"
        android:textSize="32sp"
        />
</RelativeLayout>


问:
Swift 4 : Set Different Date and Time
I know how to get local date and time, but what I want to do is getting the date and time from different places. For example, I want to find out what the time and date is in New York. How can i solve this simple problem?

Here is my code for local date and time :

```<code>let date = NSDate()
let calendar = Calendar.current

let components = calendar.dateComponents([.hour, .minute, .month, .year, .day, .second, .weekOfMonth], from: date as Date)

let currentDate = calendar.date(from: components)
</code>```

I searched about it here, but i didn't find what i want and I'm still looking for the date libaries. If you know any source or sample to redirect me, I really appreciate that.

答:
If you don't know the time zone of the place you are searching for, you can use the CoreLocation's CLGeocoder and search on an address string. Then you can get the timezone for that place and translate that into the time you're looking for:</p>

```<code>let geocoder = CLGeocoder()
geocoder.geocodeAddressString("New York, New York") { (placemarks, error) in
    guard error == nil else {
        print("Error")
        print(error!.localizedDescription)
        return
    }
    guard let placemarks = placemarks,
        let place = placemarks.first else {
        print("No results")
        return
    }

    if let timeZone = place.timeZone {
        print("TimeZone: \(timeZone.identifier)")
        // TimeZone: America/New_York

        //Ignore the time zone offset from this one, it will be the difference between the current time and the new york time
        let dateInNewYork = Date().addingTimeInterval(TimeInterval.init(timeZone.secondsFromGMT()))
        print(dateInNewYork)
        // 2017-11-13 15:03:05 +0000

        //Or
        let formatter = DateFormatter()
        formatter.timeZone = TimeZone(identifier: timeZone.identifier)
        formatter.dateStyle = .long
        formatter.timeStyle = .long
        let formattedDateInNewYork = formatter.string(from: Date())
        print(formattedDateInNewYork)
        // November 13, 2017 at 3:03:05 PM EST

        //Or
        let components = Calendar.current.dateComponents(in: TimeZone(identifier: timeZone.identifier)!, from: Date())
        print(components.date!)
        // 2017-11-13 20:03:05 +0000
    }

}
</code>```

Title: Swift 4 : Set Different Date and Time

Body:
I know how to get local date and time, but what I want to do is getting the date and time from different places. For example, I want to find out what the time and date is in New York. How can i solve this simple problem?

Here is my code for local date and time :

let date = NSDate()
let calendar = Calendar.current

let components = calendar.dateComponents([.hour, .minute, .month, .year, .day, .second, .weekOfMonth], from: date as Date)

let currentDate = calendar.date(from: components)

I searched about it here, but i didn't find what i want and I'm still looking for the date libaries. If you know any source or sample to redirect me, I really appreciate that.

Body:
If you don't know the time zone of the place you are searching for, you can use the CoreLocation's CLGeocoder and search on an address string. Then you can get the timezone for that place and translate that into the time you're looking for:

let geocoder = CLGeocoder()
geocoder.geocodeAddressString("New York, New York") { (placemarks, error) in
    guard error == nil else {
        print("Error")
        print(error!.localizedDescription)
        return
    }
    guard let placemarks = placemarks,
        let place = placemarks.first else {
        print("No results")
        return
    }

    if let timeZone = place.timeZone {
        print("TimeZone: \(timeZone.identifier)")
        // TimeZone: America/New_York

        //Ignore the time zone offset from this one, it will be the difference between the current time and the new york time
        let dateInNewYork = Date().addingTimeInterval(TimeInterval.init(timeZone.secondsFromGMT()))
        print(dateInNewYork)
        // 2017-11-13 15:03:05 +0000

        //Or
        let formatter = DateFormatter()
        formatter.timeZone = TimeZone(identifier: timeZone.identifier)
        formatter.dateStyle = .long
        formatter.timeStyle = .long
        let formattedDateInNewYork = formatter.string(from: Date())
        print(formattedDateInNewYork)
        // November 13, 2017 at 3:03:05 PM EST

        //Or
        let components = Calendar.current.dateComponents(in: TimeZone(identifier: timeZone.identifier)!, from: Date())
        print(components.date!)
        // 2017-11-13 20:03:05 +0000
    }

}


问:
Electron for only front end
I am trying to make my web application into a desktop app. I have already built and configured a server to host the backend scripting written in python.

My front end is written in JS, JQuery, HTML, CSS.

I have found an open source framework called Electron that packages web apps into desktop apps. Can I implement this so that it only wraps around my front end components without having to alter my back end server?

答:
In essence, yes you can use your current web code to create a desktop app using Electron, as Electron in essence is basically just a simplified browser. However, you will need to add some things to your project if they don't already exist in order for Electron to work.

3 things in particular:

(See the quick start guide: https://electron.atom.io/docs/tutorial/quick-start/)

package.json

main.js

index.html

You'll also need nodejs installed as electron itself is an npm module.

So not quite as straightforward as you may have thought but definitely a fairly simple and viable approach.

Title: Electron for only front end


问:
Text is Hidden When Window Resizes
I'm building a website for class, based on a provided template, and I'm struggling to make it so that my text will move as the window gets resized (right now, resizing the window obscures the text and associated buttons).

Ideally, I'd like for the page to be anchored in such a way that the focus remains on the text/buttons - and by extension, the bottom right corner of the image - as the window is resized.

Here is my HTML:

```<code><!DOCTYPE html>
<html lang="en">
    <head>

        <meta name="viewport" content="width=device-width, inital-scale=1.0">
<!-- This tells mobile devices not to zoom out the page, start with scale=1 -->
        <link rel="stylesheet", type="text/css", href="Vendors/css/normalize.css">
        <link rel="stylesheet", type="text/css", href="Vendors/css/grid.css">
        <link rel="stylesheet", type="text/css", href="Vendors/css/ionicons.min.css">
        <link rel="stylesheet", type="text/css", href="Resources/css/style.css">
        <link rel="stylesheet", type="text/css", href="Resources/css/queries.css">
        <link href='http://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel='stylesheet' type='text/css'>

        <title>Whitetail Acres Tree Farm</title>
    </head>
    <body>
        <header>
            <nav>
                <div class="row">
                    <img src="Resources/img/logo-white.png" alt="Omnifood logo" class="logo">
                    <ul class="main-nav">
                        <li><a href="#features">Food Delivery</a></li>
                        <li><a href="#meals">How it Works</a></li>
                        <li><a href="#steps">Our Cities</a></li>
                        <li><a href="#cities">Sign up</a></li>
                    </ul>
                    <a class="mobile-nav-icon js--nav-icon"><i class="ion-navicon-round"></i></a>
                </div>
            </nav>
            <div class="hero-text-box">
                <h1>Schedule <br> Your Visit!</h1>
                <a class="btn btn-full js--scroll-to-plans" href="#">I'm hungry</a>
                <a class="btn btn-ghost js--scroll-to-start" href="#">Show me more</a>
            </div>
        </header>
</code>```

And here is my CSS:

```<code>/* Universal Reset*/
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html
{
    background-color: #ffffff;
    color: #555;
    font-family: 'Lato', 'Arial', sans-serif;
    font-size: 20px;
    font-weight: 300;
    text-rendering: optimizeLegibility;
}

.clearfix {zoom: 1}
.clearfix:after {
    content: '.';
    clear: both;
    display: block;
    height: 0;
    visibility: hidden;
}

header{
    background-image: url(img/hero.jpg);
    background-size: cover;
    background-position:bottom, right;
    height: 100vh;
    background-attachment:inherit;
}

.hero-text-box{
    position: absolute;
    width:1080px;
    top:80%;
    left:55%;
    text-align: right;
    transform: translate(-50%, -50%);
}

.row{
    max-width: 1140px;
    margin:0 auto;
}

section{
    padding: 80px 0;
}

.box{

    padding: 1%;
</code>```

答:
Looks like you havent defined a width for the row.
Try something like:</p>

```<code>.row{
max-width: 1140px;
width: 100%;
margin:0 auto;
}
</code>```

Title: Text is Hidden When Window Resizes

Body:
I'm building a website for class, based on a provided template, and I'm struggling to make it so that my text will move as the window gets resized (right now, resizing the window obscures the text and associated buttons).

Ideally, I'd like for the page to be anchored in such a way that the focus remains on the text/buttons - and by extension, the bottom right corner of the image - as the window is resized.

Here is my HTML:

<!DOCTYPE html>

        <meta name="viewport" content="width=device-width, inital-scale=1.0">

        <link rel="stylesheet", type="text/css", href="Vendors/css/normalize.css">
        <link rel="stylesheet", type="text/css", href="Vendors/css/grid.css">
        <link rel="stylesheet", type="text/css", href="Vendors/css/ionicons.min.css">
        <link rel="stylesheet", type="text/css", href="Resources/css/style.css">
        <link rel="stylesheet", type="text/css", href="Resources/css/queries.css">
        <link href='http://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel='stylesheet' type='text/css'>

        <title>Whitetail Acres Tree Farm</title>

Food Delivery

How it Works

Our Cities

Sign up

Schedule
 Your Visit!

                I'm hungry
                Show me more

And here is my CSS:

/* Universal Reset*/
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html
{
    background-color: #ffffff;
    color: #555;
    font-family: 'Lato', 'Arial', sans-serif;
    font-size: 20px;
    font-weight: 300;
    text-rendering: optimizeLegibility;
}

.clearfix {zoom: 1}
.clearfix:after {
    content: '.';
    clear: both;
    display: block;
    height: 0;
    visibility: hidden;
}

header{
    background-image: url(img/hero.jpg);
    background-size: cover;
    background-position:bottom, right;
    height: 100vh;
    background-attachment:inherit;
}

.hero-text-box{
    position: absolute;
    width:1080px;
    top:80%;
    left:55%;
    text-align: right;
    transform: translate(-50%, -50%);
}

.row{
    max-width: 1140px;
    margin:0 auto;
}

section{
    padding: 80px 0;
}

.box{

    padding: 1%;

Body:
Looks like you havent defined a width for the row.
Try something like:

.row{
max-width: 1140px;
width: 100%;
margin:0 auto;
}


问:
Tensorboard error: 'Tensor' object has no attribute 'value'
My goal: Add arbitrary text to tensorboard.

My code:

```<code>text = "muh teeeext"
summary = tf.summary.text("Muh taaaag", tf.convert_to_tensor(text))
writer.add_summary(summary)
</code>```

My error:

```<code>  File xxx, line xxx, in xxx
    writer.add_summary(summary)
  File "/home/xxx/.local/lib/python3.5/site-packages/tensorflow/python/summary/writer/writer.py", line 123, in add_summary
    for value in summary.value:
AttributeError: 'Tensor' object has no attribute 'value'
</code>```

答:
writer.add_summary(summary) is a tensor. the tensorboard writer expects a string for the summary. To get the summary from the tensor, add an eval() to the add_summary line like so:

writer.add_summary(summary).eval()

Body:
My goal: Add arbitrary text to tensorboard.

My code:

text = "muh teeeext"
summary = tf.summary.text("Muh taaaag", tf.convert_to_tensor(text))
writer.add_summary(summary)

My error:

  File xxx, line xxx, in xxx
    writer.add_summary(summary)
  File "/home/xxx/.local/lib/python3.5/site-packages/tensorflow/python/summary/writer/writer.py", line 123, in add_summary
    for value in summary.value:
AttributeError: 'Tensor' object has no attribute 'value'


问:
How can I prevent a gitlab job running on push event
I have a simple gitlab-yaml file that I thought would run a job when only scheduled. However, it is getting fire on a push event as well.
Can anyone please tell me the correct way in which to specify that a job is only run when scheduled.
This is my gitlab-yaml file

```<code>job:on-schedule:
    only:
        - schedules
        - branches
    script:
        - /usr/local/bin/phpunit -c phpunit_config.xml
</code>```

Thanks

答:
According to the GitLab documentation, branches means "When a branch is pushed".

https://docs.gitlab.com/ce/ci/yaml/README.html#only-and-except-simplified

So including branches in your only: section causes the pipeline job to also run on pushes to any branch.

You can either remove the branches entry, or if you wanted to restrict to pushes for a specific branch you could extend the branch entry to include project and branch name (branches@<project>/<branch>).

My suggestion is to reduce your YML to:

```<code>job:on-schedule:
    only:
        - schedules
    script:
        - /usr/local/bin/phpunit -c phpunit_config.xml
</code>```

Body:
I have a simple gitlab-yaml file that I thought would run a job when only scheduled. However, it is getting fire on a push event as well.
Can anyone please tell me the correct way in which to specify that a job is only run when scheduled.
This is my gitlab-yaml file

job:on-schedule:
    only:
        - schedules
        - branches
    script:
        - /usr/local/bin/phpunit -c phpunit_config.xml

Thanks

Body:
According to the GitLab documentation, branches means "When a branch is pushed".

https://docs.gitlab.com/ce/ci/yaml/README.html#only-and-except-simplified

So including branches in your only: section causes the pipeline job to also run on pushes to any branch.

You can either remove the branches entry, or if you wanted to restrict to pushes for a specific branch you could extend the branch entry to include project and branch name (branches@<project>/<branch>).

My suggestion is to reduce your YML to:

job:on-schedule:
    only:
        - schedules
    script:
        - /usr/local/bin/phpunit -c phpunit_config.xml


问:
Array of objects as property
I know how to initialise an array of objects:

```<code>arrayOfA(3,2) = ClassA();

for i = 1:3
    for j = 1:2
        arrayofA(i,j) = ClassA(...);
    end
end
</code>```

but when I try this for a property:

```<code>classdef ClassB

properties
    arrayOfA;
    ...
end

methods
    %% Constructor
    function b = ClassB(...)
        b.arrayOfA(3,2) = ClassA();  % Error!
        ...
    end
end
</code>```

I get the exception Conversion to double from ClassA is not possible.

I have read that when a default value for a property is not provided, it is initialised to an empty array of doubles. This explains the exception, but how do I set the default value of arrayOfA such that I can fill it with objects?

I have tried:

```<code>properties
    arrayOfA(3,2) = ClassA;
</code>```

but this gives the exception Unbalanced or unexpected parenthesis or bracket.

Edit: I am using MATLAB R2015b, which turns out to affect the solution - see below.

答:
In the property definition of arrayOfA, you should be able to set it as:

```<code>properties
    arrayOfA = ClassA.empty
end
</code>```

empty is a built-in method of all non-abstract classes for exactly this purpose. It will initialise the array to an empty array of ClassA, rather than an empty array of doubles.

Title: Array of objects as property

Body:
I know how to initialise an array of objects:

arrayOfA(3,2) = ClassA();

for i = 1:3
    for j = 1:2
        arrayofA(i,j) = ClassA(...);
    end
end

but when I try this for a property:

classdef ClassB

properties
    arrayOfA;
    ...
end

methods
    %% Constructor
    function b = ClassB(...)
        b.arrayOfA(3,2) = ClassA();  % Error!
        ...
    end
end

I get the exception Conversion to double from ClassA is not possible.

I have read that when a default value for a property is not provided, it is initialised to an empty array of doubles. This explains the exception, but how do I set the default value of arrayOfA such that I can fill it with objects?

I have tried:

properties
    arrayOfA(3,2) = ClassA;

but this gives the exception Unbalanced or unexpected parenthesis or bracket.

Edit: I am using MATLAB R2015b, which turns out to affect the solution - see below.

Body:
In the property definition of arrayOfA, you should be able to set it as:

properties
    arrayOfA = ClassA.empty
end

empty is a built-in method of all non-abstract classes for exactly this purpose. It will initialise the array to an empty array of ClassA, rather than an empty array of doubles.


问:
Correct Way of Subscribing to Multiple Intervals of Differing Times
I am building my first Reactive.NET application and am struggling with how to manage two sets of observables.

To start with, I am polling a server in both sets.  I have two "rings" of time (faster and slower): one that fires every second and one that fires every 15 seconds.  I noticed that if the server takes a while to process one of the calls in one of the rings, it will immediately "catch up" and continuously fire the events once the call has completed (via timeout or otherwise).  So, if I am firing every second and there is a 30 second delay, the subscription will resume by firing 30 times once the delay has completed (assuming there are no other further delays).  This is not preferred as I want to keep calls to the server to a minimum, so sticking strictly per frame of time per ring.  That is, if there is a 30 second delay, I do not want to bombarded the server with calls once that delay has elapsed.

I have gotten around this with using Sample. And, actually, everything works well, except now when the application starts, there is a delay on the outer ring and I do not see any output until 15 seconds.  With the 1-second ring I got around this by using the StartsWith(-1) but I cannot seem to get around this with the outer (slower) ring.

Here is my code:

```<code>var fast = TimeSpan.FromSeconds(1);
var slow = TimeSpan.FromSeconds(15);
var application = Observable.Interval(fast)
                            .Sample(fast)
                            .StartWith(-1)
                            .Timestamp()
                            .Window(slow)
                            .Sample(slow)
                            .Subscribe(window =>
                                        {
                                            // Outer (slower) ring: ...

                                            window.Subscribe(x =>
                                                            {
                                                                // Inner (faster) ring: ...
                                                            });
                                        });
</code>```

So, really, the questions are:

Is this the correct/preferred way of creating two rings of subscribed time of differing intervals in Rx?  (This is important going forward as I can see having additional rings of time such as 30 seconds, 1 minute, 5 minutes, etc. and I want to be sure I get this right.)

If not, what is the best/preferred way doing this?

How do I ensure the outer ring fires immediately and does not take 15 seconds to fire on the first attempt?

EDIT:

Based on @yohanmishkin's answer, here is the code that I am using:

```<code>var poll = Observable.Interval(TimeSpan.FromSeconds(1));
var lessFrequentPoll = Observable.Interval(TimeSpan.FromSeconds(15));

poll.Subscribe(o => application.UpdateFrequent(o));
lessFrequentPoll.Subscribe(o => application.UpdateLessFrequent(o));

using (new CompositeDisposable(poll, lessFrequentPoll))
{
    // ...
}
</code>```

As mentioned in the answer there, I actually did use this when I first started Rx, but I was originally thinking (due to my primitive understanding of Rx) that for each subscription I would have to nest the using contexts and wanted to avoid that.  So, if I ended up with 5 "rings" of time, I would have 5 nested using's and that is not pretty to me.  Using the CompositeDisposable alleviates this.

答:
I find this kind of thing is a bit tricky with Rx. It seems as though the subscribed work shouldn't really have the side-effect of modifying the sequence itself. However, that's what you need, because if the work runs slowly (the service is slow) you need the polling frequency to be reduced.

I think that the various recursive overloads of IScheduler.Schedule() are designed to support this kind of thing. See http://www.introtorx.com/Content/v1.0.10621.0/15_SchedulingAndThreading.html.

The idea is something like this:

```<code>private static IObservable<int> PollServer(IScheduler scheduler)
{
    return Observable.Create<int>(
        observer =>
        {
            var cts = new CancellationTokenSource();
            var token = cts.Token;

            // Make initial call immediately
            var scheduled = scheduler.Schedule(
                TimeSpan.Zero,
                async action =>
                {
                    try
                    {
                        var res = await CallServer(token);
                        observer.OnNext(res);

                        // Trigger another iteration after poll delay
                        action(TimeSpan.FromSeconds(1));
                    }
                    catch (Exception ex)
                    {
                        observer.OnError(ex);
                    }
                });

            // Discontinue polling when observable is disposed
            return () =>
            {
                cts.Cancel();
                scheduled.Dispose();
            };
        });
}

private static async Task<int> CallServer(CancellationToken token)
{
    // Remote service call
    await Task.Delay(100);
    return 42;
}
</code>```

This obviously presents only the code for your "slow ring", but hopefully it gives an idea of what you would need.

Body:
I am building my first Reactive.NET application and am struggling with how to manage two sets of observables.

To start with, I am polling a server in both sets.  I have two "rings" of time (faster and slower): one that fires every second and one that fires every 15 seconds.  I noticed that if the server takes a while to process one of the calls in one of the rings, it will immediately "catch up" and continuously fire the events once the call has completed (via timeout or otherwise).  So, if I am firing every second and there is a 30 second delay, the subscription will resume by firing 30 times once the delay has completed (assuming there are no other further delays).  This is not preferred as I want to keep calls to the server to a minimum, so sticking strictly per frame of time per ring.  That is, if there is a 30 second delay, I do not want to bombarded the server with calls once that delay has elapsed.

I have gotten around this with using Sample. And, actually, everything works well, except now when the application starts, there is a delay on the outer ring and I do not see any output until 15 seconds.  With the 1-second ring I got around this by using the StartsWith(-1) but I cannot seem to get around this with the outer (slower) ring.

Here is my code:

var fast = TimeSpan.FromSeconds(1);
var slow = TimeSpan.FromSeconds(15);
var application = Observable.Interval(fast)
                            .Sample(fast)
                            .StartWith(-1)
                            .Timestamp()
                            .Window(slow)
                            .Sample(slow)
                            .Subscribe(window =>
                                        {
                                            // Outer (slower) ring: ...

                                            window.Subscribe(x =>
                                                            {
                                                                // Inner (faster) ring: ...
                                                            });
                                        });

So, really, the questions are:

Is this the correct/preferred way of creating two rings of subscribed time of differing intervals in Rx?  (This is important going forward as I can see having additional rings of time such as 30 seconds, 1 minute, 5 minutes, etc. and I want to be sure I get this right.)

If not, what is the best/preferred way doing this?

How do I ensure the outer ring fires immediately and does not take 15 seconds to fire on the first attempt?

EDIT:

Based on @yohanmishkin's answer, here is the code that I am using:

var poll = Observable.Interval(TimeSpan.FromSeconds(1));
var lessFrequentPoll = Observable.Interval(TimeSpan.FromSeconds(15));

poll.Subscribe(o => application.UpdateFrequent(o));
lessFrequentPoll.Subscribe(o => application.UpdateLessFrequent(o));

using (new CompositeDisposable(poll, lessFrequentPoll))
{
    // ...
}

As mentioned in the answer there, I actually did use this when I first started Rx, but I was originally thinking (due to my primitive understanding of Rx) that for each subscription I would have to nest the using contexts and wanted to avoid that.  So, if I ended up with 5 "rings" of time, I would have 5 nested using's and that is not pretty to me.  Using the CompositeDisposable alleviates this.

Body:
I find this kind of thing is a bit tricky with Rx. It seems as though the subscribed work shouldn't really have the side-effect of modifying the sequence itself. However, that's what you need, because if the work runs slowly (the service is slow) you need the polling frequency to be reduced.

I think that the various recursive overloads of IScheduler.Schedule() are designed to support this kind of thing. See http://www.introtorx.com/Content/v1.0.10621.0/15_SchedulingAndThreading.html.

The idea is something like this:

private static IObservable<int> PollServer(IScheduler scheduler)
{
    return Observable.Create<int>(
        observer =>
        {
            var cts = new CancellationTokenSource();
            var token = cts.Token;

            // Make initial call immediately
            var scheduled = scheduler.Schedule(
                TimeSpan.Zero,
                async action =>
                {
                    try
                    {
                        var res = await CallServer(token);
                        observer.OnNext(res);

                        // Trigger another iteration after poll delay
                        action(TimeSpan.FromSeconds(1));
                    }
                    catch (Exception ex)
                    {
                        observer.OnError(ex);
                    }
                });

            // Discontinue polling when observable is disposed
            return () =>
            {
                cts.Cancel();
                scheduled.Dispose();
            };
        });
}

private static async Task<int> CallServer(CancellationToken token)
{
    // Remote service call
    await Task.Delay(100);
    return 42;
}

This obviously presents only the code for your "slow ring", but hopefully it gives an idea of what you would need.


问:
Why is my free-jqgrid showing no data?
CONTEXT

I'm working on migrating a very large app with many customized grids to jqgrid-free. All of the grids work in the existing code, but much of the existing work does not translate well which was expected, but is frustrating. Why does the following grid definition show no data and yet give zero errors?

CODE

```<code>{
            datastr: val,
            altRows: true,
            datatype: 'jsonstring',
            sortable: false,
            width: Global.bodyWidth() - 14,
            colNames: [],
            rowNum: 10000,
            colModel: col_model,
            onCellSelect: function(id){
                $this.grid_select_id_array = [id];
                $this.setDefaultMenu();
            },
            ondblClickRow: function() {
                $this.onGridDblClickRow();
            },
            gridview: true,
            treeGrid: true,
            treeGridModel: 'adjacency',
            treedatatype: 'local',
            ExpandColumn: 'name',
            multiselect: false,
            jsonReader: {
                repeatitems: false,
                root: function( obj ) {
                    return obj;
                },
                page: function( obj ) {
                    return 1;
                },
                total: function( obj ) {
                    return 1;
                },
                records: function( obj ) {
                    return obj.length;
                }
            }
        }
</code>```

FIDDLE

Here's a fiddle to show in more detail what the data looks like:
See fiddle at: https://jsfiddle.net/catbadger/mhvzerdg/18

答:
I'd suggest you to fill the data in the grid during creating the grid. It's more effective as to call always setData method directly after creating the grid. Moreover, free jqGrid allows to create TreeGrid using datatype: "local" and data as the input data. The option jsonReader and many other will be unneeded. You can use just

var grid_setup = {
        altRows: true,
        width: $('body').width(),
        treeGrid: true,
        treeGridModel: 'adjacency',
        ExpandColumn: 'name',
        multiselect: false
    };
grid = new TTGrid('grid_here',grid_setup,columns, "", result_data);
```

<p>see https://jsfiddle.net/OlegKi/mhvzerdg/19/</p>

<p><strong>UPDATED:</strong> If you want to understand <em>why</em> your original code not work you can examine another demo https://jsfiddle.net/OlegKi/mhvzerdg/20/, which just fixes the option <code>treedatatype: 'local'</code> to <code>treedatatype: 'jsonstring'</code> and changes</p>

```this.setData = function( data ) {
    if ( this.grid ) {
        this.grid.clearGridData();
        this.setGridParam({data: data});
        this.reloadGrid();
    } else {
        throw('ERROR: Grid is not ready yet.');
    }
}
```

<p>to</p>

```this.setData = function( data ) {
    if ( this.grid ) {
        this.grid.clearGridData();
        if (this.grid.getGridParam("treeGrid")) {
            this.setGridParam({
                datatype: "jsonstring",
                datastr: data
            });
        } else {
            this.setGridParam({data: data});
        }
        this.reloadGrid();
    } else {
        throw('ERROR: Grid is not ready yet.');
    }
}
```

I still recommend you to follow my first demo and fill the grid during creating.

Title: Why is my free-jqgrid showing no data?

Body:
CONTEXT

I'm working on migrating a very large app with many customized grids to jqgrid-free. All of the grids work in the existing code, but much of the existing work does not translate well which was expected, but is frustrating. Why does the following grid definition show no data and yet give zero errors?

CODE

{
            datastr: val,
            altRows: true,
            datatype: 'jsonstring',
            sortable: false,
            width: Global.bodyWidth() - 14,
            colNames: [],
            rowNum: 10000,
            colModel: col_model,
            onCellSelect: function(id){
                $this.grid_select_id_array = [id];
                $this.setDefaultMenu();
            },
            ondblClickRow: function() {
                $this.onGridDblClickRow();
            },
            gridview: true,
            treeGrid: true,
            treeGridModel: 'adjacency',
            treedatatype: 'local',
            ExpandColumn: 'name',
            multiselect: false,
            jsonReader: {
                repeatitems: false,
                root: function( obj ) {
                    return obj;
                },
                page: function( obj ) {
                    return 1;
                },
                total: function( obj ) {
                    return 1;
                },
                records: function( obj ) {
                    return obj.length;
                }
            }
        }

FIDDLE

Here's a fiddle to show in more detail what the data looks like:
See fiddle at: https://jsfiddle.net/catbadger/mhvzerdg/18

Body:
I'd suggest you to fill the data in the grid during creating the grid. It's more effective as to call always setData method directly after creating the grid. Moreover, free jqGrid allows to create TreeGrid using datatype: "local" and data as the input data. The option jsonReader and many other will be unneeded. You can use just

var grid_setup = {
        altRows: true,
        width: $('body').width(),
        treeGrid: true,
        treeGridModel: 'adjacency',
        ExpandColumn: 'name',
        multiselect: false
    };
grid = new TTGrid('grid_here',grid_setup,columns, "", result_data);

see https://jsfiddle.net/OlegKi/mhvzerdg/19/

UPDATED: If you want to understand why your original code not work you can examine another demo https://jsfiddle.net/OlegKi/mhvzerdg/20/, which just fixes the option treedatatype: 'local' to treedatatype: 'jsonstring' and changes

this.setData = function( data ) {
    if ( this.grid ) {
        this.grid.clearGridData();
        this.setGridParam({data: data});
        this.reloadGrid();
    } else {
        throw('ERROR: Grid is not ready yet.');
    }
}

to

this.setData = function( data ) {
    if ( this.grid ) {
        this.grid.clearGridData();
        if (this.grid.getGridParam("treeGrid")) {
            this.setGridParam({
                datatype: "jsonstring",
                datastr: data
            });
        } else {
            this.setGridParam({data: data});
        }
        this.reloadGrid();
    } else {
        throw('ERROR: Grid is not ready yet.');
    }
}

I still recommend you to follow my first demo and fill the grid during creating.


问:
Issues using regex to match either (forward slash[/]) or (hyphen[-]) characters in data validation for data-processing program
I have researched fairly extensively (I've looked at 5 or 6 stackoverflow posts that have often lead me to stare at the official Java regex resource for 30 minutes at a time) but I'm still struggling with this issue. Here is my code for the String matching method:

```<code>        public String checkDateFormat(String date)
        {
            if (date.matches("[0-3][0-9](?:-|/)[0-1][0-9](?:-|/)[0-2][0-9][0-9][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else if (date.matches("[0-1][0-9](?:-|/)[0-3][0-9](?:-|/)[0-2][0-9][0-9][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else if (date.matches("[0-2][0-9][0-9][0-9](?:-|/)[0-1][0-9](?:-|/)[0-3][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else if (date.matches("[0-2][0-9][0-9][0-9](?:-|/)[0-3][0-9](?:-|/)[0-1][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else
            {
                throw new InvalidParameterException("(The passed argument is invalid date format: [yyyy/dd/MM, yyyy/MM/dd, MM/dd/yyyy, or dd/MM/yyyy])");
            }
        }
</code>```

The current setup for checking the - and / conditions is one of many I've tried; I've also attempted these: [-/] [-\\\\/] [-&&[/]] [-[/]] and probably a few more I don't remember.

The program simply needs to be able to accept - and / as different separators in the dd/MM/yyyy format as I'm reading this info from multiple csv files that contain the format both as dd/MM/yyyy and dd-MM-yyyy.

EDIT: I've updated my code to this for the time being, but I still fail to pass the data through this validation method. To be more specific about the problem, the specific string I'm checking is 2016-01-01. I've also tried using the code Ole V.V. provided using the DateTimeFormatter class, but to no success.

答:
Answer number one, do not use regular expression for validating dates. Java has a nice API for parsing dates in all thinkable formats, so try parsing your date and see if it succeeds:

```<code>private static final String[] validFormatPatterns = {
        "dd/MM/uuuu HH:mm:ss",
        "dd-MM-uuuu HH:mm:ss",
        "MM/dd/uuuu HH:mm:ss",
        "MM-dd-uuuu HH:mm:ss",
        "uuuu/MM/dd HH:mm:ss",
        "uuuu-MM-dd HH:mm:ss",
        "uuuu/dd/MM HH:mm:ss",
        "uuuu-dd-MM HH:mm:ss"
};

private static final DateTimeFormatter[] validFormats
        = Arrays.stream(validFormatPatterns)
                .map(fp -> DateTimeFormatter.ofPattern(fp).withResolverStyle(ResolverStyle.STRICT))
                .toArray(DateTimeFormatter[]::new);

public String checkDateFormat(String date) {
    for (DateTimeFormatter formatter : validFormats) {
        try {
            LocalDateTime.parse(date, formatter);
            return date;
        } catch (DateTimeParseException dtpe) {
            // ignore, try next format
        }
    }
    throw new InvalidParameterException("(The passed argument is invalid date format:"
            + " [yyyy/dd/MM, yyyy/MM/dd, MM/dd/yyyy, or dd/MM/yyyy])");
}
</code>```

The .withResolverStyle(ResolverStyle.STRICT) part makes sure that not even invalid dates like 2017-29-02 23:32:30 are accepted.

Other than that, the regex notation for matching either a hyphen or a slash is (?:-|/). For example

```<code>        if (date.matches("[0-3][0-9](?:-|/)[0-1][0-9](?:-|/)[0-2][0-9][0-9][0-9]"
             + " [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
</code>```

(-|/) would work too, it’s a capturing group, useful if you need to know afterwards whether a hyphen or a slash was matched. If you don’t need this, insert ?: to make the group non-capturing as I just did.

EDIT: Yes, you may use a capturing group to verify that the same separating character (either hyphen or slash) is used in both places:

```<code>date.matches("[0-3][0-9](-|/)[0-1][0-9]\\1[0-2][0-9][0-9][0-9]"))
</code>```

(-|/) is the capturing group, and \\1 matches whatever the 1st (and only) capturing group matched. Groups are numbered from 1 since group 0 is the entire regular expression. The above matches 30/11/2017 and 30-11-2017 but not 30-11/2017.

Body:
I have researched fairly extensively (I've looked at 5 or 6 stackoverflow posts that have often lead me to stare at the official Java regex resource for 30 minutes at a time) but I'm still struggling with this issue. Here is my code for the String matching method:

        public String checkDateFormat(String date)
        {
            if (date.matches("[0-3][0-9](?:-|/)[0-1][0-9](?:-|/)[0-2][0-9][0-9][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else if (date.matches("[0-1][0-9](?:-|/)[0-3][0-9](?:-|/)[0-2][0-9][0-9][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else if (date.matches("[0-2][0-9][0-9][0-9](?:-|/)[0-1][0-9](?:-|/)[0-3][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else if (date.matches("[0-2][0-9][0-9][0-9](?:-|/)[0-3][0-9](?:-|/)[0-1][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else
            {
                throw new InvalidParameterException("(The passed argument is invalid date format: [yyyy/dd/MM, yyyy/MM/dd, MM/dd/yyyy, or dd/MM/yyyy])");
            }
        }

The current setup for checking the - and / conditions is one of many I've tried; I've also attempted these: [-/] [-\\\\/] [-&&[/]] [-[/]] and probably a few more I don't remember.

The program simply needs to be able to accept - and / as different separators in the dd/MM/yyyy format as I'm reading this info from multiple csv files that contain the format both as dd/MM/yyyy and dd-MM-yyyy.

EDIT: I've updated my code to this for the time being, but I still fail to pass the data through this validation method. To be more specific about the problem, the specific string I'm checking is 2016-01-01. I've also tried using the code Ole V.V. provided using the DateTimeFormatter class, but to no success.

Body:
Answer number one, do not use regular expression for validating dates. Java has a nice API for parsing dates in all thinkable formats, so try parsing your date and see if it succeeds:

private static final String[] validFormatPatterns = {
        "dd/MM/uuuu HH:mm:ss",
        "dd-MM-uuuu HH:mm:ss",
        "MM/dd/uuuu HH:mm:ss",
        "MM-dd-uuuu HH:mm:ss",
        "uuuu/MM/dd HH:mm:ss",
        "uuuu-MM-dd HH:mm:ss",
        "uuuu/dd/MM HH:mm:ss",
        "uuuu-dd-MM HH:mm:ss"
};

private static final DateTimeFormatter[] validFormats
        = Arrays.stream(validFormatPatterns)
                .map(fp -> DateTimeFormatter.ofPattern(fp).withResolverStyle(ResolverStyle.STRICT))
                .toArray(DateTimeFormatter[]::new);

public String checkDateFormat(String date) {
    for (DateTimeFormatter formatter : validFormats) {
        try {
            LocalDateTime.parse(date, formatter);
            return date;
        } catch (DateTimeParseException dtpe) {
            // ignore, try next format
        }
    }
    throw new InvalidParameterException("(The passed argument is invalid date format:"
            + " [yyyy/dd/MM, yyyy/MM/dd, MM/dd/yyyy, or dd/MM/yyyy])");
}

The .withResolverStyle(ResolverStyle.STRICT) part makes sure that not even invalid dates like 2017-29-02 23:32:30 are accepted.

Other than that, the regex notation for matching either a hyphen or a slash is (?:-|/). For example

        if (date.matches("[0-3][0-9](?:-|/)[0-1][0-9](?:-|/)[0-2][0-9][0-9][0-9]"
             + " [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))

(-|/) would work too, it’s a capturing group, useful if you need to know afterwards whether a hyphen or a slash was matched. If you don’t need this, insert ?: to make the group non-capturing as I just did.

EDIT: Yes, you may use a capturing group to verify that the same separating character (either hyphen or slash) is used in both places:

date.matches("[0-3][0-9](-|/)[0-1][0-9]\\1[0-2][0-9][0-9][0-9]"))

(-|/) is the capturing group, and \\1 matches whatever the 1st (and only) capturing group matched. Groups are numbered from 1 since group 0 is the entire regular expression. The above matches 30/11/2017 and 30-11-2017 but not 30-11/2017.


问:
How do i get my code to append to the end of a specific csv row
Here is my code:

```<code>import csv

with open("Grades.txt", "r") as file:
        reader = csv.reader(file)
        for row in reader:
            if name == row[0]:
                with open("Grades.txt", "a") as file:
                    writer = csv.writer(file)
                    writer.writerow(grade)
</code>```

The variable name and grade have already been defined in an earlier function. I have a text file with a list of names so the code checks if the name(John) is in the text file and then is supposed to write the grade(A) next the name with a comma separating it. The problem is that my code will write the grade a space or 2 spaces below the entire list of names. If I can get it to write to the end of the name it would just be shown like (JohnA) with no separation. Im clueless about how to go about fixing this. I would appreciate if you could correct my code to do what I need it to. The variable name is an input from a login in a different function so the input is different every time. Also new names may be added through my sign up function so the similar question doesn't help.

for example say my text file looked like this:

John

Sam

Bob

And the grade Sam got was an A. How would I append the A grade to the end of Bobs name with a comma separating the name and the grade?

答:
I don't see how this code example should do the job you describe. Sorry.

```<code>import csv

students = [["Anne", "A"], ["Emily", "B"]]

with open("grades.csv", "w", newline="") as f:
    writer = csv.writer(f)
    for row in students:
        writer.writerow(row)
</code>```

You must give a tupel or a list as a row to csv.writer. What you describe sounds that you write two times to that file, but I don't see that this is been done by your code as described.

I hope to help you a little bit. Sorry at the moment I can't comment...

New:

What I want to say is, that you should put the names and grades in your main program together and then write it to the file. This is how I would solve your task.

```<code>names = ["John", "Sam", "Bob"]
grades = ["A", "B", "C"]

names_grades = zip(names, grades)

for row in names_grades:
    print(row)
</code>```

The new row can be written easily to your file.

Body:
Here is my code:

import csv

with open("Grades.txt", "r") as file:
        reader = csv.reader(file)
        for row in reader:
            if name == row[0]:
                with open("Grades.txt", "a") as file:
                    writer = csv.writer(file)
                    writer.writerow(grade)

The variable name and grade have already been defined in an earlier function. I have a text file with a list of names so the code checks if the name(John) is in the text file and then is supposed to write the grade(A) next the name with a comma separating it. The problem is that my code will write the grade a space or 2 spaces below the entire list of names. If I can get it to write to the end of the name it would just be shown like (JohnA) with no separation. Im clueless about how to go about fixing this. I would appreciate if you could correct my code to do what I need it to. The variable name is an input from a login in a different function so the input is different every time. Also new names may be added through my sign up function so the similar question doesn't help.

for example say my text file looked like this:

John

Sam

Bob

And the grade Sam got was an A. How would I append the A grade to the end of Bobs name with a comma separating the name and the grade?

Body:
I don't see how this code example should do the job you describe. Sorry.

import csv

students = [["Anne", "A"], ["Emily", "B"]]

with open("grades.csv", "w", newline="") as f:
    writer = csv.writer(f)
    for row in students:
        writer.writerow(row)

You must give a tupel or a list as a row to csv.writer. What you describe sounds that you write two times to that file, but I don't see that this is been done by your code as described.

I hope to help you a little bit. Sorry at the moment I can't comment...

New:

What I want to say is, that you should put the names and grades in your main program together and then write it to the file. This is how I would solve your task.

names = ["John", "Sam", "Bob"]
grades = ["A", "B", "C"]

names_grades = zip(names, grades)

for row in names_grades:
    print(row)

The new row can be written easily to your file.


问:
write error disk full in EC2 Machine
I have my EC2 linux instance where some softwares are installed.
I downloaded a new zip and was trying to unzip it.

I got this error   write error (disk full?).  Continue? (y/n/^C) n

The zip is not corrupted and I can unzip it from other instances.

I change instance type from small to medium and then large.Nothing worked.

I ran df -h .

```<code>$ df -h
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs         16G   56K   16G   1% /dev
tmpfs            16G     0   16G   0% /dev/shm
/dev/xvda1      9.8G  9.7G     0 100% /
</code>```

I think /dev/xvda1 is culprit. How can i increase the size of this?
What is this /dev/xvda1

答:
It is not a matter of instance type. You must change the volume (EBS) size.

Go to console and select the EBS of that instance , click action dropdown menu , then click modify volume  ( A form will appear with the current volume size, increase it )

Try to remove some kilobytes to be able to run (3). rm -rf /tmp/* for example.

Grow/Expand your filesystem :

```<code>sudo growpart /dev/xvda 1
sudo resize2fs /dev/xvda1
</code>```

NOTES :

check Step(1) by lsblk command and check step (3 ) by df -h

Scale down your instance before receiving a huge billing the end of month  ( Let it small as it was )

Title: write error disk full in EC2 Machine

Body:
I have my EC2 linux instance where some softwares are installed.
I downloaded a new zip and was trying to unzip it.

I got this error   write error (disk full?).  Continue? (y/n/^C) n

The zip is not corrupted and I can unzip it from other instances.

I change instance type from small to medium and then large.Nothing worked.

I ran df -h .

$ df -h
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs         16G   56K   16G   1% /dev
tmpfs            16G     0   16G   0% /dev/shm
/dev/xvda1      9.8G  9.7G     0 100% /

I think /dev/xvda1 is culprit. How can i increase the size of this?
What is this /dev/xvda1

Body:
It is not a matter of instance type. You must change the volume (EBS) size.

Go to console and select the EBS of that instance , click action dropdown menu , then click modify volume  ( A form will appear with the current volume size, increase it )

Try to remove some kilobytes to be able to run (3). rm -rf /tmp/* for example.

Grow/Expand your filesystem :

sudo growpart /dev/xvda 1
sudo resize2fs /dev/xvda1

NOTES :

check Step(1) by lsblk command and check step (3 ) by df -h

Scale down your instance before receiving a huge billing the end of month  ( Let it small as it was )


问:
Bind array values to dropdown in AngularJs
I have an Edit Page there I have an drop down called Role, while inserting I sent a value (like 1 instead "Role Name") to db, while retrieving to edit page I couldn't able to initialize the selected text in drop down

below is my html code

```<code><label class="adjust1-label-right">Role</label>
<select id="role" class="adjust-select-combo" ng-options="r.role_name for r in Role_Name track by r.roleid" ng-model="role">
      <option ng-repeat="rol.roleid for rol in Role_Name" value="{{rol.roleid}}">{{rol.role_name}}</option>
</select>
</code>```

I tried this but no luck

```<code>$scope.role = $scope.Role_Name[0];
</code>```

My data looks like

```<code>[{"Role_Id":1,"User_Id":10001}]
</code>```

答:
Your binding won't work, because you are using ng-options in your select along with ng-repeat in your options, only one of them should be used.

And use ng-value instead of value, this is how should be your HTML binding:

```<code><select id="role" class="adjust-select-combo" ng-model="role">
   <option ng-selected="rol == role"
        ng-repeat="rol in Role_Name"
        ng-value="rol.Role_Id">{{rol.User_Id}}
   </option>
</select>
</code>```

Demo:

This is a working Snippet:

var app = angular.module('app', []);

app.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {

  $scope.Role_Name = [{
    "Role_Id": 1,
    "User_Id": 10001
  }, {
    "Role_Id": 2,
    "User_Id": 10002
  }, {
    "Role_Id": 3,
    "User_Id": 10003
  }];
  $scope.role = $scope.Role_Name[1];

}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>

<html ng-app="app">

  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>

<body>

  <div ng-controller="MainCtrl">
    <select id="role" class="adjust-select-combo" ng-model="role">
   <option ng-selected="rol == role"
        ng-repeat="rol in Role_Name"
        ng-value="rol.Role_Id">{{rol.User_Id}}
   </option>
</select>
  </div>

</body>

</html></code>```

Body:
I have an Edit Page there I have an drop down called Role, while inserting I sent a value (like 1 instead "Role Name") to db, while retrieving to edit page I couldn't able to initialize the selected text in drop down

below is my html code

Role
<select id="role" class="adjust-select-combo" ng-options="r.role_name for r in Role_Name track by r.roleid" ng-model="role">
      <option ng-repeat="rol.roleid for rol in Role_Name" value="{{rol.roleid}}">{{rol.role_name}}</option>
</select>

I tried this but no luck

$scope.role = $scope.Role_Name[0];

My data looks like

[{"Role_Id":1,"User_Id":10001}]

Body:
Your binding won't work, because you are using ng-options in your select along with ng-repeat in your options, only one of them should be used.

And use ng-value instead of value, this is how should be your HTML binding:

<select id="role" class="adjust-select-combo" ng-model="role">
   <option ng-selected="rol == role"
        ng-repeat="rol in Role_Name"
        ng-value="rol.Role_Id">{{rol.User_Id}}
   </option>
</select>

Demo:

This is a working Snippet:

var app = angular.module('app', []);

app.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {

  $scope.Role_Name = [{
    "Role_Id": 1,
    "User_Id": 10001
  }, {
    "Role_Id": 2,
    "User_Id": 10002
  }, {
    "Role_Id": 3,
    "User_Id": 10003
  }];
  $scope.role = $scope.Role_Name[1];

}]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>

<html ng-app="app">

  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>

<body>

  <div ng-controller="MainCtrl">
    <select id="role" class="adjust-select-combo" ng-model="role">
   <option ng-selected="rol == role"
        ng-repeat="rol in Role_Name"
        ng-value="rol.Role_Id">{{rol.User_Id}}
   </option>
</select>
  </div>

</body>

</html>


问:
How can I get Docker Linux container information from within the container itself?
I would like to make my docker containers aware of their configuration, the same way you can get information about EC2 instances through metadata.

I can use (provided docker is listening on port 4243)

```<code>curl http://172.17.42.1:4243/containers/$HOSTNAME/json
</code>```

to get some of its data, but would like to know if there is a better way at least the get the full ID of the container, because HOSTNAME is actually shortened to 12 characters and docker seems to perform a "best match" on it.

Also, how can I get the external IP of the docker host (other than accessing the EC2 metadata, which is specific to AWS)

答:
To make it simple,

Container ID is your host name inside docker

Container information is available inside /proc/self/cgroup

To get host name,

```<code>hostname
</code>```

or

```<code>uname -n
</code>```

or

```<code>cat /etc/host
</code>```

Output can be redirected to any file & read back from application
E.g.: # hostname > /usr/src//hostname.txt

ContentLicense: CC BY-SA 4.0

Body:
I would like to make my docker containers aware of their configuration, the same way you can get information about EC2 instances through metadata.

I can use (provided docker is listening on port 4243)

curl http://172.17.42.1:4243/containers/$HOSTNAME/json

to get some of its data, but would like to know if there is a better way at least the get the full ID of the container, because HOSTNAME is actually shortened to 12 characters and docker seems to perform a "best match" on it.

Also, how can I get the external IP of the docker host (other than accessing the EC2 metadata, which is specific to AWS)

Body:
To make it simple,

Container ID is your host name inside docker

Container information is available inside /proc/self/cgroup

To get host name,

hostname

or

uname -n

or

cat /etc/host

Output can be redirected to any file & read back from application
E.g.: # hostname > /usr/src//hostname.txt


问:
How to pass value of names in struct array as reference in C?
im supposed to be able to print all of the countries in the printfunction and pass it to the second if statement, but it doesn't seem to be printing . I know it's the

printf("%s\n", ctryList[numCountries].countryName);

part but i don't know what's wrong with it.

```<code>#include <stdio.h>
#include <string.h>
#include <stdbool.h>

const int MAX_COUNTRY_NAME_LENGTH = 50;

typedef struct CountryTvWatch_struct {
   char countryName[50];
   int tvMinutes;
} CountryTvWatch;

void PrintCountryNames(CountryTvWatch ctryList[], int numCountries)
{
   int i;
   for(i = 0; i < numCountries; i++)
   {
   printf("%s\n", ctryList[numCountries].countryName);
   }
   return;
}

int main(void) {
   // Source: www.statista.com, 2010
   const int NUM_COUNTRIES = 4;

   CountryTvWatch countryList[NUM_COUNTRIES];
   char countryToFind[MAX_COUNTRY_NAME_LENGTH];
   bool countryFound = false;
   int i = 0;

   strcpy(countryList[0].countryName, "Brazil");
   countryList[0].tvMinutes = 222;
   strcpy(countryList[1].countryName, "India");
   countryList[1].tvMinutes = 119;
   strcpy(countryList[2].countryName, "U.K.");
   countryList[2].tvMinutes = 242;
   strcpy(countryList[3].countryName, "U.S.A.");
   countryList[3].tvMinutes = 283;

   printf("Enter country name: \n");
   scanf("%s", countryToFind);

   countryFound = false;
   for (i = 0; i < NUM_COUNTRIES; ++i) { // Find country's index
      if (strcmp(countryList[i].countryName, countryToFind) == 0) {
         countryFound = true;
         printf("People in %s watch\n", countryToFind);
         printf("%d minutes of TV daily.\n", countryList[i].tvMinutes);
      }
   }
   if (!countryFound) {
      printf("Country not found, try again.\n");
      printf("Valid countries:\n");
      PrintCountryNames(countryList, NUM_COUNTRIES);
   }

   return 0;
}
</code>```

答:
the following proposed code:

incorporates the comments to the question

properly checks for I/O errors

lets the user know what countries are available to chose from

is appropriately spaced, both horizontally and vertically, for readability

performs the desired functionality

cleanly compiles

documents why each header file is included

and now the proposed code:

```<code>#include <stdio.h>     // scanf(), printf()
#include <stdlib.h>    // exit(), EXIT_FAILURE
#include <string.h>    // strcmp()
#include <stdbool.h>   // bool, true, false

#define MAX_COUNTRY_NAME_LENGTH  50
#define NUM_COUNTRIES  4

struct CountryTvWatch_struct
{
    char countryName[ MAX_COUNTRY_NAME_LENGTH ];
    int tvMinutes;
};
typedef struct CountryTvWatch_struct CountryTvWatch;

// prototypes
void PrintCountryNames( CountryTvWatch ctryList[], int numCountries );

int main(void)
{
   // Source: www.statista.com, 2010

   CountryTvWatch countryList[NUM_COUNTRIES];
   char countryToFind[ MAX_COUNTRY_NAME_LENGTH+1];

   strcpy(countryList[0].countryName, "Brazil");
   countryList[0].tvMinutes = 222;

   strcpy(countryList[1].countryName, "India");
   countryList[1].tvMinutes = 119;

   strcpy(countryList[2].countryName, "U.K.");
   countryList[2].tvMinutes = 242;

   strcpy(countryList[3].countryName, "U.S.A.");
   countryList[3].tvMinutes = 283;

   // let user know what countries are available and how they are spelled
   PrintCountryNames(countryList, NUM_COUNTRIES);

   printf("Enter country name: \n");

   // Note: following statement
   //     checks for error
   //     includes a MAX_CHAR modifier that is one less than
   //    the length of the input field
   if( 1 != scanf("%49s", countryToFind) )
   {
       perror( "scanf failed" );
       exit( EXIT_FAILURE );
   }

   // implied else, scanf successful

   bool countryFound = false;

   for ( int i = 0; i < NUM_COUNTRIES; ++i )
   { // Find country's index
      if (strcmp(countryList[i].countryName, countryToFind) == 0)
      {
         countryFound = true;
         printf("People in %s watch\n", countryToFind);
         printf("%d minutes of TV daily.\n", countryList[i].tvMinutes);
         break;  // exit the search loop early
      }
   }

   if (!countryFound)
   {
      printf("Country not found, try again.\n");
      printf("Valid countries:\n");
      PrintCountryNames(countryList, NUM_COUNTRIES);
   }

   return 0;
}

void PrintCountryNames( CountryTvWatch ctryList[], int numCountries )
{
    for( int i = 0; i < numCountries; i++ )
    {
        printf("%s\n", ctryList[ i ].countryName);
    }
}
</code>```

Body:
im supposed to be able to print all of the countries in the printfunction and pass it to the second if statement, but it doesn't seem to be printing . I know it's the

printf("%s\n", ctryList[numCountries].countryName);

part but i don't know what's wrong with it.

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

const int MAX_COUNTRY_NAME_LENGTH = 50;

typedef struct CountryTvWatch_struct {
   char countryName[50];
   int tvMinutes;
} CountryTvWatch;

void PrintCountryNames(CountryTvWatch ctryList[], int numCountries)
{
   int i;
   for(i = 0; i < numCountries; i++)
   {
   printf("%s\n", ctryList[numCountries].countryName);
   }
   return;
}

int main(void) {
   // Source: www.statista.com, 2010
   const int NUM_COUNTRIES = 4;

   CountryTvWatch countryList[NUM_COUNTRIES];
   char countryToFind[MAX_COUNTRY_NAME_LENGTH];
   bool countryFound = false;
   int i = 0;

   strcpy(countryList[0].countryName, "Brazil");
   countryList[0].tvMinutes = 222;
   strcpy(countryList[1].countryName, "India");
   countryList[1].tvMinutes = 119;
   strcpy(countryList[2].countryName, "U.K.");
   countryList[2].tvMinutes = 242;
   strcpy(countryList[3].countryName, "U.S.A.");
   countryList[3].tvMinutes = 283;

   printf("Enter country name: \n");
   scanf("%s", countryToFind);

   countryFound = false;
   for (i = 0; i < NUM_COUNTRIES; ++i) { // Find country's index
      if (strcmp(countryList[i].countryName, countryToFind) == 0) {
         countryFound = true;
         printf("People in %s watch\n", countryToFind);
         printf("%d minutes of TV daily.\n", countryList[i].tvMinutes);
      }
   }
   if (!countryFound) {
      printf("Country not found, try again.\n");
      printf("Valid countries:\n");
      PrintCountryNames(countryList, NUM_COUNTRIES);
   }

   return 0;
}

Body:
the following proposed code:

incorporates the comments to the question

properly checks for I/O errors

lets the user know what countries are available to chose from

is appropriately spaced, both horizontally and vertically, for readability

performs the desired functionality

cleanly compiles

documents why each header file is included

and now the proposed code:

#include <stdio.h>     // scanf(), printf()
#include <stdlib.h>    // exit(), EXIT_FAILURE
#include <string.h>    // strcmp()
#include <stdbool.h>   // bool, true, false

#define MAX_COUNTRY_NAME_LENGTH  50
#define NUM_COUNTRIES  4

struct CountryTvWatch_struct
{
    char countryName[ MAX_COUNTRY_NAME_LENGTH ];
    int tvMinutes;
};
typedef struct CountryTvWatch_struct CountryTvWatch;

// prototypes
void PrintCountryNames( CountryTvWatch ctryList[], int numCountries );

int main(void)
{
   // Source: www.statista.com, 2010

   CountryTvWatch countryList[NUM_COUNTRIES];
   char countryToFind[ MAX_COUNTRY_NAME_LENGTH+1];

   strcpy(countryList[0].countryName, "Brazil");
   countryList[0].tvMinutes = 222;

   strcpy(countryList[1].countryName, "India");
   countryList[1].tvMinutes = 119;

   strcpy(countryList[2].countryName, "U.K.");
   countryList[2].tvMinutes = 242;

   strcpy(countryList[3].countryName, "U.S.A.");
   countryList[3].tvMinutes = 283;

   // let user know what countries are available and how they are spelled
   PrintCountryNames(countryList, NUM_COUNTRIES);

   printf("Enter country name: \n");

   // Note: following statement
   //     checks for error
   //     includes a MAX_CHAR modifier that is one less than
   //    the length of the input field
   if( 1 != scanf("%49s", countryToFind) )
   {
       perror( "scanf failed" );
       exit( EXIT_FAILURE );
   }

   // implied else, scanf successful

   bool countryFound = false;

   for ( int i = 0; i < NUM_COUNTRIES; ++i )
   { // Find country's index
      if (strcmp(countryList[i].countryName, countryToFind) == 0)
      {
         countryFound = true;
         printf("People in %s watch\n", countryToFind);
         printf("%d minutes of TV daily.\n", countryList[i].tvMinutes);
         break;  // exit the search loop early
      }
   }

   if (!countryFound)
   {
      printf("Country not found, try again.\n");
      printf("Valid countries:\n");
      PrintCountryNames(countryList, NUM_COUNTRIES);
   }

   return 0;
}

void PrintCountryNames( CountryTvWatch ctryList[], int numCountries )
{
    for( int i = 0; i < numCountries; i++ )
    {
        printf("%s\n", ctryList[ i ].countryName);
    }
}


问:
rspec: can't define singleton Error when trying to mock 1.month-ago
I'm trying to test the following method:

```<code>  def update_players_data(team_id, import_id)
    team = Team.find(team_id)
    players_to_update = team.players.where("updated_at < ?", 1.month.ago)
    players_to_update.each { |player| update_player(player, import_id) }
  end
</code>```

With this test class:

```<code>  context "update_players_data" do
    let(:player1) { double(:player) }
    let(:player2) { double(:player) }
    let(:players) { [player1, player2]}
    let(:players_to_update) { [player1] }
    let(:date) { 1.month.ago }
    let(:import_id) { "import_id" }
    let(:team_id) { "team_id" }
    let(:team) { double(:team) }

    before do
      allow(Team).to receive(:find).with(team_id) { team }
      allow(team).to receive(:players) { players }
      allow(1).to receive_message_chain(:month, :ago) { date }
      allow(players).to receive(:where).with("geocoded_at < ?", date) { players_to_update }
    end

    it "calls update_player" do
      subject.update_players_data(team_id, import_id)
      expect(subject).to have_received(:update_player).with(player1, import_id)
    end
  end
</code>```

But the tests breaks when it tries to mock the date here:

```<code>allow(1).to receive_message_chain(:month, :ago) { date }
</code>```

throwing 'TypeError: can't define singleton '

The problem is I cannot just call 1.month.ago inside the test because test date differs with the date on execution time by miliseconds causing the test to fail. Date has to be mocked. But I cannot find the correct way to do it.

答:
Use something like Timecop.

Additionally

```<code>    players_to_update = team.players.where("updated_at < ?", 1.month.ago)
    players_to_update.each { |player| update_player(player, import_id) }
</code>```

can be

```<code>    team.players.where("updated_at < ?", 1.month.ago).update_all(import_id: import_id)
</code>```

(assuming you're just updating the value inside that function).

Body:
I'm trying to test the following method:

  def update_players_data(team_id, import_id)
    team = Team.find(team_id)
    players_to_update = team.players.where("updated_at < ?", 1.month.ago)
    players_to_update.each { |player| update_player(player, import_id) }
  end

With this test class:

  context "update_players_data" do
    let(:player1) { double(:player) }
    let(:player2) { double(:player) }
    let(:players) { [player1, player2]}
    let(:players_to_update) { [player1] }
    let(:date) { 1.month.ago }
    let(:import_id) { "import_id" }
    let(:team_id) { "team_id" }
    let(:team) { double(:team) }

    before do
      allow(Team).to receive(:find).with(team_id) { team }
      allow(team).to receive(:players) { players }
      allow(1).to receive_message_chain(:month, :ago) { date }
      allow(players).to receive(:where).with("geocoded_at < ?", date) { players_to_update }
    end

    it "calls update_player" do
      subject.update_players_data(team_id, import_id)
      expect(subject).to have_received(:update_player).with(player1, import_id)
    end
  end

But the tests breaks when it tries to mock the date here:

allow(1).to receive_message_chain(:month, :ago) { date }

throwing 'TypeError: can't define singleton '

The problem is I cannot just call 1.month.ago inside the test because test date differs with the date on execution time by miliseconds causing the test to fail. Date has to be mocked. But I cannot find the correct way to do it.

Body:
Use something like Timecop.

Additionally

    players_to_update = team.players.where("updated_at < ?", 1.month.ago)
    players_to_update.each { |player| update_player(player, import_id) }

can be

    team.players.where("updated_at < ?", 1.month.ago).update_all(import_id: import_id)

(assuming you're just updating the value inside that function).