问:
How to authenticate MailChimp on DKIM in 1and1
I've searched everywhere about this issue and found nothing.
I want to authenticate my domain in MailChimp. My website is hosted in 1and1.
These are the instructions from MailChimp:
Create a CNAME record for k1._domainkey.YOURDOMAIN.com with this value:
dkim.mcsv.net

The problem is that 1and1 only allows CNAME records on subdomains, so I created a subdomain named mail.MYDOMAIN.com and set up a CNAME record for it with the alias dkim.mcsv.net. Waited for 24 hours and it doesn't work.

Does anyone know what's wrong and the correct way to do this?

答:
1and1 do things deferently. Even though Mailchimp says - to create subdomain k1._domainkey.YOURDOMAIN.com or k1._domainkey.MYDOMAIN.com it does not work.

Also the interface accepts the values differently by separating them.

Here is what I have on "my working set up", to register your Domain authentication with Mailchimp using 1and1, please follow.

Log in and go to your Control Panel

Click Manage Domains

Click the three dots next to Actions, Select Advanced Settings.

Scroll down to DNS Settings, click edit.

For DKIM: Create a CNAME record for k1._domainkey.yourname.com with this value:

Scroll down to TXT, CNAME and SRV Records.

Click button Add record

Select CNAME from the drop down menu

In the Prefix box put "k1._domainkey" no quotes.

In the Value box put "dkim.mcsv.net" no quotes.

click Add.

To create a SPF: Create a TXT record for your domain.com

Click Add record for the last time.

Select TXT from the drop down menu.

In the Value box put "v=spf1 include:servers.mcsv.net ?all" no quotes.

click Add.

Now click Save!

All done... Wait 28/48 hours and go back to MailChimp and verify


来源: stackexchange

问:
java.lang.IllegalArgumentException: contains a path separator
I have a filename in my code as :

```<code>String NAME_OF_FILE="//sdcard//imageq.png";
FileInputStream fis =this.openFileInput(NAME_OF_FILE); // 2nd line
</code>```

I get an error on 2nd line :

05-11 16:49:06.355: ERROR/AndroidRuntime(4570): Caused by: java.lang.IllegalArgumentException: File //sdcard//imageq.png contains a path separator

I tried this format also:

```<code>String NAME_OF_FILE="/sdcard/imageq.png";
</code>```

答:
I solved this type of error by making a directory in the onCreate event, then accessing the directory by creating a new file object in a method that needs to do something such as save or retrieve a file in that directory, hope this helps!</p>

```<code> public class MyClass {

 private String state;
 public File myFilename;

 @Override
 protected void onCreate(Bundle savedInstanceState) {//create your directory the user will be able to find
    super.onCreate(savedInstanceState);
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        myFilename = new File(Environment.getExternalStorageDirectory().toString() + "/My Directory");
        if (!myFilename.exists()) {
            myFilename.mkdirs();
        }
    }
 }

 public void myMethod {

 File fileTo = new File(myFilename.toString() + "/myPic.png");
 // use fileTo object to save your file in your new directory that was created in the onCreate method
 }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a filename in my code as :

String NAME_OF_FILE="//sdcard//imageq.png";
FileInputStream fis =this.openFileInput(NAME_OF_FILE); // 2nd line

I get an error on 2nd line :

05-11 16:49:06.355: ERROR/AndroidRuntime(4570): Caused by: java.lang.IllegalArgumentException: File //sdcard//imageq.png contains a path separator

I tried this format also:

String NAME_OF_FILE="/sdcard/imageq.png";

Body:
I solved this type of error by making a directory in the onCreate event, then accessing the directory by creating a new file object in a method that needs to do something such as save or retrieve a file in that directory, hope this helps!

 public class MyClass {

 private String state;
 public File myFilename;

 @Override
 protected void onCreate(Bundle savedInstanceState) {//create your directory the user will be able to find
    super.onCreate(savedInstanceState);
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        myFilename = new File(Environment.getExternalStorageDirectory().toString() + "/My Directory");
        if (!myFilename.exists()) {
            myFilename.mkdirs();
        }
    }
 }

 public void myMethod {

 File fileTo = new File(myFilename.toString() + "/myPic.png");
 // use fileTo object to save your file in your new directory that was created in the onCreate method
 }
}


问:
codeigniter validate
Hello I have a forum and when a user creates a comment, I want that if he didn't type anything I want to show him an error that he must type something in :) but I dont know how to put him the the thread he is in.

I have this

```<code>if($this->_submit_validate_comment() == false) {
   $this->post(); return;
}

function _submit_validate_comment() {
  $this->form_validation->set_rules('kommentar', 'kommentar', 'required|min_length[4]');
  return $this->form_validation->run();
}
</code>```

答:
You could do this with jquery but if that is not an option you could get the forum or topic id from the url (assuming your are using the url this way).

For example:

http://yoursite.com/forum/topic/12

```<code>if($this->_submit_validate_comment() == false)
{
    $topic_id = $this->uri->segment(3);
    redirect('/forum/topic/'. $topic_id);
}
</code>```

Or

```<code>if($this->_submit_validate_comment() == false)
{
    $topic_id = $this->uri->segment(3);
    $this->topic($topic_id);
}
</code>```

Hope this helps.

ContentLicense: CC BY-SA 2.5

Title: codeigniter validate

Body:
Hello I have a forum and when a user creates a comment, I want that if he didn't type anything I want to show him an error that he must type something in :) but I dont know how to put him the the thread he is in.

I have this

if($this->_submit_validate_comment() == false) {
   $this->post(); return;
}

function _submit_validate_comment() {
  $this->form_validation->set_rules('kommentar', 'kommentar', 'required|min_length[4]');
  return $this->form_validation->run();
}

Body:
You could do this with jquery but if that is not an option you could get the forum or topic id from the url (assuming your are using the url this way).

For example:

http://yoursite.com/forum/topic/12

if($this->_submit_validate_comment() == false)
{
    $topic_id = $this->uri->segment(3);
    redirect('/forum/topic/'. $topic_id);
}

Or

if($this->_submit_validate_comment() == false)
{
    $topic_id = $this->uri->segment(3);
    $this->topic($topic_id);
}

Hope this helps.

OwnerDisplayName: Cadmus


问:
Detect change in each object of an array. Typescript/Angular 2
I have a person array which I displayed in a primeng datatable. Each object has these fields (firstName, lastName and age). Each field corresponds to a column in a table with an additional column that displays the status of each object. The status indicates if the object/row in the table has change. There are two status "Object Change/Not Change"

```<code><p-dataTable [value]="persons" [editable]="true"  resizableColumns="true" reorderableColumns="true">
    <p-column header="Status">
      <ng-template pTemplate="body">
         <span [hidden]=true>Object Change</span>
       <span >Not Change</span>
      </ng-template>
    </p-column>
    <p-column field="firstName" header="First Name" [editable]="true"></p-column>
    <p-column field="lastName" header="Last Name" [editable]="true"></p-column>
    <p-column field="age" header="Age" [editable]="true">
      <ng-template let-col let-car="rowData" pTemplate="editor">
        <select class="form-control" [(ngModel)]="car[col.field]">
          <option [value]=12>12</option>
          <option [value]=14>14</option>
          <option [value]=23>23</option>
        </select>
      </ng-template>
    </p-column>
</p-dataTable>

<p>{{persons | json}}</p>
</code>```

I set the primeng datatable column editable to true so that the user can edit the data inside the table. Now, I want to detect if each object has changed. If the object has changed I want the "status" column be set to "Object change". I want to apply this condition in each object in the array. Is there a way to detect the change for each row/object in the array.I createda plunkr for this. http://plnkr.co/edit/x8Sdgz?p=preview

答:
I will detect the change on the field. If you want to intercept every change on any field you'll have to use the same pattern (ng-template) on every column in the datatable.

Kind regards

Body:
I have a person array which I displayed in a primeng datatable. Each object has these fields (firstName, lastName and age). Each field corresponds to a column in a table with an additional column that displays the status of each object. The status indicates if the object/row in the table has change. There are two status "Object Change/Not Change"

      <ng-template pTemplate="body">
         Object Change
       Not Change
      </ng-template>

      <ng-template let-col let-car="rowData" pTemplate="editor">
        <select class="form-control" [(ngModel)]="car[col.field]">
          <option [value]=12>12</option>
          <option [value]=14>14</option>
          <option [value]=23>23</option>
        </select>
      </ng-template>

{{persons | json}}

I set the primeng datatable column editable to true so that the user can edit the data inside the table. Now, I want to detect if each object has changed. If the object has changed I want the "status" column be set to "Object change". I want to apply this condition in each object in the array. Is there a way to detect the change for each row/object in the array.I createda plunkr for this. http://plnkr.co/edit/x8Sdgz?p=preview


问:
Set div to fixed until it comes into contact with other element where it becomes absolute. Won't revert back to fixed when scrolling back up
I'm having some trouble adding a sticky on scroll "Add to Cart" area to a product page.

So far I'm able to make the selected element become position: fixed from a certain point while scrolling until it reaches a 'cutoff point' so to speak, where it becomes position: absolute.

I also have a rule written to remove the position styling when I scroll above the 'starting point' for position: fixed. All of these are written inside one function which fires on $(document).scroll(). I'll post my code below.

The rules I've written seem to be working fine except for one specific thing. When I scroll down, the element becomes fixed. When the fixed element reaches the 'cutoff point' it switches to position: absolute and stays there when I continue scrolling. This is what I want.

The problem is when I start scrolling back up past the 'cutoff point' the element's positioning doesn't switch back to position: fixed. It stays position: absolute until I reach the top of the page where the styling is removed. I can then scroll down again and it will start all over again, fixed > absolute > not reverting back to fixed on scroll up.

```<code>function checkOffset() {

    var div1 = $(".ProductMain");
    var div2 = $(".SideRelatedProducts");
    var div3 = $("#cssmenu");

    var div1_top = div1.offset().top;
    var div2_top = div2.offset().top;
    var div3_top = div3.offset().top;

    var div1_bottom = div1_top + div1.height();
    var div2_bottom = div2_top + div2.height();
    var div3_bottom = div3_top + div3.height();

  // This is what removes styling assigned from scrolling, when element gets back to top of page

    if (div1_bottom >= div3_bottom && $(window).width() > 900) {
        $('.ProductMain').css({
            'position': 'absolute',
            'top': 'auto',
            'bottom': '55px'
        });
        console.log('ABSOLUTE');
    }

  // This is what removes styling assigned from scrolling, when element gets back to top of page

    if ($(document).scrollTop() > $('.main').offset().top + 20 && $(document).scrollTop() + div1.height() < (div2_top + 75) && div1_bottom < div3_bottom && $(window).width() > 900) {
        $('.ProductMain').css({
            'position': 'fixed',
            'top': '60px',
            'bottom': 'auto'
        }); // restore when you scroll up
        console.log('FIXED');
    }

  // This is what removes styling assigned from scrolling, when element gets back to top of page

    if($(document).scrollTop() < $('.main').offset().top && $(document).scrollTop() + window.innerHeight < div2_top || $(window).width() < 900) {
        $('.ProductMain').removeAttr('style');
    }
}

