问:
How to read the json string through C# code in runtime?
```<code>{
    "StudentInformation": {
        "rollNumber": null,
        "isClassLeader": false,
        "result": "Pass"

    },

    "CollegeInformation": {
        "allClass": ["A", "B"],
        "currencyAccepted": "INR",
        "calendarDates": [],
        "currencyCode": "INR",
        "collegeCode": null,
        "hasBulidingFundPrices": false,
        "hasHostel": false,
        "hasSecurityFares": false

    },

    "Collegetrips": [{
        "tripsdate": [{
                "departureTripDate": "2017-08-15 00:00:00",
                    "Places": [{
                            "destination": "Bombay",
                            "price": [{
                                "priceAmount": 1726
                                    }]
                                }]
                        }]
             }]
}
</code>```

In the above json file i need to retrieve only "priceAmount": 1726. Please anyone suggest how can able to achieve?

答:
You can use System.Web.Script.Serialization (you need to add a reference to System.Web.Extensions):

```<code>dynamic json = new JavaScriptSerializer()
    .DeserializeObject(jsonString);

decimal price = json["Collegetrips"][0]
    ["tripsdate"][0]
    ["Places"][0]
    ["price"][0]
    ["priceAmount"]; // 1726
</code>```

Note that you can pretty much traverse the json in this manner using indexes and key names.

Body:
{
    "StudentInformation": {
        "rollNumber": null,
        "isClassLeader": false,
        "result": "Pass"

    },

    "CollegeInformation": {
        "allClass": ["A", "B"],
        "currencyAccepted": "INR",
        "calendarDates": [],
        "currencyCode": "INR",
        "collegeCode": null,
        "hasBulidingFundPrices": false,
        "hasHostel": false,
        "hasSecurityFares": false

    },

    "Collegetrips": [{
        "tripsdate": [{
                "departureTripDate": "2017-08-15 00:00:00",
                    "Places": [{
                            "destination": "Bombay",
                            "price": [{
                                "priceAmount": 1726
                                    }]
                                }]
                        }]
             }]
}

In the above json file i need to retrieve only "priceAmount": 1726. Please anyone suggest how can able to achieve?

Body:
You can use System.Web.Script.Serialization (you need to add a reference to System.Web.Extensions):

dynamic json = new JavaScriptSerializer()
    .DeserializeObject(jsonString);

decimal price = json["Collegetrips"][0]
    ["tripsdate"][0]
    ["Places"][0]
    ["price"][0]
    ["priceAmount"]; // 1726

Note that you can pretty much traverse the json in this manner using indexes and key names.


来源: stackexchange

问:
jquery each div add remove class infinity
want to create infinity loop that adds class to each div with some timeout

for know have like this:

$(document).ready(function() {
  $('.small-bordered-box').each(function(i) {
    var $t = $(this);
    setTimeout(function() {
      $t.addClass('active');
    }, 2000 * i);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.small-bordered-box {
  display: block;
  height: 118px;
  width: 100px;
  border: 2px solid #3e3b38;
  border-radius: 5px;
  float: left;
  margin-right: 35px;
}

.small-bordered-box.active {
  animation: shake 0.83s cubic-bezier(.36, .07, .19, .97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}</code>```

  test1

  test2

  test3

```

want to keep effect like this, just that it would go infiny time..
that users would always sees this effect no matter what or where they are on the page..

答:
You can use setInterval to shake it with an interval of element's-length*Timeouts-interval i.e. 3*2000 like,

$(document).ready(function() {
  function shakeIt() {
    $('.small-bordered-box').each(function(i) {
      var $t = $(this);
      setTimeout(function() {
        $t.addClass('active');
      }, 2000 * i);
    });
  }
  shakeIt();
  setInterval(function() {
    shakeIt();
    $('.small-bordered-box').removeClass('active');
  }, $('.small-bordered-box').length*2000);

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.small-bordered-box {
  display: block;
  height: 118px;
  width: 100px;
  border: 2px solid #3e3b38;
  border-radius: 5px;
  float: left;
  margin-right: 35px;
}

.small-bordered-box.active {
  animation: shake 0.83s cubic-bezier(.36, .07, .19, .97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}</code>```

  test1

  test2

  test3

```

ContentLicense: CC BY-SA 3.0

Body:
want to create infinity loop that adds class to each div with some timeout

for know have like this:

$(document).ready(function() {
  $('.small-bordered-box').each(function(i) {
    var $t = $(this);
    setTimeout(function() {
      $t.addClass('active');
    }, 2000 * i);
  });
});

.small-bordered-box {
  display: block;
  height: 118px;
  width: 100px;
  border: 2px solid #3e3b38;
  border-radius: 5px;
  float: left;
  margin-right: 35px;
}

.small-bordered-box.active {
  animation: shake 0.83s cubic-bezier(.36, .07, .19, .97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}

  test1

  test2

  test3

want to keep effect like this, just that it would go infiny time..
that users would always sees this effect no matter what or where they are on the page..

Body:
You can use setInterval to shake it with an interval of element's-length*Timeouts-interval i.e. 3*2000 like,

$(document).ready(function() {
  function shakeIt() {
    $('.small-bordered-box').each(function(i) {
      var $t = $(this);
      setTimeout(function() {
        $t.addClass('active');
      }, 2000 * i);
    });
  }
  shakeIt();
  setInterval(function() {
    shakeIt();
    $('.small-bordered-box').removeClass('active');
  }, $('.small-bordered-box').length*2000);

});

.small-bordered-box {
  display: block;
  height: 118px;
  width: 100px;
  border: 2px solid #3e3b38;
  border-radius: 5px;
  float: left;
  margin-right: 35px;
}

.small-bordered-box.active {
  animation: shake 0.83s cubic-bezier(.36, .07, .19, .97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="small-bordered-box ">
  <a href="#">test1</a>
</div>
<div class="small-bordered-box ">
  <a href="#">test2</a>
</div>
<div class="small-bordered-box ">
  <a href="#">test3</a>
</div>


问:
How to give custom size to PdfSharp generated Pdf
I was trying to generate a pdf from HTML which containing a table using PdfSharp and HTMLRenderer. The following shows the code.

```<code>            pdf = PdfGenerator.GeneratePdf(html, PageSize.A3);

            byte[] fileContents = null;
            using (MemoryStream stream = new MemoryStream())
            {
                pdf.Save(stream, true);
                fileContents = stream.ToArray();
                return new FileStreamResult(new MemoryStream(fileContents.ToArray()), "application/pdf");
            }
</code>```

Is there any possibility for me to provide a custom size to the PDF and change the orientation of the page. I am using a memory stream to show the PDF directly on the browser display.

答:
You can use the PdfGenerateConfig parameter of the GeneratePdf method to specify a custom page size using the ManualPageSize property.

Use the PageOrientation to get standard page sizes in landscape.

Code from comment:

```<code>var config = new PdfGenerateConfig();
config.PageOrientation = PageOrientation.Landscape;
config.ManualPageSize = new PdfSharp.Drawing.XSize(1080, 828);

pdf = PdfGenerator.GeneratePdf(html, config);
</code>```

Body:
I was trying to generate a pdf from HTML which containing a table using PdfSharp and HTMLRenderer. The following shows the code.

            pdf = PdfGenerator.GeneratePdf(html, PageSize.A3);

            byte[] fileContents = null;
            using (MemoryStream stream = new MemoryStream())
            {
                pdf.Save(stream, true);
                fileContents = stream.ToArray();
                return new FileStreamResult(new MemoryStream(fileContents.ToArray()), "application/pdf");
            }

Is there any possibility for me to provide a custom size to the PDF and change the orientation of the page. I am using a memory stream to show the PDF directly on the browser display.

Body:
You can use the PdfGenerateConfig parameter of the GeneratePdf method to specify a custom page size using the ManualPageSize property.

Use the PageOrientation to get standard page sizes in landscape.

Code from comment:

var config = new PdfGenerateConfig();
config.PageOrientation = PageOrientation.Landscape;
config.ManualPageSize = new PdfSharp.Drawing.XSize(1080, 828);

pdf = PdfGenerator.GeneratePdf(html, config);

ContentLicense: CC BY-SA 4.0


问:
Pass the browser to next test
I'm trying out Arquillian Drone and Graphene this time with Groovy and I have the following 2 tests what i want to do is have the second test use the browser from the first tests. but the browser closes after the first test finishes - is there a way to pass the browser to the second test?</p>

```<code>@RunWith(ArquillianSputnik)
@RunAsClient
@Stepwise
class testclass extends Specification {

@Drone
private WebDriver browser;

@Page
SubPage subPage

@ArquillianResource
URL url

def 'It should navigate to subscription page'() {
    when: 'I go to  subscription page'
    browser.get('http://localhost:8585/');

    then: 'It should should enter sub name'
    subPage.enterName("Name")
}

def "Enter subdescription"() {
    when: "I enter a sub description"

    sub.enterDescription('Description')

    then: "Subscription description should be visible in description input field"

}
</code>```

答:
second test will look like </p>

```<code> def "Enter subdescription"() {
     when: "I enter a sub description"
     browser.getCurrentUrl()
     sub.enterDescription('Description')

     then: "Subscription description should be visible in description input field"

}
</code>```

Title: Pass the browser to next test

Body:
I'm trying out Arquillian Drone and Graphene this time with Groovy and I have the following 2 tests what i want to do is have the second test use the browser from the first tests. but the browser closes after the first test finishes - is there a way to pass the browser to the second test?

@RunWith(ArquillianSputnik)
@RunAsClient
@Stepwise
class testclass extends Specification {

@Drone
private WebDriver browser;

@Page
SubPage subPage

@ArquillianResource
URL url

def 'It should navigate to subscription page'() {
    when: 'I go to  subscription page'
    browser.get('http://localhost:8585/');

    then: 'It should should enter sub name'
    subPage.enterName("Name")
}

def "Enter subdescription"() {
    when: "I enter a sub description"

    sub.enterDescription('Description')

    then: "Subscription description should be visible in description input field"

}

Body:
second test will look like

 def "Enter subdescription"() {
     when: "I enter a sub description"
     browser.getCurrentUrl()
     sub.enterDescription('Description')

     then: "Subscription description should be visible in description input field"

}


问:
How to prevent Soft Keyboard hiding button in custom dialog?
I have a custom dialog like following

When soft keyboard comes it hides the Button like below.

my code

https://mcaf.ee/9qhnef

How to avoid Submit button being hide?  i have added autoresize and auto pan but no luck so far.

答:
I also had the same issue once when I had to implement a feedback dialog with height matching almost the screen height. You need to add ScrollView to the parent layout of your view in xml file eg.

```<code><ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    //your content View goes here

  </ScroolView>
</code>```

and then after inflating the view in fragment,
try this on your onCreateView:

```<code> getDialog().getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
</code>```

The SOFT_INPUT_ADJUST_RESIZE does the trick as it does in case of activities when defined in the manifest file . Hope this helps.

Body:
I also had the same issue once when I had to implement a feedback dialog with height matching almost the screen height. You need to add ScrollView to the parent layout of your view in xml file eg.

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    //your content View goes here

  </ScroolView>

and then after inflating the view in fragment,
try this on your onCreateView:

 getDialog().getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

The SOFT_INPUT_ADJUST_RESIZE does the trick as it does in case of activities when defined in the manifest file . Hope this helps.


问:
Get post ID in variable in Grid Builder Visual Composer
I’m trying to get some custom fields inside my custom grid builder. I have added some extra taxonomy and would like to add custom data to display. I’ve read your article here: https://kb.wpbakery.com/docs/developers-how-tos/adding-custom-shortcode-to-grid-builder/ and when implementing it, I’m getting a problem when trying to get the id of the current post ID. I know the code is as follows:

```<code>add_shortcode( 'vc_post_id', 'vc_post_id_render' );
function vc_post_id_render() {
   return '<h2>{{ post_data:ID }}</h2>'; // usage of template variable post_data with argument "ID"
}
</code>```

The thing is that the {{ post_data:ID }} cannot be saved to a variable to later get the post and play with it as such:

```<code>$post_id = '{{ post_data:ID }}';
$post = get_post($post_id);
</code>```

as it will fail. Could you please tell me how to get the current post ID as a variable so I can show custom data on the grid?

Thank you very much.

答:
Ok, here what I'm thinking. In my scenario, I have a custom field called price.
So I was able to show the price by using

```<code>{{ post_data:price }}
</code>```

This. But when I was trying to assign it to a variable, it failed. When I var_dump the variable it gives me (21) characters for every time. So I thought there must be invisible characters. so I

```<code>echo bin2hex($price)
</code>```

The result was 7b7b20706f73745f646174613a7072696365207d7d

And after ASCII to text conversion, it became this

```<code>{{ post_data:price }}
</code>```

Then I realized it. Oh silly me. These are template tags. Like in smarty or angular. They injected values once the page has loaded. So PHP doesn't have a chance get value because everything happening on the client side.

Body:
I’m trying to get some custom fields inside my custom grid builder. I have added some extra taxonomy and would like to add custom data to display. I’ve read your article here: https://kb.wpbakery.com/docs/developers-how-tos/adding-custom-shortcode-to-grid-builder/ and when implementing it, I’m getting a problem when trying to get the id of the current post ID. I know the code is as follows:

add_shortcode( 'vc_post_id', 'vc_post_id_render' );
function vc_post_id_render() {
   return '
{{ post_data:ID }}
'; // usage of template variable post_data with argument "ID"
}

The thing is that the {{ post_data:ID }} cannot be saved to a variable to later get the post and play with it as such:

$post_id = '{{ post_data:ID }}';
$post = get_post($post_id);

as it will fail. Could you please tell me how to get the current post ID as a variable so I can show custom data on the grid?

Thank you very much.

Body:
Ok, here what I'm thinking. In my scenario, I have a custom field called price.
So I was able to show the price by using

{{ post_data:price }}

This. But when I was trying to assign it to a variable, it failed. When I var_dump the variable it gives me (21) characters for every time. So I thought there must be invisible characters. so I

echo bin2hex($price)

The result was 7b7b20706f73745f646174613a7072696365207d7d

And after ASCII to text conversion, it became this

{{ post_data:price }}

Then I realized it. Oh silly me. These are template tags. Like in smarty or angular. They injected values once the page has loaded. So PHP doesn't have a chance get value because everything happening on the client side.


问:
How to view tables used in hbase database?
I am new to hbase. There are 30 tables created in hbase. I want to view those table structures.

I have used the below command to view the tables but there is only one table. Hope I need to connect to right database inside hbase to list the tables.

```<code>hbase(main):017:0> list
TABLE
test
1 row(s) in 0.0140 seconds
</code>```

Now I wanted the command to know what are the databases present(already created) in hbase?

答:
To be align with HBase terminology... There is a concept of 'namespace'.
You can create tables under particular namespaces.

```<code>Group name: namespace
  Commands: alter_namespace, create_namespace, describe_namespace, drop_namespace, list_namespace, list_namespace_tables
</code>```

list - display tables in default namespace

list_namespace - shows all available namespace

list_namespace_tables 'n1' shows all tables under n1 namespace.

Most likely all your tables were created under some specific namespace. Explore..

Body:
I am new to hbase. There are 30 tables created in hbase. I want to view those table structures.

I have used the below command to view the tables but there is only one table. Hope I need to connect to right database inside hbase to list the tables.

hbase(main):017:0> list
TABLE
test
1 row(s) in 0.0140 seconds

Now I wanted the command to know what are the databases present(already created) in hbase?

Body:
To be align with HBase terminology... There is a concept of 'namespace'.
You can create tables under particular namespaces.

Group name: namespace
  Commands: alter_namespace, create_namespace, describe_namespace, drop_namespace, list_namespace, list_namespace_tables

list - display tables in default namespace

list_namespace - shows all available namespace

list_namespace_tables 'n1' shows all tables under n1 namespace.

Most likely all your tables were created under some specific namespace. Explore..


问:
Color in link tag doesn't work but color in div in link tag works?
Why doesn't this work (in terms of text color):

```<code>.navbarDivText {
    color: #DAA520;
}
.navbarDiv {
    width: 150px;
    background-color: inherit;
    margin-left: 10px;
}

<li class="navbarDiv" >
   <a href="index.php" class = "navbarDivText">Main Page</a>
</li>
</code>```

But this does:

```<code><li class="navbarDiv" >
   <a href="index.php">
     <div class = "navbarDivText">Main Page</div>
   </a>
 </li>
</code>```

答:
Bootstrap is probably overriding this...

You'll need to be more specific e.g.

```<code>a.navbarDivText {
  color: #DAA520;
}
</code>```

You may have to use:

```<code>a.navbarDivText {
  color: #DAA520!important;
}
</code>```

If for some reason that doesn't work...

Body:
Why doesn't this work (in terms of text color):

.navbarDivText {
    color: #DAA520;
}
.navbarDiv {
    width: 150px;
    background-color: inherit;
    margin-left: 10px;
}

   Main Page

But this does:

Main Page

Body:
Bootstrap is probably overriding this...

You'll need to be more specific e.g.

a.navbarDivText {
  color: #DAA520;
}

You may have to use:

a.navbarDivText {
  color: #DAA520!important;
}

If for some reason that doesn't work...


问:
Server Error in '/' Application. The resource cannot be found. (ASP.NET mvc 2 + built in web server)
I'm trying to make a MVC 2 web application for a small portal.
I started with the template in VS 2010 and made several other .aspx pages (for views)
Index.aspx (was a part of the template) opens like he should open, but when I click on a link to acces another aspx page (that I added to the template) he show me this:

Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Views/AccountPages/Aanvragen.aspx

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1

When I set Aanvragen.aspx as startup page, he show me the same message.
I use a built in server (VS2010).
Of course, I checked if the url is correct and it is. So that is certaintly not the problem

Anyone that could help me ?

Thanks a lot

答:
You should not be requesting view pages directly at all; the web.config that comes with ASP.NET MVC blocks direct requests for all views in the /views directory, for one thing.

You can link to regular web forms pages elsewhere in your site, such as in the root directory, but that's really not how MVC is meant to be used. You may want to seek out a tutorial on ASP.NET MVC, as it seems you aren't familiar with how to use it. Check out the http://www.asp.net/mvc web site.

ContentLicense: CC BY-SA 2.5


问:
How to ajax call a php file hosted on remote server and receive a response?
We are trying to call from index.html on local, a simple PHP file hosted on webhost000 to receive a response. PHP file is:

```<code><?php
if (isset($_POST['name'])) {
    $name = $_POST['name'];
    echo ($name);
}
?>
</code>```

We would like to simply input a character on a textbox in html.index and receive the same character as response from the php. We are using an ajax call to do this in html file:

```<code><script>
    $(document).ready(function() {
        $('#name').keyup(function() {
        var name = $('#name').val();
        var request = $.ajax({
              url: "https://nedo93.000webhostapp.com/phpdemo.php",
              method: "POST",
              data: { name : name },
              dataType: "html"
            });

            request.done(function( msg ) {
              alert( "Request done: " + msg );
            });

            request.fail(function( jqXHR, textStatus ) {
              alert( "Request failed: " + textStatus );
            });
        });
    });
    </script>
</code>```

(The remaining html should not be important, it works perfectly, tested and retested)

If we try to debug this we can see that the file is found, the request is sent, but we can't receive a response: screenshot

If we use this browser function instead, we can send data and receive a response without a problem, don't know if this can help.

Thank you in advance if you can answer this question.

答:
This is because your PHP script is hosted on a different server and your AJAX call code is on local.

For AJAX to run, there is same-origin policy. Under this policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin (means both are on same domain). Read more about same origin policy here.

The same-origin policy prevents some Ajax techniques from being used across domains, although the W3C has a draft of the XMLHttpRequest object that would enable this functionality. Methods exist to sidestep this security feature by using a special Cross Domain Communications channel embedded as an iframe within a page, or by the use of JSONP, websockets, cross-domain messaging  or  cross-domain resource sharing.

So in short you will not be able to access the PHP request residing on a 000webhost server to be accessed using AJAX code on local.

Either you host the AJAX code on the same 000webhost domain as well or enable cross-domain resource sharing on 000webhost domain where your PHP code is running.

As far I know, 000webhost is a free server and doesn't supports these changes. So you will have to either get a better server or test this all in a local.

Also as you mentioned in your query, all HTTP requests like GET, POST, PUT works cross domain. But for AJAX, no its not so straight forward.

Hope this helps!

Body:
We are trying to call from index.html on local, a simple PHP file hosted on webhost000 to receive a response. PHP file is:

<?php
if (isset($_POST['name'])) {
    $name = $_POST['name'];
    echo ($name);
}
?>

We would like to simply input a character on a textbox in html.index and receive the same character as response from the php. We are using an ajax call to do this in html file:

(The remaining html should not be important, it works perfectly, tested and retested)

If we try to debug this we can see that the file is found, the request is sent, but we can't receive a response: screenshot

If we use this browser function instead, we can send data and receive a response without a problem, don't know if this can help.

Thank you in advance if you can answer this question.


问:
Custom layout is not showing in a android app?
I have a created custom layout but it is not working. When I use include the layout instead of set com.samsung.android.app.spage.CustomView.WeatherStateView it is working ok. I found some answers like use the <merge> tag but it not working too, please help me:

weather_state_layout.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/weather_state_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:id="@+id/current_location"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="current location" />

<include layout="@layout/detail_info_frag_hourly_content" /></LinearLayout>
</code>```

WeatherStateView.java

```<code>public class WeatherStateView extends LinearLayout implements View.OnClickListener{
    private static final String TAG = "WeatherStateView";
    private TextView mCurrentLocation;
    private Context mContext;

    public WeatherStateView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public WeatherStateView(Context context) {
        super(context);
    }

    public WeatherStateView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context);
    }

    private void initialize(Context context) {
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.weather_state_layout, this);

        mCurrentLocation = (TextView) findViewById(R.id.current_location);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int w = MeasureSpec.getSize(widthMeasureSpec);
        int h = MeasureSpec.getSize(heightMeasureSpec);

        int size = Math.min(w, h);
        setMeasuredDimension(size, size);
    }
}
</code>```

in main_layout.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WeatherModule.WeatherViewStateFragment">

    <CustomView.WeatherStateView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/weather_state_main_layout"
        android:orientation="vertical"
    />
</code>```

答:
Problem here is

```<code> LayoutInflater.from(context).inflate(R.layout.weather_state_layout, this);
</code>```

Should change to ;

```<code>ViewGroup viewGroup = (ViewGroup) inflate(mContext , R.layout.weather_state_layout, null); addView(viewGroup);
</code>```

Body:
I have a created custom layout but it is not working. When I use include the layout instead of set com.samsung.android.app.spage.CustomView.WeatherStateView it is working ok. I found some answers like use the <merge> tag but it not working too, please help me:

weather_state_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/weather_state_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:id="@+id/current_location"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="current location" />

<include layout="@layout/detail_info_frag_hourly_content" /></LinearLayout>

WeatherStateView.java

public class WeatherStateView extends LinearLayout implements View.OnClickListener{
    private static final String TAG = "WeatherStateView";
    private TextView mCurrentLocation;
    private Context mContext;

    public WeatherStateView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public WeatherStateView(Context context) {
        super(context);
    }

    public WeatherStateView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context);
    }

    private void initialize(Context context) {
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.weather_state_layout, this);

        mCurrentLocation = (TextView) findViewById(R.id.current_location);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int w = MeasureSpec.getSize(widthMeasureSpec);
        int h = MeasureSpec.getSize(heightMeasureSpec);

        int size = Math.min(w, h);
        setMeasuredDimension(size, size);
    }
}

in main_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WeatherModule.WeatherViewStateFragment">

    <CustomView.WeatherStateView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/weather_state_main_layout"
        android:orientation="vertical"
    />

Body:
Problem here is

 LayoutInflater.from(context).inflate(R.layout.weather_state_layout, this);

Should change to ;

ViewGroup viewGroup = (ViewGroup) inflate(mContext , R.layout.weather_state_layout, null); addView(viewGroup);


答:
On a side note you should only put a div inside an a tag if you are using the HTML5 doctype, which I imagine you are.

When a link is clicked the browser will give it a color to show it has been visited. So you could try the below :visited selector. If that doesn't work then it is likely that another style is overriding your style. As mentioned in the comments, inspect the element in the developer console and see if your style is being overridden.

```<code>.navbarDivText:link, .navbarDivText:visited
{
   color: #DAA520;
}
</code>```

Title: Color in link tag doesn't work but color in div in link tag works?

Body:
On a side note you should only put a div inside an a tag if you are using the HTML5 doctype, which I imagine you are.

When a link is clicked the browser will give it a color to show it has been visited. So you could try the below :visited selector. If that doesn't work then it is likely that another style is overriding your style. As mentioned in the comments, inspect the element in the developer console and see if your style is being overridden.

.navbarDivText:link, .navbarDivText:visited
{
   color: #DAA520;
}


问:
my code get stuck in infinte loop after pressing yes button in dialog builder in function onRequestPermissionsResult
my code get stuck in infinte loop after pressing yes button in dialog builder in function onRequestPermissionsResult .Again and again builder came out when i press yes.Also after pressing no ,my app exit but when i open it again it shows the dialog builder

```<code>@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull final int[] grantResults) {

        switch (requestCode) {
            case 0: {
                boolean anyPermissionDenied = false;
                boolean neverAskAgainSelected = false;
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        anyPermissionDenied = true;
                    }
                }
                if (!anyPermissionDenied)
                {
                    getConfigFromServer();
                } else {
                    String message = "";
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) ||
                            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))  {

                        requestPermission();
                    }
                    else
                    {
                        message = "You have to give all permission to continue";
                    }
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                    alertDialogBuilder.setMessage(message);
                            alertDialogBuilder.setPositiveButton("yes",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface arg0, int arg1) {
                                        requestPermission();

                                        }
                                    });

                    alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });

                    AlertDialog alertDialog = alertDialogBuilder.create();
                    alertDialog.show();
                }
            }
            break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

    }
</code>```

code for request permission

```<code>    void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA,
                    Manifest.permission.ACCESS_FINE_LOCATION}, 0);
        } else {

            getConfigFromServer();
            //navigateToNextActivity();
        }
    }
</code>```

答: it popup again after clicking no because  you havent set any thing so in onRequestPermissionsResult ,your if-condition anyPermissionDenied happen , but for alertDialogBuilder.setPositiveButton("yes",new DialogInterface.OnClickListener()  i think its better if you post your requestPermission mehtod or atleast you should debug it to see whats happening

Body:
my code get stuck in infinte loop after pressing yes button in dialog builder in function onRequestPermissionsResult .Again and again builder came out when i press yes.Also after pressing no ,my app exit but when i open it again it shows the dialog builder

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull final int[] grantResults) {

        switch (requestCode) {
            case 0: {
                boolean anyPermissionDenied = false;
                boolean neverAskAgainSelected = false;
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        anyPermissionDenied = true;
                    }
                }
                if (!anyPermissionDenied)
                {
                    getConfigFromServer();
                } else {
                    String message = "";
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) ||
                            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))  {

                        requestPermission();
                    }
                    else
                    {
                        message = "You have to give all permission to continue";
                    }
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                    alertDialogBuilder.setMessage(message);
                            alertDialogBuilder.setPositiveButton("yes",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface arg0, int arg1) {
                                        requestPermission();

                                        }
                                    });

                    alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });

                    AlertDialog alertDialog = alertDialogBuilder.create();
                    alertDialog.show();
                }
            }
            break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

    }