$(document).scroll(function() {
    checkOffset();
});
</code>```

Thanks for your help!

答:
This seems to be answered already. Please try this answer here:

Using jQuery to keep scrolling object within visible window

Body:
I'm having some trouble adding a sticky on scroll "Add to Cart" area to a product page.

So far I'm able to make the selected element become position: fixed from a certain point while scrolling until it reaches a 'cutoff point' so to speak, where it becomes position: absolute.

I also have a rule written to remove the position styling when I scroll above the 'starting point' for position: fixed. All of these are written inside one function which fires on $(document).scroll(). I'll post my code below.

The rules I've written seem to be working fine except for one specific thing. When I scroll down, the element becomes fixed. When the fixed element reaches the 'cutoff point' it switches to position: absolute and stays there when I continue scrolling. This is what I want.

The problem is when I start scrolling back up past the 'cutoff point' the element's positioning doesn't switch back to position: fixed. It stays position: absolute until I reach the top of the page where the styling is removed. I can then scroll down again and it will start all over again, fixed > absolute > not reverting back to fixed on scroll up.

function checkOffset() {

    var div1 = $(".ProductMain");
    var div2 = $(".SideRelatedProducts");
    var div3 = $("#cssmenu");

    var div1_top = div1.offset().top;
    var div2_top = div2.offset().top;
    var div3_top = div3.offset().top;

    var div1_bottom = div1_top + div1.height();
    var div2_bottom = div2_top + div2.height();
    var div3_bottom = div3_top + div3.height();

  // This is what removes styling assigned from scrolling, when element gets back to top of page

    if (div1_bottom >= div3_bottom && $(window).width() > 900) {
        $('.ProductMain').css({
            'position': 'absolute',
            'top': 'auto',
            'bottom': '55px'
        });
        console.log('ABSOLUTE');
    }

  // This is what removes styling assigned from scrolling, when element gets back to top of page

    if ($(document).scrollTop() > $('.main').offset().top + 20 && $(document).scrollTop() + div1.height() < (div2_top + 75) && div1_bottom < div3_bottom && $(window).width() > 900) {
        $('.ProductMain').css({
            'position': 'fixed',
            'top': '60px',
            'bottom': 'auto'
        }); // restore when you scroll up
        console.log('FIXED');
    }

  // This is what removes styling assigned from scrolling, when element gets back to top of page

    if($(document).scrollTop() < $('.main').offset().top && $(document).scrollTop() + window.innerHeight < div2_top || $(window).width() < 900) {
        $('.ProductMain').removeAttr('style');
    }
}

$(document).scroll(function() {
    checkOffset();
});

Thanks for your help!


问:
How to search an specific button in a grid using webdriverIO
I'm using an ExtJS grid panel. This grid has more than 20 rows of info and I want to search in each row for an icon that represents active mode, using WebdriverIO as a test driver.

How can I search in each row till the test driver finds the first active icon? (Note: the grid I'm testing is hosted on alegra.com).

Consider the following HTML print-screen:

答:
It's hard to know exactly how to do it without knowing which locator you are using but if you first get a list of the rows and then filter them and grab the first match it should do what you are looking for.</p>

```<code>public static get rows() { return browser.elements('#someTableId > table > tbody > tr'); }

public static getFirstMatch() {
    return this.rows.value.filter((row: WebdriverIO.Element) =>
        browser.elementIdElement(row.ELEMENT, 'someLocator').value)[0];
}
</code>```

Body:
It's hard to know exactly how to do it without knowing which locator you are using but if you first get a list of the rows and then filter them and grab the first match it should do what you are looking for.

public static get rows() { return browser.elements('#someTableId > table > tbody > tr'); }

public static getFirstMatch() {
    return this.rows.value.filter((row: WebdriverIO.Element) =>
        browser.elementIdElement(row.ELEMENT, 'someLocator').value)[0];
}


问:
C# Adding multiple elements to a list using xdocument
```<code><?xml version="1.0" encoding="utf-8" ?>
<root>
  <fileUploadSpecification>
    <DirectoryPath>C:\watchFolder</DirectoryPath>
    <Region>us-west-2</Region>
    <UploadBucket>configurationtestbucket</UploadBucket>
    <FileType>
      <type>*.txt</type>
      <type>*.OpticomCfg</type>
    </FileType>
  </fileUploadSpecification>
  <fileUploadSpecification>
    <DirectoryPath>C:\watchFolder</DirectoryPath>
    <Region>us-west-2</Region>
    <UploadBucket>loguploadbucket</UploadBucket>
    <FileType>
      <type>*.Xml</type>
      <type>*.Json</type>
    </FileType>
  </fileUploadSpecification>
</root>
</code>```

This is the XML file I need to parse, I want to get each instance of fileUploadSpecification so that I can put each set of details into a list, I think some type of for loop would be appropriate, where I loop through and add the first set of upload details and then loop through and add the second. This is what I currently have, but it never gets to the second fileUploadSpecification element, it just returns the same one again.
The idea would be to create a new SettingsData for every set of fileUploadSpecification elements, whether it be two like shown above, or 10.

```<code>public interface ISettingsEngine
{

    IEnumerable<SettingsData> GetSettings();
}

public class SettingsEngine : ISettingsEngine
{

    public IEnumerable<SettingsData> GetSettings()
    {
        List<SettingsData> dataList = new List<SettingsData>();
        try
        {

            var xDoc = XDocument.Load("File1.xml");

            var instancesToParse = xDoc.Root.Elements().Count();

            var fileCount = xDoc.Root.Elements("FileType").Count();

            for (int x = 0; x < instancesToParse; x++)
            {
                var newSettingsData = new SettingsData();

                newSettingsData.UploadBucket = xDoc.Root.Element("fileUploadSpecification").Element("UploadBucket").Value;
                newSettingsData.Region = xDoc.Root.Element("fileUploadSpecification").Element("Region").Value;
                newSettingsData.DirectoryPath = xDoc.Root.Element("fileUploadSpecification").Element("DirectoryPath").Value;
                var query = xDoc.Root.Descendants("FileType").Elements("type");

                foreach (XElement e in query)
                {
                    newSettingsData.FileType.Add(e.Value);
                }
dataList.Add(newSettingsData);

            }

            return dataList;
        }
        catch(Exception)
        {
            return dataList;
        }
    }
}

public class SettingsData
{

    public List<string> FileType { get; set; }
    public string DirectoryPath { get; set; }
    public string Region { get; set; }
    public string UploadBucket { get; set; }

    public SettingsData()
    {
        FileType = new List<string>();
    }
}
</code>```

答:
```<code>var dataList = (from fus in xDoc.Root.Elements("fileUploadSpecification")
             select new SettingsData
             {
                 UploadBucket = fus.Element("UploadBucket").Value,
                 Region = fus.Element("Region").Value,
                 DirectoryPath = fus.Element("DirectoryPath").Value,
                 FileType = fus.Element("FileType")
                               .Elements("type").Select(f =>f.Value).ToList()
             }).ToList();
</code>```

Body:
<?xml version="1.0" encoding="utf-8" ?>
<root>
  <fileUploadSpecification>
    <DirectoryPath>C:\watchFolder</DirectoryPath>
    <Region>us-west-2</Region>
    <UploadBucket>configurationtestbucket</UploadBucket>
    <FileType>
      <type>*.txt</type>
      <type>*.OpticomCfg</type>
    </FileType>
  </fileUploadSpecification>
  <fileUploadSpecification>
    <DirectoryPath>C:\watchFolder</DirectoryPath>
    <Region>us-west-2</Region>
    <UploadBucket>loguploadbucket</UploadBucket>
    <FileType>
      <type>*.Xml</type>
      <type>*.Json</type>
    </FileType>
  </fileUploadSpecification>
</root>

This is the XML file I need to parse, I want to get each instance of fileUploadSpecification so that I can put each set of details into a list, I think some type of for loop would be appropriate, where I loop through and add the first set of upload details and then loop through and add the second. This is what I currently have, but it never gets to the second fileUploadSpecification element, it just returns the same one again.
The idea would be to create a new SettingsData for every set of fileUploadSpecification elements, whether it be two like shown above, or 10.

public interface ISettingsEngine
{

    IEnumerable<SettingsData> GetSettings();
}

public class SettingsEngine : ISettingsEngine
{

    public IEnumerable<SettingsData> GetSettings()
    {
        List<SettingsData> dataList = new List<SettingsData>();
        try
        {

            var xDoc = XDocument.Load("File1.xml");

            var instancesToParse = xDoc.Root.Elements().Count();

            var fileCount = xDoc.Root.Elements("FileType").Count();

            for (int x = 0; x < instancesToParse; x++)
            {
                var newSettingsData = new SettingsData();

                newSettingsData.UploadBucket = xDoc.Root.Element("fileUploadSpecification").Element("UploadBucket").Value;
                newSettingsData.Region = xDoc.Root.Element("fileUploadSpecification").Element("Region").Value;
                newSettingsData.DirectoryPath = xDoc.Root.Element("fileUploadSpecification").Element("DirectoryPath").Value;
                var query = xDoc.Root.Descendants("FileType").Elements("type");

                foreach (XElement e in query)
                {
                    newSettingsData.FileType.Add(e.Value);
                }
dataList.Add(newSettingsData);

            }

            return dataList;
        }
        catch(Exception)
        {
            return dataList;
        }
    }
}

public class SettingsData
{

    public List<string> FileType { get; set; }
    public string DirectoryPath { get; set; }
    public string Region { get; set; }
    public string UploadBucket { get; set; }

    public SettingsData()
    {
        FileType = new List<string>();
    }
}


问:
Basic Flow Control in JavaScript
Could you, please, explain to me, how to write really basic flow control in JavaScript? Thank you.</p>

```<code>flow([

  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback();  }

], function() {

  alert("Done.");

});
</code>```

答:
Would something like this work?</p>

```<code>function flow(fns, last) {
    var f = last;
    for (var i = fns.length - 1; i >= 0; i--)
        f = makefunc(fns[i], f);
    f();
}