code for request permission

    void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA,
                    Manifest.permission.ACCESS_FINE_LOCATION}, 0);
        } else {

            getConfigFromServer();
            //navigateToNextActivity();
        }
    }


问:
How do you count the elements of an array in java
Say i have the array

```<code>int theArray = new int[20];
</code>```

The length of the array is 20 but the count is 0. How can i get the count?

答:
When defining an array, you are setting aside a block of memory to hold all the items you want to have in the array.

This will have a default value, depending on the type of the array member types.

What you can't do is find out the number of items that you have populated, except for tracking it in your own code.

Body:
Say i have the array

int theArray = new int[20];

The length of the array is 20 but the count is 0. How can i get the count?


问:
Control the Sql that Linq sends to db explanation
Hello I have the a linq query that I have created for a left outer join. I am wondering why linq creates the Sql it does, and how to make it a better query.

here's the c# query:

```<code>var query=
(
    from subject in subjects
    join statement in statements.DefaultIfEmpty() on subject.Id equals statement.SubjectId
    select subject
);
query.Take(100).Dump();
</code>```

and the Sql that it sends:

```<code>SELECT TOP (100)
--some fields here
FROM [Subject] AS [t0]
INNER JOIN ((
        SELECT NULL AS [EMPTY]
        ) AS [t1]
    LEFT OUTER JOIN [SubjectStatement] AS [t2] ON 1=1 ) ON [t0].[id] = [t2].[SubjectId]
</code>```