function makefunc(f, g) {
    return function() { f(g) }
}
</code>```

Title: Basic Flow Control in JavaScript

Body:
Could you, please, explain to me, how to write really basic flow control in JavaScript? Thank you.

flow([

  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback();  }

], function() {

  alert("Done.");

});

Body:
Would something like this work?

function flow(fns, last) {
    var f = last;
    for (var i = fns.length - 1; i >= 0; i--)
        f = makefunc(fns[i], f);
    f();
}

function makefunc(f, g) {
    return function() { f(g) }
}


问:
XSLT: Ignore duplicates similar values
I am working on XSLT which has a logic to ignore duplicates using (MySegment/*[not(.=preceding::*)]).

Input:

```<code><MySegment>
  <Field1>ABCD</Field1>
  <FIeld2>1</Field2>
</MySegment>
<MySegment>
  <Field1>ABCD123</Field1>
  <FIeld2>1</Field2>
</MySegment>
</code>```

Here we have two distinct values, however since ABCD123 contains ABCD as well,its being treated as a duplicate entry. Can anyone advise.

Here is how my XSLT looks like:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

  <xsl:template match="/RecordsInp">

    <xsl:for-each select="ParentSegment">

      <xsl:for-each select="./MySegment/*[not(.=preceding::*)]">

        <A>
          <Field1><xsl:value-of select ="name(.)"/></Field1>
          <Field2><xsl:value-of select="."/></Field2>
        </A>

      </xsl:for-each>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>
</code>```

My input is:

```<code><RecordsInp>
  <ParentSegment>
    <MySegment>
      <Field1>ABC</Field1>
      <Field2>A1</Field2>
    </MySegment>

    <MySegment>
      <Field1>ABC</Field1>
      <Field2>A1</Field2>
    </MySegment>

    <MySegment>
      <Field1>ABCDEF</Field1>
      <Field2>ABC</Field2>
    </MySegment>
  </ParentSegment>
</RecordsInp>
</code>```

What I am getting is:

```<code> <?xml version="1.0" encoding="UTF-8"?>
    <A>
      <Field1>Field1</Field1>
      <Field2>ABC</Field2>
    </A><A>
      <Field1>Field2</Field1>
      <Field2>A1</Field2>
    </A><A>
      <Field1>Field1</Field1>
      <Field2>ABCDEF</Field2>
    </A>
</code>```

Notice I am not getting Field2=ABC in the last occurrence. Since Field2 never had ABC in previous occurrences, I need below XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<A>
  <Field1>Field1</Field1>
  <Field2>ABC</Field2>
</A><A>
  <Field1>Field2</Field1>
  <Field2>A1</Field2>
</A><A>
  <Field1>Field1</Field1>
  <Field2>ABCDEF</Field2>
</A>
<A>
  <Field1>Field2</Field1>
  <Field2>ABC</Field2>
</A>
</code>```

答:
Your XPath expression ./MySegment/*[not(.=preceding::*)] selects those child elements of each of the context node's <MySegment> children whose string values do not match those of any element preceding them in document order.  Thus, the <Field2>ABC</Field2> is not reflected in the result because of the preceding <Field1>ABC</Field1> elements.

Evidently that's a broader condition than you intend; as I understand it, you want to compare only with preceding elements having the same name.  That's a bit tricky to express in pure XPath; it would be easier to handle with a stylesheet refactoring.  Gratuitous use of xsl:for-each suggests such a refactoring anyway.  Here's a reasonable way to go about it:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/RecordsInp/ParentSegment/MySegment/*">
    <!-- bind the context node's name and value to variables: -->
    <xsl:variable name="fname" select="name()"/>
    <xsl:variable name="fvalue" select="string(.)"/>

    <!-- here's the test you seem really to want: -->
    <xsl:if test="not(preceding::*[name() = $fname and string() = $fvalue])">
      <A>
        <Field1><xsl:value-of select ="$fname"/></Field1>
        <Field2><xsl:value-of select="$fvalue"/></Field2>
      </A>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>
</code>```

ContentLicense: CC BY-SA 4.0

Title: XSLT: Ignore duplicates similar values

Body:
I am working on XSLT which has a logic to ignore duplicates using (MySegment/*[not(.=preceding::*)]).

Input:

<MySegment>
  <Field1>ABCD</Field1>
  <FIeld2>1</Field2>
</MySegment>
<MySegment>
  <Field1>ABCD123</Field1>
  <FIeld2>1</Field2>
</MySegment>

Here we have two distinct values, however since ABCD123 contains ABCD as well,its being treated as a duplicate entry. Can anyone advise.

Here is how my XSLT looks like:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

  <xsl:template match="/RecordsInp">

    <xsl:for-each select="ParentSegment">

      <xsl:for-each select="./MySegment/*[not(.=preceding::*)]">

          <Field1><xsl:value-of select ="name(.)"/></Field1>
          <Field2><xsl:value-of select="."/></Field2>

      </xsl:for-each>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

My input is:

<RecordsInp>
  <ParentSegment>
    <MySegment>
      <Field1>ABC</Field1>
      <Field2>A1</Field2>
    </MySegment>

    <MySegment>
      <Field1>ABC</Field1>
      <Field2>A1</Field2>
    </MySegment>

    <MySegment>
      <Field1>ABCDEF</Field1>
      <Field2>ABC</Field2>
    </MySegment>
  </ParentSegment>
</RecordsInp>

What I am getting is:

 <?xml version="1.0" encoding="UTF-8"?>

      <Field1>Field1</Field1>
      <Field2>ABC</Field2>

      <Field1>Field2</Field1>
      <Field2>A1</Field2>

      <Field1>Field1</Field1>
      <Field2>ABCDEF</Field2>

Notice I am not getting Field2=ABC in the last occurrence. Since Field2 never had ABC in previous occurrences, I need below XML:

<?xml version="1.0" encoding="UTF-8"?>

  <Field1>Field1</Field1>
  <Field2>ABC</Field2>

  <Field1>Field2</Field1>
  <Field2>A1</Field2>

  <Field1>Field1</Field1>
  <Field2>ABCDEF</Field2>

  <Field1>Field2</Field1>
  <Field2>ABC</Field2>

Body:
Your XPath expression ./MySegment/*[not(.=preceding::*)] selects those child elements of each of the context node's <MySegment> children whose string values do not match those of any element preceding them in document order.  Thus, the <Field2>ABC</Field2> is not reflected in the result because of the preceding <Field1>ABC</Field1> elements.

Evidently that's a broader condition than you intend; as I understand it, you want to compare only with preceding elements having the same name.  That's a bit tricky to express in pure XPath; it would be easier to handle with a stylesheet refactoring.  Gratuitous use of xsl:for-each suggests such a refactoring anyway.  Here's a reasonable way to go about it:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/RecordsInp/ParentSegment/MySegment/*">
    <!-- bind the context node's name and value to variables: -->
    <xsl:variable name="fname" select="name()"/>
    <xsl:variable name="fvalue" select="string(.)"/>

    <!-- here's the test you seem really to want: -->
    <xsl:if test="not(preceding::*[name() = $fname and string() = $fvalue])">
      <A>
        <Field1><xsl:value-of select ="$fname"/></Field1>
        <Field2><xsl:value-of select="$fvalue"/></Field2>
      </A>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>


问:
JS enable & disable microphone
I'm trying to enable and disable my microphone on press but I can't really get it to work, I'm new to javascript.

Thank you for help.. PS Im using webrtc

```<code>navigator.getUserMedia({"audio":USE_AUDIO},
                function(stream) { /* user accepted access to a/v */
                    console.log("Access granted to audio/video");
                    local_media_stream = stream;
                    var local_media = $("<audio>");
                    local_media.attr("autoplay", "autoplay");
                    local_media.attr("muted", "true"); /* always mute ourselves by default */
                    local_media.attr("controls", "");
                    $('body').append(local_media);
                    attachMediaStream(local_media[0], stream);

                    if (callback) callback();

                    $('.testHold').mousedown(function() {
                      $('.tracker').html("holding holding holding");
                          local_media.attr("muted", "false");

                    }).bind('mouseup mouseleave', function() {
                      $('.tracker').text('Left the button');
                        local_media.attr("muted", "true");

                    });

                }
</code>```

答:
```<code>  $('.testHold').mousedown(function() {
                      $('.tracker').html("holding holding holding");
                      stream.getAudioTracks()[0].enabled = true;

                    }).bind('mouseup mouseleave', function() {
                      $('.tracker').text('Left the button');
                        stream.getAudioTracks()[0].enabled = false;

                    });