What I would like to see sent is

```<code>SELECT TOP(100)
   --some fields here
FROM Subject
LEFT OUTER JOIN SubjectStatemnt ON Subject.Id = SubjectStatement.Id
</code>```

Is there a way to control the Sql that is being passed to Sql Server?

答:
You are using the syntax of an inner join and while that might work out some times, you would normally create a left join using the following syntax:

```<code>var query =
(
    from subject in subjects
    join statement in statements on subject.Id equals statement.SubjectId into ljStatement
    from statement in ljStatement.DefaultIfEmpty()
    select subject
);
query.Take(100).Dump();
</code>```

This would result in:

```<code>SELECT TOP (100) [t0].[Id]
FROM [Subject] AS [t0]
LEFT OUTER JOIN [SubjectStatement] AS [t1] ON [t0].[Id] = [t1].[SubjectId]
</code>```

into (C# Reference)

The into contextual keyword can be used to create a temporary
  identifier to store the results of a group, join or select clause into
  a new identifier.

join clause (C# Reference)

A join clause with an into expression is called a group join.

...

A group join produces a hierarchical result sequence, which associates elements in the left source sequence with one or more matching elements in the right side source sequence. A group join has no equivalent in relational terms; it is essentially a sequence of object arrays.
  If no elements from the right source sequence are found to match an element in the left source, the join clause will produce an empty array for that item. Therefore, the group join is still basically an inner-equijoin except that the result sequence is organized into groups.

Body:
Hello I have the a linq query that I have created for a left outer join. I am wondering why linq creates the Sql it does, and how to make it a better query.

here's the c# query:

var query=
(
    from subject in subjects
    join statement in statements.DefaultIfEmpty() on subject.Id equals statement.SubjectId
    select subject
);
query.Take(100).Dump();

and the Sql that it sends:

SELECT TOP (100)
--some fields here
FROM [Subject] AS [t0]
INNER JOIN ((
        SELECT NULL AS [EMPTY]
        ) AS [t1]
    LEFT OUTER JOIN [SubjectStatement] AS [t2] ON 1=1 ) ON [t0].[id] = [t2].[SubjectId]

What I would like to see sent is

SELECT TOP(100)
   --some fields here
FROM Subject
LEFT OUTER JOIN SubjectStatemnt ON Subject.Id = SubjectStatement.Id

Is there a way to control the Sql that is being passed to Sql Server?

Body:
You are using the syntax of an inner join and while that might work out some times, you would normally create a left join using the following syntax:

var query =
(
    from subject in subjects
    join statement in statements on subject.Id equals statement.SubjectId into ljStatement
    from statement in ljStatement.DefaultIfEmpty()
    select subject
);
query.Take(100).Dump();

This would result in:

SELECT TOP (100) [t0].[Id]
FROM [Subject] AS [t0]
LEFT OUTER JOIN [SubjectStatement] AS [t1] ON [t0].[Id] = [t1].[SubjectId]

into (C# Reference)

The into contextual keyword can be used to create a temporary
  identifier to store the results of a group, join or select clause into
  a new identifier.

join clause (C# Reference)

A join clause with an into expression is called a group join.

...

A group join produces a hierarchical result sequence, which associates elements in the left source sequence with one or more matching elements in the right side source sequence. A group join has no equivalent in relational terms; it is essentially a sequence of object arrays.
  If no elements from the right source sequence are found to match an element in the left source, the join clause will produce an empty array for that item. Therefore, the group join is still basically an inner-equijoin except that the result sequence is organized into groups.


问:
Building 64 bit Python extension on Windows tuple : undeclared identifier
I work on 64 bit windows with 64 bit python 2.7 and i am trying to compile my first c++ extension for python.
At first i tried to use mingw but ran into many linker errors, so now i use c++ for python 2.7 with the windows7 SDK.

It should be an object storing two times a c++ map, map<tuple<int,int,int>,pen> and map<int,pen>, where pen is a c++ struct.

The header of the class (Tactic.h):

```<code>#include <iostream>
#include <string>
#include <string.h>
#include <sstream>
#include <map>
#ifndef TACTIC
#define TACTIC
#include <tuple>
#include <vector>
using namespace std;
struct pen
{
public:
    pen():p0(-15),p1(-15),p2(-15),p3(-15),
        p4(-15),p5(-15),p6(-15),
        p7(-15),p8(-15),p9(0){}
    signed int p0:11;
    signed int p1:11;
    signed int p2:11;
    signed int p3:11;
    signed int p4:11;
    signed int p5:11;
    signed int p6:11;
    signed int p7:11;
    signed int p8:11;
    signed int p9:4;
};
class Tactic
{
    public:
        Tactic();
        Tactic(vector<vector<int>> &map1, vector<vector<int>> &map2);
        ~Tactic();
        void adjust_map1(int k0, int k1,int k2,const char *act, int modifier);
        void adjust_map2(int key,const char *act, int modifier);
        vector<int> get_map1(int key);
        vector<int> get_map2(int k0, int k1,int k2);
        vector< vector < vector<int> > > get_list();
        void load_dict(vector< vector < vector<int> > > dict_list);
    private:
        map<int,pen> *map1;
        map<tuple<int,int,int>,pen> *map2;
};
#endif
</code>```

the setup.py:

import os

```<code>from setuptools import setup
from setuptools import Extension
from Cython.Build import cythonize

ext_modules=[
    Extension("tactic",
        extra_compile_args=["/EHsc"],
        sources = ["tactic.pyx","Tact_source.cpp"],
        language = "c++",)]
setup(
    name="tactic",
    ext_modules = cythonize(ext_modules),)
</code>```

The command python setup.py build_ext --inplace -compiler=msvc fails with following error:

```<code>D:\...>python setup.py build_ext --inplace -compiler=msvc
running build_ext
building 'tactic' extension
C:\Users\....\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Python27\include -IC:\Python27\PC /Tptactic.cpp /Fobuild\temp.win-amd64-2.7\Release\tactic.obj /EHsc
tactic.cpp
d:\...\Tactic.h(44) : error C2065: 'tuple' : undeclared identifier
d:\...\Tactic.h(44) : error C2062: type 'int' unexpected
d:\...\Tactic.h(44) : error C2059: syntax error : ','
d:\...\Tactic.h(44) : error C2238: unexpected token(s) preceding ';'
error: command '"C:\Users\....\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe"' failed with exit status 2
</code>```

So, it seems that although i imported tuple, the compiler cannot find a declaration of tuple.
Does anyone have an idea what the matter could be?
Is this maybe not a compiler but a linker error?
Thank you in advance for any help.

答:
Visual studio 2008 C++ compiler being outdated does not have tuple in std namespace but in std::tr1, so replacing instances of std::tuple with std::tr1::tuple should work.

This is also documented in msdn docs

Body:
I work on 64 bit windows with 64 bit python 2.7 and i am trying to compile my first c++ extension for python.
At first i tried to use mingw but ran into many linker errors, so now i use c++ for python 2.7 with the windows7 SDK.

It should be an object storing two times a c++ map, map<tuple<int,int,int>,pen> and map<int,pen>, where pen is a c++ struct.

The header of the class (Tactic.h):

#include <iostream>
#include <string>
#include <string.h>
#include <sstream>
#include <map>
#ifndef TACTIC
#define TACTIC
#include <tuple>
#include <vector>
using namespace std;
struct pen
{
public:
    pen():p0(-15),p1(-15),p2(-15),p3(-15),
        p4(-15),p5(-15),p6(-15),
        p7(-15),p8(-15),p9(0){}
    signed int p0:11;
    signed int p1:11;
    signed int p2:11;
    signed int p3:11;
    signed int p4:11;
    signed int p5:11;
    signed int p6:11;
    signed int p7:11;
    signed int p8:11;
    signed int p9:4;
};
class Tactic
{
    public:
        Tactic();
        Tactic(vector<vector<int>> &map1, vector<vector<int>> &map2);
        ~Tactic();
        void adjust_map1(int k0, int k1,int k2,const char *act, int modifier);
        void adjust_map2(int key,const char *act, int modifier);
        vector<int> get_map1(int key);
        vector<int> get_map2(int k0, int k1,int k2);
        vector< vector < vector<int> > > get_list();
        void load_dict(vector< vector < vector<int> > > dict_list);
    private:
        map<int,pen> *map1;
        map<tuple<int,int,int>,pen> *map2;
};
#endif

the setup.py:

import os

from setuptools import setup
from setuptools import Extension
from Cython.Build import cythonize

ext_modules=[
    Extension("tactic",
        extra_compile_args=["/EHsc"],
        sources = ["tactic.pyx","Tact_source.cpp"],
        language = "c++",)]
setup(
    name="tactic",
    ext_modules = cythonize(ext_modules),)

The command python setup.py build_ext --inplace -compiler=msvc fails with following error:

D:\...>python setup.py build_ext --inplace -compiler=msvc
running build_ext
building 'tactic' extension
C:\Users\....\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Python27\include -IC:\Python27\PC /Tptactic.cpp /Fobuild\temp.win-amd64-2.7\Release\tactic.obj /EHsc
tactic.cpp
d:\...\Tactic.h(44) : error C2065: 'tuple' : undeclared identifier
d:\...\Tactic.h(44) : error C2062: type 'int' unexpected
d:\...\Tactic.h(44) : error C2059: syntax error : ','
d:\...\Tactic.h(44) : error C2238: unexpected token(s) preceding ';'
error: command '"C:\Users\....\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe"' failed with exit status 2

So, it seems that although i imported tuple, the compiler cannot find a declaration of tuple.
Does anyone have an idea what the matter could be?
Is this maybe not a compiler but a linker error?
Thank you in advance for any help.


问:
How to expand the last column of table to the rest of width?
Here is my code:

.frm-find-people table td:nth-child(1) {
    padding: 5px 15px;
    width: 100px
}

.frm-find-people table td:nth-child(2) {
    border: 1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="frm-find-people">
    <table>
        <tbody>
            <tr>
                <td>Name</td>
                <td><input type="text" name="name"></td>
            </tr>
        </tbody>
    </table>
</form></code>```

The red box (second td of the table) should be expanded to the rest of width. How can I do that?

答:
Due to tables layout rules, no cell can be less than it's content width. So you can set it's width to 100%, and it will try to fill whatever is left by the Name cell:

.label {
    width: 100px;
    padding: 5px 15px;
}

.input {
    border: 1px solid red;
    width: 100%;
}

.input > input {
  width: calc(100% - 4px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="frm-find-people">
    <table>
        <tbody>
            <tr>
                <td class="label">Name</td>
                <td class="input"><input type="text" name="name"></td>
            </tr>
        </tbody>
    </table>
</form></code>```

Body:
Here is my code:

.frm-find-people table td:nth-child(1) {
    padding: 5px 15px;
    width: 100px
}

.frm-find-people table td:nth-child(2) {
    border: 1px solid red;
}

<form class="frm-find-people">

                Name
                <input type="text" name="name">

</form>

The red box (second td of the table) should be expanded to the rest of width. How can I do that?

Body:
Due to tables layout rules, no cell can be less than it's content width. So you can set it's width to 100%, and it will try to fill whatever is left by the Name cell:

.label {
    width: 100px;
    padding: 5px 15px;
}

.input {
    border: 1px solid red;
    width: 100%;
}

.input > input {
  width: calc(100% - 4px);
}

<form class="frm-find-people">
    <table>
        <tbody>
            <tr>
                <td class="label">Name</td>
                <td class="input"><input type="text" name="name"></td>
            </tr>
        </tbody>
    </table>
</form>


问:
How do you generate a random date in objective-c?
I'd like to generate a random date between two dates -- for example a random date between today and 60 days from now. How do I do that?

UPDATE

Using information from the answers, I came up with this method, which I  use quite often:

```<code>// Generate a random date sometime between now and n days before day.
// Also, generate a random time to go with the day while we are at it.
- (NSDate *) generateRandomDateWithinDaysBeforeToday:(NSInteger)days
{
    int r1 = arc4random_uniform(days);
    int r2 = arc4random_uniform(23);
    int r3 = arc4random_uniform(59);

    NSDate *today = [NSDate new];
    NSCalendar *gregorian =
             [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *offsetComponents = [NSDateComponents new];
    [offsetComponents setDay:(r1*-1)];
    [offsetComponents setHour:r2];
    [offsetComponents setMinute:r3];

    NSDate *rndDate1 = [gregorian dateByAddingComponents:offsetComponents
                                                  toDate:today options:0];

    return rndDate1;
}
</code>```

答:
Swift 3.x +

```<code>public extension Date {
    /// SwiftRandom extension
    public static func randomWithinDaysBeforeToday(days: Int) -> Date {
        let today = Date()
        let gregorian = Calendar(identifier: .gregorian)

        let r1 = arc4random_uniform(UInt32(days))
        let r2 = arc4random_uniform(UInt32(23))
        let r3 = arc4random_uniform(UInt32(23))
        let r4 = arc4random_uniform(UInt32(23))

        let offsetComponents = NSDateComponents()
        offsetComponents.day = Int(r1) * -1
        offsetComponents.hour = Int(r2)
        offsetComponents.minute = Int(r3)
        offsetComponents.second = Int(r4)

        let rndDate1 = gregorian.date(byAdding: offsetComponents as DateComponents, to: today)
        return rndDate1!
    }

    /// SwiftRandom extension
    public static func random() -> Date {
        let randomTime = TimeInterval(arc4random_uniform(UInt32.max))
        return Date(timeIntervalSince1970: randomTime)
    }
}
</code>```

P.S. Esqarrouth's answer corrected for latest Swift.

Body:
I'd like to generate a random date between two dates -- for example a random date between today and 60 days from now. How do I do that?

UPDATE

Using information from the answers, I came up with this method, which I  use quite often:

// Generate a random date sometime between now and n days before day.
// Also, generate a random time to go with the day while we are at it.
- (NSDate *) generateRandomDateWithinDaysBeforeToday:(NSInteger)days
{
    int r1 = arc4random_uniform(days);
    int r2 = arc4random_uniform(23);
    int r3 = arc4random_uniform(59);

    NSDate *today = [NSDate new];
    NSCalendar *gregorian =
             [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *offsetComponents = [NSDateComponents new];
    [offsetComponents setDay:(r1*-1)];
    [offsetComponents setHour:r2];
    [offsetComponents setMinute:r3];

    NSDate *rndDate1 = [gregorian dateByAddingComponents:offsetComponents
                                                  toDate:today options:0];

    return rndDate1;
}

Body:
Swift 3.x +

public extension Date {
    /// SwiftRandom extension
    public static func randomWithinDaysBeforeToday(days: Int) -> Date {
        let today = Date()
        let gregorian = Calendar(identifier: .gregorian)

        let r1 = arc4random_uniform(UInt32(days))
        let r2 = arc4random_uniform(UInt32(23))
        let r3 = arc4random_uniform(UInt32(23))
        let r4 = arc4random_uniform(UInt32(23))

        let offsetComponents = NSDateComponents()
        offsetComponents.day = Int(r1) * -1
        offsetComponents.hour = Int(r2)
        offsetComponents.minute = Int(r3)
        offsetComponents.second = Int(r4)

        let rndDate1 = gregorian.date(byAdding: offsetComponents as DateComponents, to: today)
        return rndDate1!
    }

    /// SwiftRandom extension
    public static func random() -> Date {
        let randomTime = TimeInterval(arc4random_uniform(UInt32.max))
        return Date(timeIntervalSince1970: randomTime)
    }
}

P.S. Esqarrouth's answer corrected for latest Swift.


问:
Google charts Area chart, How to avoid the color shades in charts?
[Google Area charts**

This is "options" I used in my code.

var options = {
        // title: 'Company Performance',
        // hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
        // vAxis: {minValue: 0}
        vAxis: {
            format: '#',
            gridlines: { count: 4},
          },
      };```

**]1

答:
add the following chart option...  </p>

```<code>areaOpacity: 1
</code>```

Body:
[Google Area charts**

This is "options" I used in my code.

var options = {
        // title: 'Company Performance',
        // hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
        // vAxis: {minValue: 0}
        vAxis: {
            format: '#',
            gridlines: { count: 4},
          },
      };

**]1

Body:
add the following chart option...

areaOpacity: 1


问:
Clear ComboBox if RadioButton is deactivated
I have five RadioButton and five ComboBox controls.

Each RadioButton is connected to a ComboBox.

When I activate one RadioButton, the corresponding ComboBox, it gets enabled.
Now when I choose another RadioButton, the information in the previously selected ComboBox should clear but does not!

I have tried with ComboBox.Clear() as well as ComboBox.Reset(), but it doesn't work.

Here is my code for one of the ComboBox and RadioButton

```<code>if (radioButtondinner.Checked == true)
        {
            comboBoxdinner.DataSource = DList.Dwork();
            comboBoxdinner.DisplayMember = "dinner";
        }
</code>```

答:
// create a check change event and use this. </p>

```<code>private void radioButtondinner_CheckedChanged(object sender, EventArgs e)
        {
            if (!radioButtondinner.Checked)
            {
                // if you want to clear only the text or selected item text
                comboBoxdinner.Text = String.Empty;
                // if you want to clear the entire data source
                comboBoxdinner.DataSource = null;
            }

        }
</code>```

Body:
I have five RadioButton and five ComboBox controls.

Each RadioButton is connected to a ComboBox.

When I activate one RadioButton, the corresponding ComboBox, it gets enabled.
Now when I choose another RadioButton, the information in the previously selected ComboBox should clear but does not!

I have tried with ComboBox.Clear() as well as ComboBox.Reset(), but it doesn't work.

Here is my code for one of the ComboBox and RadioButton

if (radioButtondinner.Checked == true)
        {
            comboBoxdinner.DataSource = DList.Dwork();
            comboBoxdinner.DisplayMember = "dinner";
        }

Body:
// create a check change event and use this.

private void radioButtondinner_CheckedChanged(object sender, EventArgs e)
        {
            if (!radioButtondinner.Checked)
            {
                // if you want to clear only the text or selected item text
                comboBoxdinner.Text = String.Empty;
                // if you want to clear the entire data source
                comboBoxdinner.DataSource = null;
            }

        }


问:
Python Listing 2 Lists In Bullet Form
In my python code, I have 2 lists

```<code>myList = ["Example", "Example2", "Example3"]
mySecondList = ["0000", "1111", "2222"]
</code>```

I need to print these so they look like this:

```<code>- Example 0000
- Example2 1111
- Example3 2222
</code>```

Is there any way to achieve this?

答:
Yes it is, look for zip:

```<code>myList = ["Example", "Example2", "Example3"]
mySecondList = ["0000", "1111", "2222"]

for a, b in zip(myList, mySecondList):
    print("- {} {}".format(a, b))
</code>```

```<code>- Example 0000
- Example2 1111
- Example3 2222
</code>```

The above will work if the lists have the same size, otherwise you should look into izip_longest or zip_longest from itertools module depending on the python version you're using

Title: Python Listing 2 Lists In Bullet Form

Body:
In my python code, I have 2 lists

myList = ["Example", "Example2", "Example3"]
mySecondList = ["0000", "1111", "2222"]

I need to print these so they look like this:

- Example 0000
- Example2 1111
- Example3 2222

Is there any way to achieve this?

Body:
Yes it is, look for zip:

myList = ["Example", "Example2", "Example3"]
mySecondList = ["0000", "1111", "2222"]

for a, b in zip(myList, mySecondList):
    print("- {} {}".format(a, b))

- Example 0000
- Example2 1111
- Example3 2222

The above will work if the lists have the same size, otherwise you should look into izip_longest or zip_longest from itertools module depending on the python version you're using


问:
Login using HTTP Post : iPhone
I'm have created a Login view. Everytime I login it gives me login failed error even if I enter right credentials. This is the method I'm using right now:</p>

```<code>NSString *postString = [[NSString alloc] initWithFormat:@"username=%@&password=%@",userName, password];
    // Package the string in an NSData object
    NSData *requestData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]];

    // Create the URL request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:@"https://172.168.1.9/dologin.php"]];  // create the URL request
    [request setHTTPMethod: @"POST"];   // you're sending POST data
    [request setHTTPBody: requestData];  // apply the post data to be sent
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    // Call the URL
    NSURLResponse *response;  // holds the response from the server
    NSError *error;   // holds any errors
    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&error];
</code>```

答:
Can you verify what the response is? Also, you should probably be encoding the parameters you post: Objective-c iPhone percent encode a string?

ASIHttpRequest example

```<code>- (void)btnLoginTap {
    [txtUsername resignFirstResponder];
    [txtPassword resignFirstResponder];

    NSURL *url = [[NSURL alloc] initWithString:YOUR_URL_HERE];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setTimeOutSeconds:120];
    [request setPostValue:txtUsername.text forKey:@"username"];
    [request setPostValue:txtPassword.text forKey:@"password"];
    [request setDelegate:self];
    [request startAsynchronous];
    [url release];

    //Show a loading view or something here while you wait for the response...
}

- (void) requestFinished:(ASIHTTPRequest *)request {
    //Hide your loading view here.
    NSString *responseString = [request responseString];
    DLog(@"%@", responseString);
    //Request succeeded
}

- (void) requestFailed:(ASIHTTPRequest *)request {
    //Hide your loading view here.
    NSError *error = [request error];
    DLog(@"%@", [error localizedDescription]);
    //Request failed
}
</code>```

Title: Login using HTTP Post : iPhone

Body:
I'm have created a Login view. Everytime I login it gives me login failed error even if I enter right credentials. This is the method I'm using right now:

NSString *postString = [[NSString alloc] initWithFormat:@"username=%@&password=%@",userName, password];
    // Package the string in an NSData object
    NSData *requestData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]];

    // Create the URL request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:@"https://172.168.1.9/dologin.php"]];  // create the URL request
    [request setHTTPMethod: @"POST"];   // you're sending POST data
    [request setHTTPBody: requestData];  // apply the post data to be sent
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    // Call the URL
    NSURLResponse *response;  // holds the response from the server
    NSError *error;   // holds any errors
    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&error];

Body:
Can you verify what the response is? Also, you should probably be encoding the parameters you post: Objective-c iPhone percent encode a string?

ASIHttpRequest example

- (void)btnLoginTap {
    [txtUsername resignFirstResponder];
    [txtPassword resignFirstResponder];

    NSURL *url = [[NSURL alloc] initWithString:YOUR_URL_HERE];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setTimeOutSeconds:120];
    [request setPostValue:txtUsername.text forKey:@"username"];
    [request setPostValue:txtPassword.text forKey:@"password"];
    [request setDelegate:self];
    [request startAsynchronous];
    [url release];

    //Show a loading view or something here while you wait for the response...
}

- (void) requestFinished:(ASIHTTPRequest *)request {
    //Hide your loading view here.
    NSString *responseString = [request responseString];
    DLog(@"%@", responseString);
    //Request succeeded
}

- (void) requestFailed:(ASIHTTPRequest *)request {
    //Hide your loading view here.
    NSError *error = [request error];
    DLog(@"%@", [error localizedDescription]);
    //Request failed
}


问:
How to separate a collection into different "buckets"
I have a collection of C# objects. Each object has, for data members, a string which is a guid, an index which is an int, and a string which is a document name. Here is what a typical collection looks like:

```<code>"guid1","c:\temp\doc1.docx",1
"guid1","c:\temp\doc2.docx",2
"guid1","c:\temp\doc3.docx",3
"guid1","c:\temp\doc4.docx",4
"guid2","c:\temp\doc5.docx",5
"guid1","c:\temp\doc6.docx",6
"guid1","c:\temp\doc7.docx",7

I need to end up breaking the collection into individual collections like this:

"guid1","c:\temp\doc1.docx",1
"guid1","c:\temp\doc2.docx",2
"guid1","c:\temp\doc3.docx",3
"guid1","c:\temp\doc4.docx",4

"guid2","c:\temp\doc5.docx",5

"guid1","c:\temp\doc6.docx",6
"guid1","c:\temp\doc7.docx",7
</code>```

These individual collections will then be fed into another function for processing. Trying to figure out the best way to do this.

答:
Try using Linq, GroupBy:

```<code> IEnumerable<MyClass> source = ...;

 int group = 0;
 Guid key = new Guid();

 // Let's have an array of arrays (array of individual collections) as a result
 MyClass[][] buckets = source
   .GroupBy(item => {
      if (group == 0 || key != item.guid) {
        key = item.guid;
        group += 1;
      }

      return group; })
   .Select(chunk => chunk.ToArray())
   .ToArray();
</code>```

Body:
I have a collection of C# objects. Each object has, for data members, a string which is a guid, an index which is an int, and a string which is a document name. Here is what a typical collection looks like:

"guid1","c:\temp\doc1.docx",1
"guid1","c:\temp\doc2.docx",2
"guid1","c:\temp\doc3.docx",3
"guid1","c:\temp\doc4.docx",4
"guid2","c:\temp\doc5.docx",5
"guid1","c:\temp\doc6.docx",6
"guid1","c:\temp\doc7.docx",7

I need to end up breaking the collection into individual collections like this:

"guid1","c:\temp\doc1.docx",1
"guid1","c:\temp\doc2.docx",2
"guid1","c:\temp\doc3.docx",3
"guid1","c:\temp\doc4.docx",4

"guid2","c:\temp\doc5.docx",5

"guid1","c:\temp\doc6.docx",6
"guid1","c:\temp\doc7.docx",7

These individual collections will then be fed into another function for processing. Trying to figure out the best way to do this.

Body:
Try using Linq, GroupBy:

 IEnumerable<MyClass> source = ...;

 int group = 0;
 Guid key = new Guid();

 // Let's have an array of arrays (array of individual collections) as a result
 MyClass[][] buckets = source
   .GroupBy(item => {
      if (group == 0 || key != item.guid) {
        key = item.guid;
        group += 1;
      }

      return group; })
   .Select(chunk => chunk.ToArray())
   .ToArray();


问:
max function in python
```<code>#!/usr/bin/python
import math
l=raw_input("Enter some numbers:")
a=l.split(",")
b=list(a)
print b
print max(b)
</code>```

output

```<code>Enter some numbers:100,30,31,56,50
['100', '30', '31', '56', '50']
56
</code>```

I'm unable to get accurate result for 100,30,31,56,50. Its giving me 56. Is it because max function doesn't understand three digit numbers? The program works fine for any user input of 2 digits but when I give inputs as a three digit number it cannot find the max.

答:
You should map your data to int. Else your try to take the max of a list of strings.

Change b=list(a) to:

```<code>b=map(int,a)
</code>```

edit You get 56 since 5 is the largest element between 1,3&5 (Which correspond to first character of strings) and then (second character) when we compare 56 and 50, we have 6 which is larger than 0 (so it returns 56).

Title: max function in python

Body:
#!/usr/bin/python
import math
l=raw_input("Enter some numbers:")
a=l.split(",")
b=list(a)
print b
print max(b)

output

Enter some numbers:100,30,31,56,50
['100', '30', '31', '56', '50']
56

I'm unable to get accurate result for 100,30,31,56,50. Its giving me 56. Is it because max function doesn't understand three digit numbers? The program works fine for any user input of 2 digits but when I give inputs as a three digit number it cannot find the max.

Body:
You should map your data to int. Else your try to take the max of a list of strings.

Change b=list(a) to:

b=map(int,a)

edit You get 56 since 5 is the largest element between 1,3&5 (Which correspond to first character of strings) and then (second character) when we compare 56 and 50, we have 6 which is larger than 0 (so it returns 56).


问:
How to Get POST ID from one page to another page
I have created a message system in wordpress. There s a consultation page fr each user.also a sidebar with certain menus. when the submit button is clicked the admin reviews the question and answers it. The message will be shown in the inbox sidebar menu on the same consultation page.

but whtever i tried am not getting the reply message of the corresponding user. my problem is that when i defined the link for inbox there is no id being passed.later in tht particular page whtever id s am calling its bring up the page id only and nothing else.

This is the sidebar code:

```<code><li>
    <a href="<?php echo site_url();?>/inbox/?id=<?php echo get_current_user_id();?>"><i class="fa fa-sort-alpha-asc " aria-hidden="true"> </i> <span style="margin-left:10px;">Inbox</span>  </a>
</li>
</code>```

now its bringing the id = 1. no matter which user it is.

this is the inbox code:

```<code><?php
global $post;
$idd= $post->ID;

$title= $post->post_title;
var_dump($title);

echo "<div class= 'col-lg-4'><table style='width:500px;'><tr><td><b>Reply:</b> ".get_post_meta( $idd, 'docreply', true)."</td></tr></div>";

echo "<div class= 'col-lg-4'><table style='width:500px;'><tr><td><b>Amount:</b> ".get_post_meta( $idd, 'amount', true)."</td></tr></div>";
</code>```

答:
Where is the message data saved?

I see you calling the page URL with the ID of the currently logged user.

Later, you're using the ID of the page then fetching two meta values and displaying them.

If you're using post meta, use the ID of the user that is logged in and get the meta value by using get_user_meta - https://codex.wordpress.org/Function_Reference/get_user_meta

More code would help solve this easier :)

Body:
I have created a message system in wordpress. There s a consultation page fr each user.also a sidebar with certain menus. when the submit button is clicked the admin reviews the question and answers it. The message will be shown in the inbox sidebar menu on the same consultation page.

but whtever i tried am not getting the reply message of the corresponding user. my problem is that when i defined the link for inbox there is no id being passed.later in tht particular page whtever id s am calling its bring up the page id only and nothing else.

This is the sidebar code:

    <a href="<?php echo site_url();?>/inbox/?id=<?php echo get_current_user_id();?>">  Inbox

now its bringing the id = 1. no matter which user it is.

this is the inbox code:

<?php
global $post;
$idd= $post->ID;

$title= $post->post_title;
var_dump($title);

echo "

Reply: ".get_post_meta( $idd, 'docreply', true)."

";

echo "

Amount: ".get_post_meta( $idd, 'amount', true)."

";


问:
How to add "using Zxing" in source code?
I am new to c#. currently I am trying to decode qr code via webcam, I have taken an example from the internet and re written it to try to understand the code. my question is How do I add using Zxing instead of using com.google.zxing?

I know that I should add a reference, but I try to add all the references I know but still it wouldnt allow me to add 'using Zxing'. it only allow 'using com.goggle.zxing' [ I use zxing.dll] as reference

Another problem is compiler error at var reader = new BarcodeReader(); I belief its related to the 'using Zxing" or unknown reference

I really need help on this matter. Kindly show me how to solve or where can I find the Zxing reference. thanks again.

答:
Just add this line for namespace.

using ZXing;

after installing from nugget package.


问:
MySQL stored procedure returns multiple records while straight query returns one
If I create this stored procedure below and the run it I get back both rows from the table when it should be just one query.

```<code>    CREATE PROCEDURE `getUserName`(IN Guid VARCHAR(36), IN GameID INT(11))
    BEGIN
        SELECT `Name` as UserName, `GUID` as guid
        FROM playerdata
        WHERE `GUID` = Guid AND `GameID` = GameID;
    END

    CALL getUserName('86fd1007-4a9c-11e7-b2e2-1803733c2d41', 1001);
</code>```

Returns See Image

However if I just run it as a regular query

```<code>    SELECT `Name` as UserName, `GUID` as guid
    FROM playerdata
    WHERE `GUID` = "86fd1007-4a9c-11e7-b2e2-1803733c2d41" AND `GameID` = 1001;
</code>```

Returns See Image

I am baffled as to the behavior considering... at least to me they are the same thing.

答:
```<code>CREATE PROCEDURE `getUserName`(IN IN_Guid VARCHAR(36), IN IN_GameID INT(11))
    BEGIN
        SELECT `Name` as UserName, `GUID` as guid
        FROM playerdata
        WHERE `GUID` = IN_Guid  AND `GameID` = IN_GameID ;
    END

    CALL getUserName('86fd1007-4a9c-11e7-b2e2-1803733c2d41', 1001);
</code>```

Try above code.

If input parameter have same name as column name,it will finally evaluate equivalent to 1=1 so there is no meaning of condition.Means GameID = GameID and 1=1 both are equivalent.
So always try to make input and output parameters name differ to Column name of specific table.

I had tried it's working fine.

Hope this will helps you.

Body:
If I create this stored procedure below and the run it I get back both rows from the table when it should be just one query.

    CREATE PROCEDURE `getUserName`(IN Guid VARCHAR(36), IN GameID INT(11))
    BEGIN
        SELECT `Name` as UserName, `GUID` as guid
        FROM playerdata
        WHERE `GUID` = Guid AND `GameID` = GameID;
    END

    CALL getUserName('86fd1007-4a9c-11e7-b2e2-1803733c2d41', 1001);

Returns See Image

However if I just run it as a regular query

    SELECT `Name` as UserName, `GUID` as guid
    FROM playerdata
    WHERE `GUID` = "86fd1007-4a9c-11e7-b2e2-1803733c2d41" AND `GameID` = 1001;

Returns See Image

I am baffled as to the behavior considering... at least to me they are the same thing.

Body:
CREATE PROCEDURE `getUserName`(IN IN_Guid VARCHAR(36), IN IN_GameID INT(11))
    BEGIN
        SELECT `Name` as UserName, `GUID` as guid
        FROM playerdata
        WHERE `GUID` = IN_Guid  AND `GameID` = IN_GameID ;
    END

    CALL getUserName('86fd1007-4a9c-11e7-b2e2-1803733c2d41', 1001);

Try above code.

If input parameter have same name as column name,it will finally evaluate equivalent to 1=1 so there is no meaning of condition.Means GameID = GameID and 1=1 both are equivalent.
So always try to make input and output parameters name differ to Column name of specific table.

I had tried it's working fine.

Hope this will helps you.


答:
You can use below regex to capture the parts of the string and replace it by the second column value

```<code>^(\(\d+,\s*.*?(\d+).*?value":).*?([,}])
</code>```

And use \1"\2"\3 as the replacement part.

Live Demo on RegEx101

Explanation:

^: Start of line

\(: Match ( literal

\d+,\s*: Match digit/s followed by comma and any number of spaces

.*?: Match anything to satisfy the following condition

(\d+): Match one or more digits and add them in captured group

.*?value":: Match till value"

([,}]): Match either , or }

The captured group \1 will contain the string till value":, "\2" will contain the number in the second column in double quotes and \3 will contain the last , or }.

Title: How to capture and replace strings with regex in Notepad++

Body:
I try to capture and replace strings with regex in notepad++, but the result is not as expected. The database is formatted like this:

(602, '0602', '[{"id":"9","value":""},{"id":"1","value":"1"}]'),
(1644, '0164', '[{"id":"9","value":""},{"id":"1","value":"3"}]'),
(1311, '0131', '[{"id":"9","value":""},{"id":"1","value":"100"}]'),
(1321, '0132', '[{"id":"9","value":""},{"id":"1","value":"150"}]')

The task is to capture and place column 2 (values 0602, 0164, 0131, 0131) and to insert it as value of id 9. For example, end result must be like this:

(602, '0602', '[{"id":"9","value":"0602"},{"id":"1","value":"1"}]'),
(1644, '0164', '[{"id":"9","value":"0164"},{"id":"1","value":"3"}]'),
(1311, '0131', '[{"id":"9","value":"0131"},{"id":"1","value":"100"}]'),
(1321, '0132', '[{"id":"9","value":"0132"},{"id":"1","value":"150"}]')

I try with this regex in Notepad++ - Search:

(, '.*)("id":"9","value":"")

Replace:

($1)("id":"9","value":"$1")

The result is close, but not what I need. Please, help me if you know the right answer. Thank you in advance.

Body:
You can use below regex to capture the parts of the string and replace it by the second column value

^(\(\d+,\s*.*?(\d+).*?value":).*?([,}])

And use \1"\2"\3 as the replacement part.

Live Demo on RegEx101

Explanation:

^: Start of line

\(: Match ( literal

\d+,\s*: Match digit/s followed by comma and any number of spaces

.*?: Match anything to satisfy the following condition

(\d+): Match one or more digits and add them in captured group

.*?value":: Match till value"

([,}]): Match either , or }

The captured group \1 will contain the string till value":, "\2" will contain the number in the second column in double quotes and \3 will contain the last , or }.


问:
Discard rows that do not have 6 doublequotes
I have a CSV file that has some errors in it. What I want to do is disregard all lines that do not have 6 double quotes (") in them.

So in short it should be something like;

```<code>cat output.txt | grep -v '"*"*"*"*"*"'
</code>```

Of course the above command won't work.. but it's a direction I am thinking.. maybe AWK would be a better option?

答:
* is glob pattern not regex pattern.

You can use this regex in grep:

```<code>grep -Ev '^([^"]*"){6}' file
</code>```

Using awk you can do by using " as input field separator:

```<code>awk -F '"' 'NF<7' file
</code>```

Body:
I have a CSV file that has some errors in it. What I want to do is disregard all lines that do not have 6 double quotes (") in them.

So in short it should be something like;

cat output.txt | grep -v '"*"*"*"*"*"'

Of course the above command won't work.. but it's a direction I am thinking.. maybe AWK would be a better option?

Body:
* is glob pattern not regex pattern.

You can use this regex in grep:

grep -Ev '^([^"]*"){6}' file

Using awk you can do by using " as input field separator:

awk -F '"' 'NF<7' file


问:
How to execute business logic handler in a separate thread pool using netty
I have a handler that needs to execute some business logic and I want that to be executed in a separate thread pool to not block the io event loop. I have added DefaultEventExecutorGroup into the pipeline as specified in http://netty.io/4.0/api/io/netty/channel/ChannelPipeline.html javadoc and http://netty.io/wiki/new-and-noteworthy-in-4.0.html#no-more-executionhandler---its-in-the-core wiki:

```<code>ch.pipeline().addLast(new DefaultEventExecutorGroup(10), new ServerHandler());
</code>```

Just for testing purposes my ServerHandler just puts the current thread to sleep for 5 seconds:

```<code>protected void channelRead0(ChannelHandlerContext ctx, Command cmd) throws Exception {
    System.out.println("Starting.");

    try {
        Thread.currentThread().sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("Finished.");
}
</code>```

But apparently the business logic is still executed synchronously:

```<code>Starting.
Finished.
Starting.
Finished.
Starting.
Finished.
</code>```

What am I missing?

答:
In case your goal is not to block IO event loop - you did it right. But due to netty specific, your handler will be always attached to the same thread of EventExecutorGroup and thus behavior you described above is expected.

In case you want to execute blocking operation in parallel as soon as it arrives you need to use the another way - separate ThreadPoolExecutor. Like this:

```<code>ch.pipeline().addLast(new ServerHandler(blockingThreadPool));
</code>```

where blockingThreadPool is regular ThreadPoolExecutor.

For example:

```<code>ExecutorService blockingThreadPool = Executors.newFixedThreadPool(10);
</code>```

Now, within your logic handler you can submit blocking tasks to this executor like this:

```<code>protected void channelRead0(ChannelHandlerContext ctx, Command cmd) throws Exception {

    blockingIOProcessor.execute(new Runnable() {
        @Override
        public void run() {
            System.out.println("Starting.");

            try {
                Thread.currentThread().sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println("Finished.");
        }
    });

}
</code>```

You can also pass context to this runnable in order to return the response back when processing is finished if needed.

Body:
I have a handler that needs to execute some business logic and I want that to be executed in a separate thread pool to not block the io event loop. I have added DefaultEventExecutorGroup into the pipeline as specified in http://netty.io/4.0/api/io/netty/channel/ChannelPipeline.html javadoc and http://netty.io/wiki/new-and-noteworthy-in-4.0.html#no-more-executionhandler---its-in-the-core wiki:

ch.pipeline().addLast(new DefaultEventExecutorGroup(10), new ServerHandler());

Just for testing purposes my ServerHandler just puts the current thread to sleep for 5 seconds:

protected void channelRead0(ChannelHandlerContext ctx, Command cmd) throws Exception {
    System.out.println("Starting.");

    try {
        Thread.currentThread().sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("Finished.");
}

But apparently the business logic is still executed synchronously:

Starting.
Finished.
Starting.
Finished.
Starting.
Finished.

What am I missing?

Body:
In case your goal is not to block IO event loop - you did it right. But due to netty specific, your handler will be always attached to the same thread of EventExecutorGroup and thus behavior you described above is expected.

In case you want to execute blocking operation in parallel as soon as it arrives you need to use the another way - separate ThreadPoolExecutor. Like this:

ch.pipeline().addLast(new ServerHandler(blockingThreadPool));

where blockingThreadPool is regular ThreadPoolExecutor.

For example:

ExecutorService blockingThreadPool = Executors.newFixedThreadPool(10);

Now, within your logic handler you can submit blocking tasks to this executor like this:

protected void channelRead0(ChannelHandlerContext ctx, Command cmd) throws Exception {

    blockingIOProcessor.execute(new Runnable() {
        @Override
        public void run() {
            System.out.println("Starting.");

            try {
                Thread.currentThread().sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println("Finished.");
        }
    });

}

You can also pass context to this runnable in order to return the response back when processing is finished if needed.


问:
sync cookies and sessions in different subdomains (asp.net)
I am building a site in asp.net and have multiple subdomains. For example,
one.cookies.com
two.cookies.com

I want my users to be able to login at either subdomain and be logged in for both websites. In addition, I'd like the sessions and cookies to be in sync. So far I haven't found a reliable way to do this.

答:
When you create the cookie you can set the domain:

```<code>HttpCookie cookie = new HttpCookie("name", "value");
cookie.Domain = "cookies.com";
</code>```

This will allow your cookie to be accessible from all subdomains of cookies.com.

If you are using FormsAuthentication then you can set the domain for the auth cookie in web.config:

```<code><forms name=".ASPXAUTH"
       loginUrl="login.aspx"
       defaultUrl="default.aspx"
       protection="All"
       timeout="30"
       path="/"
       requireSSL="false"
       domain="cookies.com">
</forms>
</code>```

Remember that for the single sign-on to work on multiple subdomains your ASP.NET applications must share the same machine keys as explained in this CodeProject article.

Sharing sessions between different subdomains (different worker processes) is more difficult because sessions are constrained to an application and you will have to implement a custom session synchronization mechanism.

OwnerDisplayName: dan

LastEditorDisplayName: dan

Body:
When you create the cookie you can set the domain:

HttpCookie cookie = new HttpCookie("name", "value");
cookie.Domain = "cookies.com";

This will allow your cookie to be accessible from all subdomains of cookies.com.

If you are using FormsAuthentication then you can set the domain for the auth cookie in web.config:

<forms name=".ASPXAUTH"
       loginUrl="login.aspx"
       defaultUrl="default.aspx"
       protection="All"
       timeout="30"
       path="/"
       requireSSL="false"
       domain="cookies.com">
</forms>

Remember that for the single sign-on to work on multiple subdomains your ASP.NET applications must share the same machine keys as explained in this CodeProject article.

Sharing sessions between different subdomains (different worker processes) is more difficult because sessions are constrained to an application and you will have to implement a custom session synchronization mechanism.

OwnerDisplayName: darin

LastEditorDisplayName: darin


问:
Java: XML to Object (or Array)
How could I convert a XML Document to a Java Object (or Array)?
I readed the XML like this:

```<code>DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();

Document doc = dBuilder.parse(new File("file.xml"));
doc.getDocumentElement().normalize();
</code>```

Now I want that XML as Object (or Array) but how should I do this?
Are there any methods or tutorials or classes out there to do that?

答: I have used Simple XML and have found it quite easy and powerful.  I am not as familiar with XStream, but Simple lets you control your XML schema using annotations which gives you a lot of freedom.  The guy who writes it is always responsive on his mailing list.</p>

Title: Java: XML to Object (or Array)

Body:
How could I convert a XML Document to a Java Object (or Array)?
I readed the XML like this:

DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();

Document doc = dBuilder.parse(new File("file.xml"));
doc.getDocumentElement().normalize();

Now I want that XML as Object (or Array) but how should I do this?
Are there any methods or tutorials or classes out there to do that?


问:
unable to get xpath of anchor element under span element
I have already learned to use xpath but i am kind of stuck here - http://phptravels.com/requirements/. Can anyone please tell me how to find xpath of "Demo" hyperlink on this website. I simply used //a[text()= 'Demo                 ']. keep whitespaces in mind.

答:
Try to bind the xpath with an id which is persistent, you can consider using this xpath:

```<code>//nav[@id='main-menu']/ul/li/span/span/a[contains(text(), 'Demo')]
</code>```

Body:
Try to bind the xpath with an id which is persistent, you can consider using this xpath:

//nav[@id='main-menu']/ul/li/span/span/a[contains(text(), 'Demo')]


问:
Not able to install node-sass
I have been trying to install node-sass using npm but it shows a postinstall error. I have already got the latest version of node and npm.

答:
I had the same issue exactly, here is how i solve it:

Install node-gyp globally:

npm install node-gyp -g

check if you are behind a proxy, if yes, then you need to create .npmrc file in windows user profile folder and add there your proxy details:

```<code>proxy=null
http-proxy=http://<proxy host>:<port>
https-proxy=http://<proxy host>:<port>
</code>```

in Unix/OSX the .npmrc file should be in $HOME/.npmrc

Title: Not able to install node-sass

Body:
I had the same issue exactly, here is how i solve it:

Install node-gyp globally:

npm install node-gyp -g

check if you are behind a proxy, if yes, then you need to create .npmrc file in windows user profile folder and add there your proxy details:

proxy=null
http-proxy=http://<proxy host>:<port>
https-proxy=http://<proxy host>:<port>

in Unix/OSX the .npmrc file should be in $HOME/.npmrc


问:
How to create batch file for FFMpeg to download stream videos
Hi I'm using this cmd code to download stream video using ffmpeg:

```<code>ffmpeg -i "http://wpc.866f.edgecastcdn.net/03866F/greyback/yourtrinity/130929-webword_,2500,1500,580,265,.mp4.m3u8" -c copy 130929-webword.mkv
</code>```

now I want a batch file that in running time ask me the video address and the file name by pressing Enter.

答:
```<code>@echo off
set /p "address=Video Address:"
set /p "filename=File name:"
ffmpeg -i "%address%" -c copy "%filename%"
</code>```

Body:
Hi I'm using this cmd code to download stream video using ffmpeg:

ffmpeg -i "http://wpc.866f.edgecastcdn.net/03866F/greyback/yourtrinity/130929-webword_,2500,1500,580,265,.mp4.m3u8" -c copy 130929-webword.mkv

now I want a batch file that in running time ask me the video address and the file name by pressing Enter.