</code>```

Title: JS enable & disable microphone

Body:
I'm trying to enable and disable my microphone on press but I can't really get it to work, I'm new to javascript.

Thank you for help.. PS Im using webrtc

navigator.getUserMedia({"audio":USE_AUDIO},
                function(stream) { /* user accepted access to a/v */
                    console.log("Access granted to audio/video");
                    local_media_stream = stream;
                    var local_media = $("<audio>");
                    local_media.attr("autoplay", "autoplay");
                    local_media.attr("muted", "true"); /* always mute ourselves by default */
                    local_media.attr("controls", "");
                    $('body').append(local_media);
                    attachMediaStream(local_media[0], stream);

                    if (callback) callback();

                    $('.testHold').mousedown(function() {
                      $('.tracker').html("holding holding holding");
                          local_media.attr("muted", "false");

                    }).bind('mouseup mouseleave', function() {
                      $('.tracker').text('Left the button');
                        local_media.attr("muted", "true");

                    });

                }


问:
Viewing changes to deleted files in git
Let's say that when I branch off from master, there's a file colors.txt on the master branch of my repo with these contents:

```<code>red
green
blue
yellow
</code>```

I then branch off into my-branch, in which I make the following changes:

Delete colors.txt

Add red.txt with these contents:

```<code>red
</code>```

Add green.txt with these contents:

```<code>green
</code>```

Add blue.txt with these contents:

```<code>blue
</code>```

Add yellow.txt with these contents:

```<code>yellow
</code>```

Now, there have been some changes on master that I need, so I want to merge. However, someone has also changed colors.txt to:

```<code>red
green
blue
yellow
orange
purple
</code>```

During my merge, the only information I get is that I deleted the file colors.txt, so how can I see the changes that have been to the file on master so I can appropriately resolve the conflict (in this case, by adding the files orange.txt and purple.txt)?

答:
You can show all changes done to that file on master using this command:

```<code>git diff HEAD...master -- colors.txt
</code>```

This should lead to this output in your case:

```<code>red
green
blue
yellow
+orange
+purple
</code>```

Using three dots for git diff will show the changes of all commits which are parents of the second referenced commit but not of the first referenced commit. Therefore, using this you will see all changes which would be merged if the file had not been deleted.

By using -- colors.txt the changes shown by git diff are limited to that file.

A more generic version of that command would be

```<code>git diff HEAD...MERGE_HEAD -- colors.txt
</code>```

MERGE_HEAD is always set to the merged commit, thus it can replace the merged branch name. Using this you could even set up an alias to reuse this command:

```<code>git config --global alias.merge-diff-theirs "diff HEAD...MERGE_HEAD"
</code>```

Afterwards you can just do

```<code>git merge-diff-theirs -- colors.txt
</code>```

Title: Viewing changes to deleted files in git

Body:
Let's say that when I branch off from master, there's a file colors.txt on the master branch of my repo with these contents:

red
green
blue
yellow

I then branch off into my-branch, in which I make the following changes:

Delete colors.txt

Add red.txt with these contents:

red

Add green.txt with these contents:

green

Add blue.txt with these contents:

blue

Add yellow.txt with these contents:

yellow

Now, there have been some changes on master that I need, so I want to merge. However, someone has also changed colors.txt to:

red
green
blue
yellow
orange
purple

During my merge, the only information I get is that I deleted the file colors.txt, so how can I see the changes that have been to the file on master so I can appropriately resolve the conflict (in this case, by adding the files orange.txt and purple.txt)?

Body:
You can show all changes done to that file on master using this command:

git diff HEAD...master -- colors.txt

This should lead to this output in your case:

red
green
blue
yellow
+orange
+purple

Using three dots for git diff will show the changes of all commits which are parents of the second referenced commit but not of the first referenced commit. Therefore, using this you will see all changes which would be merged if the file had not been deleted.

By using -- colors.txt the changes shown by git diff are limited to that file.

A more generic version of that command would be

git diff HEAD...MERGE_HEAD -- colors.txt

MERGE_HEAD is always set to the merged commit, thus it can replace the merged branch name. Using this you could even set up an alias to reuse this command:

git config --global alias.merge-diff-theirs "diff HEAD...MERGE_HEAD"

Afterwards you can just do

git merge-diff-theirs -- colors.txt


问:
How to create a list of string in nth position of every line in Python
What would be a pythonic way to create a list of (to illustrate with an example) the fifth string of every line of a text file, assuming it ressembles something like this:

12, 27.i, 3, 6.7, Hello, 438

In this case, the script would add "Hello" (without quotes) to the list.

In other words (to generalize), with an input "input.txt", how could I get a list in python that takes the nth string (n being a defined number) of every line?

Many thanks in advance!

答:
If its a text file it can be as simple as:</p>

```<code>with open(my_file, 'r') as f:
    mylist = [line.split(',')[4] for line in f]  # adds the 5th element of split to my_list
</code>```

Body:
If its a text file it can be as simple as:

with open(my_file, 'r') as f:
    mylist = [line.split(',')[4] for line in f]  # adds the 5th element of split to my_list


问:
conflicting ruby gems
I need to use two gems in my project that both claim the PDF namespace:  pdf-reader and htmldoc.

Is there any way to get them to play nice together?  The only way I can think of is to rewrite my own version of htmldoc to give it a different namespace.

答: I've heard of a new piece of functionality called refinements. It's designed to avoid two different monkeypatches affecting the same class causing problems, but I'd see if it could help with your problem.</p>

Title: conflicting ruby gems


问:
SharePoint 2013 - InfoPath form using REST API and cannot get the data
Environment: SharePoint 2013 Online & InfoPath form 2013

I'm try to make a data collection using REST API and using a button to trigger the action.

When I preview the form & press the button first time, I get the error as below

The query cannot be run for the following DataObject: Document in Dev
InfoPath cannot run the specified query.

The file is not a valid XML file.

Some form data cannot be retrieved bacause InfoPath is operating offline mode.
Form elements, such as drop-down lists, may be blank. Ensure that you have network connectivity and that InfoPath is online mode.

When I Click the button second time , it can be receive the data.

When I publish the form to SharePoint, I will get the error every time when i press the button

XML data that is required for this form to function correctly cannot be found.

An entry has been added to the Windows event log of the server.

Log ID:5566

Any Idea??

I can get the correct data when I directly access the REST API link.

答:
Same error (400 bad request) cost me much time. My working solution is adding NoRedirect=true at the end of my URL:

```<code>http://server/qa/_vti_bin/owssvr.dll?Cmd=Display&List={***E885}&XMLDATA=TRUE&noredirect=true
</code>```

Ref:
https://sajiviswam.wordpress.com/2012/03/20/the-form-cannot-run-the-specified-query-in-infopath-2007-forms-migrated-to-sharepoint-2010/#comment-564

Body:
Same error (400 bad request) cost me much time. My working solution is adding NoRedirect=true at the end of my URL:

http://server/qa/_vti_bin/owssvr.dll?Cmd=Display&List={***E885}&XMLDATA=TRUE&noredirect=true

Ref:
https://sajiviswam.wordpress.com/2012/03/20/the-form-cannot-run-the-specified-query-in-infopath-2007-forms-migrated-to-sharepoint-2010/#comment-564


问:
haproxy http-response replace
I am trying to replace this part of the string in the response header "abc,def,ghi,jkl" . Please note this value is NOT static.

```<code>  My-Customer-Header: My-Test:abc,def,ghi,jkl:12345
</code>```

Using this regex I am able to grab strings between the colon. i.e. "My-Test" & "12345" https://regex101.com/r/Ebkzjb/1

Here is what i am trying to replace value..

```<code>  My-Test:XYZ:12345
</code>```

Here is my haproxy config line..

```<code>  http-response replace-value  My-Customer-Header (.*)((?<=:)(.*)(?=:))(.*) \1XYZ\2
</code>```

Syntactically, haproxy config is loading but i may not have the regex properly. Can you please help with haproxy config for replace the value.

答:
This is working for me </p>

```<code> http-response replace-header My-Customer-Header (.*)((?<=:)(.*)(?=:))(.*) \1XYZ\4
</code>```

Title: haproxy http-response replace

Body:
I am trying to replace this part of the string in the response header "abc,def,ghi,jkl" . Please note this value is NOT static.

  My-Customer-Header: My-Test:abc,def,ghi,jkl:12345

Using this regex I am able to grab strings between the colon. i.e. "My-Test" & "12345" https://regex101.com/r/Ebkzjb/1

Here is what i am trying to replace value..

  My-Test:XYZ:12345

Here is my haproxy config line..

  http-response replace-value  My-Customer-Header (.*)((?<=:)(.*)(?=:))(.*) \1XYZ\2

Syntactically, haproxy config is loading but i may not have the regex properly. Can you please help with haproxy config for replace the value.

Body:
This is working for me

 http-response replace-header My-Customer-Header (.*)((?<=:)(.*)(?=:))(.*) \1XYZ\4


问:
Is it possible to share audio input (Microphone) stream in Android?
I am writing an application that runs as a background service recording and analyzing audio recorded from the microphone. When my app is running I can't use other apps that use the microphone (e.g. phone, voice recording, etc...).

My question is - Is there a way to share the microphone stream in Android? Maybe by using the NDK? If not, is it possible to receive an indication (e.g. a BroadcastIntent) that another app is requiring the microphone?

答: Recording audio/video, while other applications are running , is possible. I've done it in Sony Xperia Z1, continuously recorded videos and calls with a downloaded screen recorder. However, I do believe that this was a glitch of some sort, as it stopped being able to record after some time (about 2 months)and started showing an error which says that the microphone is being used by another application...


问:
How can I enable the users delete only the objects they create in Django?
They can do a bypass for a link by putting the post ID. I do not know how to solve it.

/borrar/id

Template button:

```<code>{% if user == post.user %}
    <a class="close pull-right" href="{% url 'post_borrar' post.id %}"><span aria-hidden="true">×</span></a>
{% endif %}
</code>```

Template posts/posts_mod_borrar.html:

```<code><form method="post">
    {% csrf_token %}
    ¿Estás seguro que deseas borrar el post "{{ object }}"?
    <input type="submit" value="Submit" />
</form>
</code>```

views.py

```<code>class PostDeleteView(generic.DeleteView):
    model = Post
    template_name = 'posts/posts_mod_borrar.html'
    success_url = reverse_lazy('timeline')
</code>```

model.py

```<code>class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    texto = models.CharField(max_length=200)
    imagen = models.ImageField(upload_to='posts', blank=True)
    video = models.URLField(blank=True)
    creado = models.DateTimeField(auto_now_add=True)
    actualizado = models.DateTimeField(auto_now=True)

class Meta:
    ordering = ["-creado"]

def __str__(self):
    return self.texto
</code>```

答:
You may check if obj.user is the request.user in the dispatch method:

```<code>from django.core.exceptions import PermissionDenied

class PostDeleteView(generic.DeleteView):
    ...

    def user_passes_test(self, request):
        if request.user.is_authenticated():
            self.object = self.get_object()
            return self.object.user == request.user
        return False

    def dispatch(self, request, *args, **kwargs):
        if not self.user_passes_test(request):
            raise PermissionDenied
        return super(PostDeleteView, self).dispatch(
            request, *args, **kwargs)
</code>```

If the user doesn't pass user_passes_test PermissionDenied will be raised

Body:
They can do a bypass for a link by putting the post ID. I do not know how to solve it.

/borrar/id

Template button:

{% if user == post.user %}
    ×
{% endif %}

Template posts/posts_mod_borrar.html:

<form method="post">
    {% csrf_token %}
    ¿Estás seguro que deseas borrar el post "{{ object }}"?
    <input type="submit" value="Submit" />
</form>

views.py

class PostDeleteView(generic.DeleteView):
    model = Post
    template_name = 'posts/posts_mod_borrar.html'
    success_url = reverse_lazy('timeline')

model.py

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    texto = models.CharField(max_length=200)
    imagen = models.ImageField(upload_to='posts', blank=True)
    video = models.URLField(blank=True)
    creado = models.DateTimeField(auto_now_add=True)
    actualizado = models.DateTimeField(auto_now=True)

class Meta:
    ordering = ["-creado"]

def __str__(self):
    return self.texto

Body:
You may check if obj.user is the request.user in the dispatch method:

from django.core.exceptions import PermissionDenied

class PostDeleteView(generic.DeleteView):
    ...

    def user_passes_test(self, request):
        if request.user.is_authenticated():
            self.object = self.get_object()
            return self.object.user == request.user
        return False

    def dispatch(self, request, *args, **kwargs):
        if not self.user_passes_test(request):
            raise PermissionDenied
        return super(PostDeleteView, self).dispatch(
            request, *args, **kwargs)

If the user doesn't pass user_passes_test PermissionDenied will be raised


问:
how to fix my angular 4 routing
I'm kind of new in the Angular 4 world and I came across this error when I want to route to /moviegroup/:id. For some reason I can't make it to work

app.routes.ts

```<code>import { Routes, RouterModule, PreloadAllModules } from '@angular/router';
import { MovieComponent } from '.é/movie/movie.component';
import { WizardComponent } from './wizard/wizard.component';

const routes: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'wizard', component: WizardComponent, pathMatch: 'full' },
    {
        path: 'moviegroup',
        children: [
            { path: 'moviegroup/:id', component: MovieComponent, pathMatch: 'full' }
        ]
    }
];

export const routing = RouterModule.forRoot(routes, { preloadingStrategy:
PreloadAllModules });
</code>```

I can navigate to http://localhost/wizard, http://localhost/moviegroup but not to http://localhost/moviegroup/ecf84479-c23c-1702-8440-b252591364ec. I get the following error:

```<code>ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'moviegroup/ecf84479-c23c-1702-8440-b252591364ec'
Error: Cannot match any routes. URL Segment: 'moviegroup/ecf84479-c23c-1702-8440-b252591364ec'
</code>```

Here is my file structure:

Any idea what I did wrong? If more info is required let me know!

Thanks, Reggi

答:
Remove moviegroup from the child path:

```<code>{
  path: 'moviegroup',
  children: [
    { path: ':id', component: MovieComponent }
  ]
}
</code>```

And also you don't need to include pathMatch: 'full' anywhere other than on empty route path with redirectTo.

Title: how to fix my angular 4 routing

Body:
I'm kind of new in the Angular 4 world and I came across this error when I want to route to /moviegroup/:id. For some reason I can't make it to work

app.routes.ts

import { Routes, RouterModule, PreloadAllModules } from '@angular/router';
import { MovieComponent } from '.é/movie/movie.component';
import { WizardComponent } from './wizard/wizard.component';

const routes: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'wizard', component: WizardComponent, pathMatch: 'full' },
    {
        path: 'moviegroup',
        children: [
            { path: 'moviegroup/:id', component: MovieComponent, pathMatch: 'full' }
        ]
    }
];

export const routing = RouterModule.forRoot(routes, { preloadingStrategy:
PreloadAllModules });

I can navigate to http://localhost/wizard, http://localhost/moviegroup but not to http://localhost/moviegroup/ecf84479-c23c-1702-8440-b252591364ec. I get the following error:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'moviegroup/ecf84479-c23c-1702-8440-b252591364ec'
Error: Cannot match any routes. URL Segment: 'moviegroup/ecf84479-c23c-1702-8440-b252591364ec'

Here is my file structure:

Any idea what I did wrong? If more info is required let me know!

Thanks, Reggi

Body:
Remove moviegroup from the child path:

{
  path: 'moviegroup',
  children: [
    { path: ':id', component: MovieComponent }
  ]
}

And also you don't need to include pathMatch: 'full' anywhere other than on empty route path with redirectTo.


问:
Python class doesn't change class variable
Hi I am writing a simple script with multiple processes. Here is class that I am using:

```<code>class WorkerProcess(multiprocessing.Process):
    def __init__(self, batch):
        multiprocessing.Process.__init__(self)
        self.batch = batch
        self.data_frame = pd.DataFrame()

    def run(self):
        temp = []
        for item in self.batch:
            temp.append(item)
        self.data_frame = pd.DataFrame(temp, columns=temp[0].keys())
        print('empty: ', self.data_frame.empty) # everything is fine
</code>```

Later I start processes and join them:

```<code>    workers = []
    for i in range(max_processes):
        try:
            batch = batches_data.pop()
            workers.append(WorkerProcess(batch))
        except Exception as e:
            pass

    for worker in workers:
        worker.start()

    for worker in workers:
        worker.join()

    for worker in workers:
        print(worker.data_frame) # it is empty
</code>```

When I print data_frame it is empty even though is was changed in run() function.

What am I missing?

答:
Processes do not share their memory address space. Thanks to Linux process forking strategy, you usually get the feeling the child process share its memory with the parent but in reality it's a copy.

This means that changes in the child process will not be reflected in its parent (or in any other process).

The Python multiprocessing library offers several mechanisms to share memory between processes.

Body:
Hi I am writing a simple script with multiple processes. Here is class that I am using:

class WorkerProcess(multiprocessing.Process):
    def __init__(self, batch):
        multiprocessing.Process.__init__(self)
        self.batch = batch
        self.data_frame = pd.DataFrame()

    def run(self):
        temp = []
        for item in self.batch:
            temp.append(item)
        self.data_frame = pd.DataFrame(temp, columns=temp[0].keys())
        print('empty: ', self.data_frame.empty) # everything is fine

Later I start processes and join them:

    workers = []
    for i in range(max_processes):
        try:
            batch = batches_data.pop()
            workers.append(WorkerProcess(batch))
        except Exception as e:
            pass

    for worker in workers:
        worker.start()

    for worker in workers:
        worker.join()

    for worker in workers:
        print(worker.data_frame) # it is empty

When I print data_frame it is empty even though is was changed in run() function.

What am I missing?


问:
Return FileName Only when using OpenFileDialog
I am using the following method to browse for a file:

```<code>    OpenFileDialog.ShowDialog()
    PictureNameTextEdit.Text = OpenFileDialog.FileName
</code>```

Is there a way get ONLY the file name?

The FileName method returns the entire path and file name.

i.e. I want Foo.txt instead of C:\SomeDirectory\Foo.txt

答:
if you want just the selected name without Extension you can try this code

```<code>Imports System.IO

PictureNameTextEdit.Text = Path.GetFileNameWithoutExtension(OpenFileDialog1.FileName)
</code>```

thanx

OwnerDisplayName: Gerhard Weiss

Body:
I am using the following method to browse for a file:

    OpenFileDialog.ShowDialog()
    PictureNameTextEdit.Text = OpenFileDialog.FileName

Is there a way get ONLY the file name?

The FileName method returns the entire path and file name.

i.e. I want Foo.txt instead of C:\SomeDirectory\Foo.txt

Body:
if you want just the selected name without Extension you can try this code

Imports System.IO

PictureNameTextEdit.Text = Path.GetFileNameWithoutExtension(OpenFileDialog1.FileName)

thanx


问:
Windows Server 2012, This site can’t be reached "" server DNS address could not be found
I have my website deployed in Windows Azure Virtual machine and configured in IIS server. When i do a local explore from the web server its working fine with the local host and i can able to see my website and navigate it properly.

But when i try to access it from public network with the public DNS which azure provides I am getting the error as below.

This site can’t be reached

www.f5debug.eastasia.cloudapp.azure.com’s server DNS address could not be found.
Go to http://www.azure.com/
Search Google for f5debug east asia cloudapp azure Home
ERR_NAME_NOT_RESOLVED

If I can deploy a simple website (sample website with asp.net) and try to access with the same DNS its working fine.

I am not sure as this website is working perfect in a hosting provider (databasemart.com) and when i try to move it to azure its getting this issue.

Kindly help me with some pointers if possible.

Thanks

答:
This is not a DNS issue. The DNS record f5debug.eastasia.cloudapp.azure.com is the Azure-provided DNS record for this service and it is resolving correctly to the VIP listed above.

Whatever the issue here, it is occuring after the client is hitting your service - after the Azure-provided DNS record is resolved.

As others have stated above, this is likely a service-side redirect to www.f5debug.eastasia.cloudapp.azure.com. Hopefully knowing that the DNS is working fine will allow you to focus your investigations on your deployed serivce.

Regards,
Stephen Malone - Azure Networking


问:
Spring Boot 1.5.2 Startup: java.lang.NoSuchMethodError: javax.servlet.ServletContext.getVirtualServerName()Ljava/lang/String;
I've been getting the following error from version 1.5.2 of Spring Boot. In the trace its pulling tomcat version 8.5.11, and I am using javax.servlet version 3.1. Everywhere I look has said that version 3.1 should be the fix to the issue, but I still have it, even after deleting my repository under .m2 directory.

```<code>    java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122) [na:1.8.0_66]
    at java.util.concurrent.FutureTask.get(FutureTask.java:192) [na:1.8.0_66]
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:939) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:872) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_66]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_66]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_66]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_66]
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167) [tomcat-embed-core-8.5.11.jar:8.5.11]
    ... 6 common frames omitted
Caused by: org.apache.catalina.LifecycleException: Failed to start component [Pipeline[StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5099) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.11.jar:8.5.11]
    ... 6 common frames omitted
Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.authenticator.NonLoginAuthenticator[]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardPipeline.startInternal(StandardPipeline.java:170) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.11.jar:8.5.11]
    ... 8 common frames omitted
    Caused by: java.lang.NoSuchMethodError: javax.servlet.ServletContext.getVirtualServerName()Ljava/lang/String;
    at org.apache.catalina.authenticator.AuthenticatorBase.startInternal(AuthenticatorBase.java:1137) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.11.jar:8.5.11]
    ... 10 common frames omitted
</code>```

Here is the list of dependencies I am importing:

```<code>   <properties>
    <tomcat.version>8.5.11</tomcat.version>
</properties>
<dependencies>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.4-1206-jdbc42</version>
</dependency>
<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
    <version>2.0.10.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>4.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>2.2.1</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.6.0</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.1</version>
</dependency>
</dependencies>
</code>```

答:
Try to change

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>
</code>```

to

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>
</code>```

Body:
I've been getting the following error from version 1.5.2 of Spring Boot. In the trace its pulling tomcat version 8.5.11, and I am using javax.servlet version 3.1. Everywhere I look has said that version 3.1 should be the fix to the issue, but I still have it, even after deleting my repository under .m2 directory.

    java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122) [na:1.8.0_66]
    at java.util.concurrent.FutureTask.get(FutureTask.java:192) [na:1.8.0_66]
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:939) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:872) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_66]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_66]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_66]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_66]
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167) [tomcat-embed-core-8.5.11.jar:8.5.11]
    ... 6 common frames omitted
Caused by: org.apache.catalina.LifecycleException: Failed to start component [Pipeline[StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5099) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.11.jar:8.5.11]
    ... 6 common frames omitted
Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.authenticator.NonLoginAuthenticator[]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardPipeline.startInternal(StandardPipeline.java:170) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.11.jar:8.5.11]
    ... 8 common frames omitted
    Caused by: java.lang.NoSuchMethodError: javax.servlet.ServletContext.getVirtualServerName()Ljava/lang/String;
    at org.apache.catalina.authenticator.AuthenticatorBase.startInternal(AuthenticatorBase.java:1137) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.11.jar:8.5.11]
    ... 10 common frames omitted

Here is the list of dependencies I am importing:

   <properties>
    <tomcat.version>8.5.11</tomcat.version>
</properties>
<dependencies>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.4-1206-jdbc42</version>
</dependency>
<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
    <version>2.0.10.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>4.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>2.2.1</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.3.RELEASE</version>
</dependency>

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.6.0</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.1</version>
</dependency>
</dependencies>

Body:
Try to change

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>

to

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>


问:
Why is my for loop in C working correctly?
So I have this code I created for CS50 pset1 Mario problem. The code is behaving correctly and is doing exactly what it is supposed to do, but I don't understand one of the parts. Why is it behaving this way.

Here's the code I have written in C:

```<code>  #include <cs50.h>
#include <stdio.h>

int main (void){
int height, row, space, hash;

    do {
        printf("Height: ");
        height = get_int();
    } while(height<0 || height>23);

    for (row=0; row<height; row++){

        for (space=height-(row+1); space>0; space--){
            printf("-");
        }

        for (hash=height-row; hash<=height; hash++){
            printf("#");
        }

        printf("#\n");
    }

}
</code>```

So for example when the user enters 3 as the Height, I get

```<code>--##
-###
####
</code>```

What I don't understand why it is not:

```<code>--####
-###
##
</code>```

This part is what is throwing me off:

```<code>for (hash=height-row; hash<=height; hash++){
            printf("#");
        }
</code>```

If hash = height-row then shouldn't it be 3-0=3 and have it print the hash sign 3 times? Then 3-1=2 and print it twice, and so on? Why is it doing it in reverse?

Can someone please explain what's wrong with my logic?

答:
Let's break down the for loop:

```<code>     for (hash=height-row; hash<=height; hash++){
        printf("#");
        }
</code>```

When height is 3:

```<code>for row = 0 (less than 3):
    for (hash = 3 - 0; hash <= 3 (true); hash++ (hash will be 4 next iteration))
        print #
</code>```

Next,

```<code>    for (has = 4; hash <= 3 (false); hash ++)
        (does not print #)
</code>```

and finally,

```<code>    print #\n
</code>```

You get two hashes total, e.g.

```<code>--##
</code>```

Body:
So I have this code I created for CS50 pset1 Mario problem. The code is behaving correctly and is doing exactly what it is supposed to do, but I don't understand one of the parts. Why is it behaving this way.

Here's the code I have written in C:

  #include <cs50.h>
#include <stdio.h>

int main (void){
int height, row, space, hash;

    do {
        printf("Height: ");
        height = get_int();
    } while(height<0 || height>23);

    for (row=0; row<height; row++){

        for (space=height-(row+1); space>0; space--){
            printf("-");
        }

        for (hash=height-row; hash<=height; hash++){
            printf("#");
        }

        printf("#\n");
    }

}

So for example when the user enters 3 as the Height, I get

--##
-###
####

What I don't understand why it is not:

--####
-###
##

This part is what is throwing me off:

for (hash=height-row; hash<=height; hash++){
            printf("#");
        }

If hash = height-row then shouldn't it be 3-0=3 and have it print the hash sign 3 times? Then 3-1=2 and print it twice, and so on? Why is it doing it in reverse?

Can someone please explain what's wrong with my logic?

Body:
Let's break down the for loop:

     for (hash=height-row; hash<=height; hash++){
        printf("#");
        }

When height is 3:

for row = 0 (less than 3):
    for (hash = 3 - 0; hash <= 3 (true); hash++ (hash will be 4 next iteration))
        print #

Next,

    for (has = 4; hash <= 3 (false); hash ++)
        (does not print #)

and finally,

    print #\n

You get two hashes total, e.g.

--##


问:
Array.reduce mutating state outside is not recommended?
Why is mutating variables outside .reduce() method considered bad practice? In the example below I am mutating a variable declared outside from inside the reduce method. Why is it not recommended to do so?

function balanceParens(string) {
    let max = 0;
    let res = string.split("").reduce((counter, char) => {
        // Handle if parens open and close out of order
        if (counter < 0) {
          return counter;
        }
        // Add 1 for each open in order
        if (char === "(") {
          if(++counter > max) {
            max = counter;
          }
          return counter;
        }
        // subtract 1 for each close in order
        if (char === ")") {
          return --counter;
        }
        // handle use case if char is not a paren
        return counter;
    }, 0);
    console.log("Max depth was :", max);
    return !res;
}
console.log(balanceParens("((()(((())))))((((()))))"));```

答:
See @JordanRunning comment:

"If you do that, why bother using reduce at all? If your output is via side-effects you might as well be using forEach"

I was about to say the same. And here is a version of the function without an external dependency:

function balanceParens(string) {
 let res = string.split("").reduce((state, char) => {
  // Handle if parens open and close out of order
  if (state.counter < 0) {
   return state;
  }
  // Add 1 for each open in order
  if (char === "(") {
   if (++state.counter > state.max) {
    state.max = state.counter;
   }
   return state;
  }
  // subtract 1 for each close in order
  if (char === ")") {
   state.counter = --state.counter;
   return state;
  }
  // handle use case if char is not a paren
  return state;
 }, {max: 0, counter: 0});
 console.log("Max depth was :", res.max);
 return !res.counter;
}

console.log(balanceParens("((()(((())))))((((()))))"));```


问:
Maintain taskbar visibility with WPF Window.WindowStyle = none
I am developing a WPF application. I completely got rid of the standard windows border and created my own by setting the WindowStyle to None and AllowsTransparency to true. The only problem is that when the window is maximized it fills the entire screen, covering the taskbar. Is there any way to create your own borders without this happening?</p>

答:
Much easier way, in your window constructor just set

```<code>this.MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
</code>```

and the window will not cover the task bar.

Body:
Much easier way, in your window constructor just set

this.MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;

and the window will not cover the task bar.


问:
how to use restartloader in android with listview
i get data from Sqlite using Contnet provider in listview .. when new record insert in listview.. record show in listview without refreshing activity... thats why i have used restartloader but it not work for me

getAllContacts() in Database i fetch total record from database

```<code>    public Cursor getAllPatients(){

    return db.query(TABLE_NAME, new String[] { TAG_ID, TAG_NAME , TAG_AGE, TAG_CITY, TAG_MOB } ,
            null, null, null, null,null);
}
</code>```

this is content provider

```<code>    @Nullable
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    if (uriMatcher.match(uri)==PATIENTS){
        myDb.getAllPatients().setNotificationUri(getContext().getContentResolver(), uri);
        return myDb.getAllPatients();
    }else {
        return null;
    }
}
</code>```

and this is MainActivity

```<code>    mAdapter = new SimpleCursorAdapter(getContext(),R.layout.status_item_layout,null,new String[]{
            myDb.TAG_ID,myDb.TAG_NAME,myDb.TAG_AGE,myDb.TAG_CITY,myDb.TAG_MOB},
            new int[]{R.id.tv_status_id,R.id.tv_status_name,R.id.tv_status_age,R.id.tv_status_city,R.id.tv_status_mob,},
            0);

    if(getLoaderManager().getLoader(0) == null){
        getLoaderManager().initLoader(0, null, this).forceLoad();
    }else{
        getLoaderManager().restartLoader(0, null, this).forceLoad();
    }

    listView.setAdapter(mAdapter);

    apiInterface = APIClient.getApiClient().create(ApiInterface.class);

    return linearLayout;
}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    Uri uri = Patients.CONTENT_URI;
    return new CursorLoader(getContext(),uri,null,null,null,null);

}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
     mAdapter.swapCursor(data);

}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
    mAdapter.swapCursor(null);
   }
</code>```

i have not clear know about restartLoader() please tell me where i am doing wrong?

答:
Just like @psking commented, restartLoader() won't be necessary for updating changes in a list of cursor data since the process is replaced by Cursor's setNotificationUri() and ContentResolver's notifyChange() methods when it comes to cursors with URIs. That said, what I would do is stick with initLoader() in your Activity to query the cursor data at runtime, and then use setNotificationUri() in your ContentProvider's query() method, and notifyChange() in your ContentProvider's insert() and update() methods to update cursor data in your list instantly as follows:

```<code>public class MyProvider extends ContentProvider {

    ...

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
                        String sortOrder) {

        ...

        // Registers to watch a content URI for changes. This can be the URI of a specific
        // data row (for example, "content://my_provider_type/23"), or a a generic URI for
        // a content type.
        cursor.setNotificationUri(getContext().getContentResolver(), uri);

        return cursor;
    }

    @Override
    public Uri insert(Uri uri, ContentValues contentValues) {

        ...

        // Notifies all listeners that the data has changed for the item content URI.
        getContext().getContentResolver().notifyChange(uri, null);

        // Returns the new URI with the ID (of the newly inserted row) appended at the end.
        return ContentUris.withAppendedId(uri, id);
    }

    @Override
    public int update(Uri uri, ContentValues contentValues, String selection,
                      String[] selectionArgs) {

        ...

        // Notifies all listeners that the data at the given URI has changed should at least one
        // row be updated.
        if (rowsUpdated != 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }

        return rowsUpdated;
    }
}
</code>```

Body:
i get data from Sqlite using Contnet provider in listview .. when new record insert in listview.. record show in listview without refreshing activity... thats why i have used restartloader but it not work for me

getAllContacts() in Database i fetch total record from database

    public Cursor getAllPatients(){

    return db.query(TABLE_NAME, new String[] { TAG_ID, TAG_NAME , TAG_AGE, TAG_CITY, TAG_MOB } ,
            null, null, null, null,null);
}

this is content provider

    @Nullable
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    if (uriMatcher.match(uri)==PATIENTS){
        myDb.getAllPatients().setNotificationUri(getContext().getContentResolver(), uri);
        return myDb.getAllPatients();
    }else {
        return null;
    }
}

and this is MainActivity

    mAdapter = new SimpleCursorAdapter(getContext(),R.layout.status_item_layout,null,new String[]{
            myDb.TAG_ID,myDb.TAG_NAME,myDb.TAG_AGE,myDb.TAG_CITY,myDb.TAG_MOB},
            new int[]{R.id.tv_status_id,R.id.tv_status_name,R.id.tv_status_age,R.id.tv_status_city,R.id.tv_status_mob,},
            0);

    if(getLoaderManager().getLoader(0) == null){
        getLoaderManager().initLoader(0, null, this).forceLoad();
    }else{
        getLoaderManager().restartLoader(0, null, this).forceLoad();
    }

    listView.setAdapter(mAdapter);

    apiInterface = APIClient.getApiClient().create(ApiInterface.class);

    return linearLayout;
}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    Uri uri = Patients.CONTENT_URI;
    return new CursorLoader(getContext(),uri,null,null,null,null);

}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
     mAdapter.swapCursor(data);

}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
    mAdapter.swapCursor(null);
   }

i have not clear know about restartLoader() please tell me where i am doing wrong?

Body:
Just like @psking commented, restartLoader() won't be necessary for updating changes in a list of cursor data since the process is replaced by Cursor's setNotificationUri() and ContentResolver's notifyChange() methods when it comes to cursors with URIs. That said, what I would do is stick with initLoader() in your Activity to query the cursor data at runtime, and then use setNotificationUri() in your ContentProvider's query() method, and notifyChange() in your ContentProvider's insert() and update() methods to update cursor data in your list instantly as follows:

public class MyProvider extends ContentProvider {

    ...

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
                        String sortOrder) {

        ...

        // Registers to watch a content URI for changes. This can be the URI of a specific
        // data row (for example, "content://my_provider_type/23"), or a a generic URI for
        // a content type.
        cursor.setNotificationUri(getContext().getContentResolver(), uri);

        return cursor;
    }

    @Override
    public Uri insert(Uri uri, ContentValues contentValues) {

        ...

        // Notifies all listeners that the data has changed for the item content URI.
        getContext().getContentResolver().notifyChange(uri, null);

        // Returns the new URI with the ID (of the newly inserted row) appended at the end.
        return ContentUris.withAppendedId(uri, id);
    }

    @Override
    public int update(Uri uri, ContentValues contentValues, String selection,
                      String[] selectionArgs) {

        ...

        // Notifies all listeners that the data at the given URI has changed should at least one
        // row be updated.
        if (rowsUpdated != 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }

        return rowsUpdated;
    }
}


问:
How to find the value of a dropdownlist using FindControl?
I am working on a website with VB.NET and ASP.NET. I currently have recurring DropDownLists for the user to provide input.

The design is recurring. These DropDownLists get their values from a database table, Everything with the Web interface is working except for writing these recurring values to the database - that is just to give you some background.

I have set the ID's of each DropDownList like so:

```<code>FrequencyList.ID = String.Concat("FreqList", DBReader(0))
</code>```

That is in a loop while reading the DatabaseReader.

This is what I'm having issues with (please note I simplified the code down to make it easier to read:

```<code>    Dim i As Integer
    DBCommand = New SqlCommand()

    DBCommand.Connection = DBConnection
    DBCommand.CommandType = Data.CommandType.StoredProcedure
    DBCommand.CommandText = "StoredProcedureName"
    DBConnection.Open()
    For i = 1 To AspectTableLength

        Dim ParamFrequencyID As SqlParameter = DBCommand.Parameters.Add("@nFrequencyID", SqlDbType.Int)
        ParamFrequencyID.Value = FindControl("FreqList" & Convert.ToString(i))
        ParamFrequencyID.Direction = ParameterDirection.Input
    Next
</code>```

The FindControl("FreqList" & Convert.ToString(i)) variable is incorrect because it does not access the value - and adding .SelectedItem.Value does not work.

答:
I got help from a developer.</p>

```<code>Dim MyControls As ControlCollection = Panel.Controls
        Dim Number As Integer 'this is the same as "DBReader(0)"

        For Each MyControl As Control In MyControls
            If MyControl.ID Is Nothing Then
            Else
                If MyControl.ID.StartsWith("Span") Then
                    Number = Replace(MyControl.ID, "Span", "")
                    Dim Freq As DropDownList = PanelMain.FindControl(“FreqList” & Number)

                    Dim ParamFrequencyID As SqlParameter = DBCommand.Parameters.Add("@nFrequencyID", SqlDbType.Int)
                    ParamFrequencyID.Value = Freq.SelectedIndex
                    ParamFrequencyID.Direction = ParameterDirection.Input

                    DBCommand.ExecuteNonQuery()
                    DBCommand.Parameters.Clear()
                End If
            End If
        Next

        DBConnection.Close()
</code>```

Body:
I am working on a website with VB.NET and ASP.NET. I currently have recurring DropDownLists for the user to provide input.

The design is recurring. These DropDownLists get their values from a database table, Everything with the Web interface is working except for writing these recurring values to the database - that is just to give you some background.

I have set the ID's of each DropDownList like so:

FrequencyList.ID = String.Concat("FreqList", DBReader(0))

That is in a loop while reading the DatabaseReader.

This is what I'm having issues with (please note I simplified the code down to make it easier to read:

    Dim i As Integer
    DBCommand = New SqlCommand()

    DBCommand.Connection = DBConnection
    DBCommand.CommandType = Data.CommandType.StoredProcedure
    DBCommand.CommandText = "StoredProcedureName"
    DBConnection.Open()
    For i = 1 To AspectTableLength

        Dim ParamFrequencyID As SqlParameter = DBCommand.Parameters.Add("@nFrequencyID", SqlDbType.Int)
        ParamFrequencyID.Value = FindControl("FreqList" & Convert.ToString(i))
        ParamFrequencyID.Direction = ParameterDirection.Input
    Next

The FindControl("FreqList" & Convert.ToString(i)) variable is incorrect because it does not access the value - and adding .SelectedItem.Value does not work.

Body:
I got help from a developer.

Dim MyControls As ControlCollection = Panel.Controls
        Dim Number As Integer 'this is the same as "DBReader(0)"

        For Each MyControl As Control In MyControls
            If MyControl.ID Is Nothing Then
            Else
                If MyControl.ID.StartsWith("Span") Then
                    Number = Replace(MyControl.ID, "Span", "")
                    Dim Freq As DropDownList = PanelMain.FindControl(“FreqList” & Number)

                    Dim ParamFrequencyID As SqlParameter = DBCommand.Parameters.Add("@nFrequencyID", SqlDbType.Int)
                    ParamFrequencyID.Value = Freq.SelectedIndex
                    ParamFrequencyID.Direction = ParameterDirection.Input

                    DBCommand.ExecuteNonQuery()
                    DBCommand.Parameters.Clear()
                End If
            End If
        Next

        DBConnection.Close()


问:
Convert time in seconds from the Epoch to day of the year?
I have a file filled with data, one column of which is seconds from the Epoch. For reference, an example value looks like this:

1498493536984926976

I need to convert it into a day of the year. What I have so far is this piece of code, which uses this reference to convert the date into a normal readable struct and then strftime to pull the day of the year from the struct:

```<code>time_t rawtime = stol(exploded_line[2]);
std::cout << rawtime << std::endl;
struct tm date;
date = *localtime( &rawtime );
char *buffer;
std::cout << 2 << std::endl;
strftime (buffer,sizeof(buffer),"%j",&date);
</code>```

However, this code SegFaults on the strftime line! I have no idea what is causing this. I have tried initializing buffer as

```<code>char buffer[80];
</code>```

and various other declarations but nothing seems to work. I've also tried ditching the buffer entirely and just using a std::string; that hasn't worked either.

Also, I am not partial to this method. If anyone else has a better method of getting the day of the year from an Epoch time, I will totally implement it.

Any help would be appreciated!

答:
Here's a potential solution:</p>

```<code>#include <string>
#include <iostream>
#include <ctime>

int main() {
  // Original value is a 64-bit unsigned integer representing the time in nanoseconds
  long long rawtime = 1498493536984926976LL;

  std::cout << rawtime << std::endl;

  // To convert from nanoseconds to seconds divide by a billion
  time_t epochtime = rawtime / 1000000000LL;
  std::cout << epochtime << std::endl;

  struct tm date;
  date = *std::localtime(&epochtime);

  // Uses a fixed-length buffer for `strtftime`
  char buffer[256];
  std::cout << 2 << std::endl;
  strftime(buffer,sizeof(buffer),"%j",&date);

  std::cout << buffer << std::endl;
}
</code>```

Body:
I have a file filled with data, one column of which is seconds from the Epoch. For reference, an example value looks like this:

1498493536984926976

I need to convert it into a day of the year. What I have so far is this piece of code, which uses this reference to convert the date into a normal readable struct and then strftime to pull the day of the year from the struct:

time_t rawtime = stol(exploded_line[2]);
std::cout << rawtime << std::endl;
struct tm date;
date = *localtime( &rawtime );
char *buffer;
std::cout << 2 << std::endl;
strftime (buffer,sizeof(buffer),"%j",&date);

However, this code SegFaults on the strftime line! I have no idea what is causing this. I have tried initializing buffer as

char buffer[80];

and various other declarations but nothing seems to work. I've also tried ditching the buffer entirely and just using a std::string; that hasn't worked either.

Also, I am not partial to this method. If anyone else has a better method of getting the day of the year from an Epoch time, I will totally implement it.

Any help would be appreciated!

Body:
Here's a potential solution:

#include <string>
#include <iostream>
#include <ctime>

int main() {
  // Original value is a 64-bit unsigned integer representing the time in nanoseconds
  long long rawtime = 1498493536984926976LL;

  std::cout << rawtime << std::endl;

  // To convert from nanoseconds to seconds divide by a billion
  time_t epochtime = rawtime / 1000000000LL;
  std::cout << epochtime << std::endl;

  struct tm date;
  date = *std::localtime(&epochtime);

  // Uses a fixed-length buffer for `strtftime`
  char buffer[256];
  std::cout << 2 << std::endl;
  strftime(buffer,sizeof(buffer),"%j",&date);

  std::cout << buffer << std::endl;
}


问:
Vertically Scrolling a

I have a few nested  and I want to allow my deepest  to scroll vertically.

in CSS I have tried adding:

```<code>overflow-x: hidden; /* horizontal */
overflow-y: auto;  /* vertical */
</code>```

to the class I am assigning to the  but that does not seem to do it. Changing overflow-y: yes; does not work either.

How does one accomplish this. I want this  to scroll because it gets populated with MySQL data where the other div's just present selectable criteria to create the query and run it.

thoughts are appreciated.

Example:

```<code><div id="content">
    <div id="slidingDivKeynotePresentations">
        <!-- content here -->
    </div>
</div>
</code>```

My CSS:

```<code>#content {
    position: absolute;
    top: 0;
    left: 21%;
    margin: 26% 31% 1% 21%; /* Cater for Mac IE5 */
    /*\*/ margin: 0; /* Put back for all the rest */
    /*\*/ overflow: auto; /* no need for Mac IE5 to see this */
    overflow-x: hidden; /* horizontal */
    overflow-y: yes;  /* vertical */
}

#slidingDivKeynotePresentations {
    display: none;
    height: 600px;
    width: 600px;
    background-image: url('images/transwhite.png');
    border: 1px solid #3F4933;
    position: fixed;
    top: 100px;
    left: 290px; /*Set left value to WidthOfFrameDiv*/
    padding: 12px;
    overflow-x: hidden; /* horizontal */
    overflow-y: auto;  /* vertical */
 }
</code>```

答:
You might be looking for the overflow property; overflow-x and overflow-y are not supported by all browsers; they are new in CSS3

http://www.w3schools.com/css/pr_pos_overflow.asp

http://www.w3.org/TR/css3-box/#overflow

Title: Vertically Scrolling a <DIV>

Body:
I have a few nested  and I want to allow my deepest  to scroll vertically.

in CSS I have tried adding:

overflow-x: hidden; /* horizontal */
overflow-y: auto;  /* vertical */

to the class I am assigning to the  but that does not seem to do it. Changing overflow-y: yes; does not work either.

How does one accomplish this. I want this  to scroll because it gets populated with MySQL data where the other div's just present selectable criteria to create the query and run it.

thoughts are appreciated.

Example:

My CSS:

#content {
    position: absolute;
    top: 0;
    left: 21%;
    margin: 26% 31% 1% 21%; /* Cater for Mac IE5 */
    /*\*/ margin: 0; /* Put back for all the rest */
    /*\*/ overflow: auto; /* no need for Mac IE5 to see this */
    overflow-x: hidden; /* horizontal */
    overflow-y: yes;  /* vertical */
}

#slidingDivKeynotePresentations {
    display: none;
    height: 600px;
    width: 600px;
    background-image: url('images/transwhite.png');
    border: 1px solid #3F4933;
    position: fixed;
    top: 100px;
    left: 290px; /*Set left value to WidthOfFrameDiv*/
    padding: 12px;
    overflow-x: hidden; /* horizontal */
    overflow-y: auto;  /* vertical */
 }


问:
How to replace non-ASCII characters in a sequence?
Essentially, what this code does is:

Take an input.

Replace each sequence of characters whose length is greater than 2 with the number of times that character repeated and the character itself (e.g. jjjkkkkkllll = 3j5k4l). The input does not contain any numeric values.

Return the result.

The code:

```<code>private String replaceConsecutiveChars(String data) {
    char[] dataChars = data.toCharArray();

    int i = 0;
    int k = 0;
    Character charType = null;
    for(Character c : dataChars) {
        if(k == dataChars.length - 1 && i >= 2) {
            data = data.replace(repeat(String.valueOf(charType), ++i), (i + Character.toString(charType)));
            break;
        }

        if(i == 0) {
            charType = c;
            i++;
        }else if(c == charType) {
            i++;
        }else if(c != charType && i > 2) {
            data = data.replace(repeat(String.valueOf(charType), i), (i + Character.toString(charType)));

            i = 1;
            charType = c;
        }else if(c != charType && i <= 2) {
            i = 1;
            charType = c;
        }

        k++;
    }

    return data;
}

private String repeat(String s, int n) {
    return Stream.generate(() -> s).limit(n).collect(Collectors.joining(""));
}
</code>```

However, my implementation only seems to work with the limited-ASCII character set, but I am trying to get it work with the Unicode character set. For example:

The input ddddddddkkkkkpppp will correctly output 8d5k4p.

The input êêêêÌÌÌÌÌÌÌØØØ will incorrectly output êêêêÌÌÌÌÌÌÌØØØ

The input "rrrrrêêêêÌÌÌÌÌkkkkØØØ" will incorrectly output 5rêêêêÌÌÌÌÌ4kØØØ

Why is this?

In addition, is there a better way I could do this than the way I'm doing it right now?

答:
You are comparing instances of Character using ==, which will not work as expected because the operator compares object references instead of values.

A simple quick fix is to change the for-loop to:

```<code>for (char c : dataChars) {
}
</code>```

Notice the change of types (Character to char). This way charType is automatically unboxed to the primitive char when comparing it to c.

Another solution is to replace every c == charType with c.equals(charType) to not compare references, but values.

Body:
Essentially, what this code does is:

Take an input.

Replace each sequence of characters whose length is greater than 2 with the number of times that character repeated and the character itself (e.g. jjjkkkkkllll = 3j5k4l). The input does not contain any numeric values.

Return the result.

The code:

private String replaceConsecutiveChars(String data) {
    char[] dataChars = data.toCharArray();

    int i = 0;
    int k = 0;
    Character charType = null;
    for(Character c : dataChars) {
        if(k == dataChars.length - 1 && i >= 2) {
            data = data.replace(repeat(String.valueOf(charType), ++i), (i + Character.toString(charType)));
            break;
        }

        if(i == 0) {
            charType = c;
            i++;
        }else if(c == charType) {
            i++;
        }else if(c != charType && i > 2) {
            data = data.replace(repeat(String.valueOf(charType), i), (i + Character.toString(charType)));

            i = 1;
            charType = c;
        }else if(c != charType && i <= 2) {
            i = 1;
            charType = c;
        }

        k++;
    }

    return data;
}

private String repeat(String s, int n) {
    return Stream.generate(() -> s).limit(n).collect(Collectors.joining(""));
}

However, my implementation only seems to work with the limited-ASCII character set, but I am trying to get it work with the Unicode character set. For example:

The input ddddddddkkkkkpppp will correctly output 8d5k4p.

The input êêêêÌÌÌÌÌÌÌØØØ will incorrectly output êêêêÌÌÌÌÌÌÌØØØ

The input "rrrrrêêêêÌÌÌÌÌkkkkØØØ" will incorrectly output 5rêêêêÌÌÌÌÌ4kØØØ

Why is this?

In addition, is there a better way I could do this than the way I'm doing it right now?

Body:
You are comparing instances of Character using ==, which will not work as expected because the operator compares object references instead of values.

A simple quick fix is to change the for-loop to:

for (char c : dataChars) {
}

Notice the change of types (Character to char). This way charType is automatically unboxed to the primitive char when comparing it to c.

Another solution is to replace every c == charType with c.equals(charType) to not compare references, but values.