问:
int.Parse is not working with string value (System.FormatException: Input string was not in a correct format )
If a user inputs anything but a number I get Unhandled Exception:

System.FormatException: Input string was not in a correct format.

Can someone explain what I am doing wrong?

Here's my code C# .NET:

```<code>private static int WeightIFeMale()
{
    Console.WriteLine("How Much Do You Weigh?", Environment.NewLine);
    int femaleWeight = int.Parse(Console.ReadLine());

    if
        (0 >= femaleWeight && 80 <= femaleWeight)
    {
        Console.WriteLine("Damn, how much crack are you smoking?", Environment.NewLine);
    }
    else if
        (81 >= femaleWeight && 110 <= femaleWeight)
    {
        Console.WriteLine("What the ****, are you a midget *****?", Environment.NewLine);

    }
    else if
        (111 >= femaleWeight && 140 <= femaleWeight)
    {
        Console.WriteLine("Holy shit, I have some protein bar coupons you can have!", Environment.NewLine);

    }
    else if
        (141 >= femaleWeight && 160 <= femaleWeight)
    {
        Console.WriteLine("Bro you need to hit the Gym, ASAP!", Environment.NewLine);

    }
    else if
        (161 >= femaleWeight && 200 <= femaleWeight)
    {
        Console.WriteLine("Really!!!, can I hit the Gym with you?", Environment.NewLine);

    }
    else if
        (201 >= femaleWeight && 240 <= femaleWeight)
    {
        Console.WriteLine("Do you Have a small ****, Steroids are a mother @#$%^&&", Environment.NewLine);

    }
    else if
        (241 >= femaleWeight && 999 <= femaleWeight)
    {
        Console.WriteLine("My condolences!", Environment.NewLine);
    }
    else if
        (femaleWeight >= 1000)
    {
        Console.WriteLine("There is absolutely no way that you weigh {0} lbs, so stop ******* around!", femaleWeight, Environment.NewLine);
    }
    else
    {
        Console.Write("What the **** is {0} It has to be a number numb nuts, lets try that again!", Environment.NewLine);
        WeightIFeMale();
    }

    return femaleWeight;
}
</code>```

答:
Here when you providing value which is not seemed like a number value int.Parse() can't Parse it as INT. See this article Int32.Parse Method (String) and see the Exceptions table FormatException description. So, 1. better you have a try catch functionality. Try the following suggestion , it is working. 2. Also You can use the    int.TryParse method

Way 1. Remove this statement  int femaleWeight = int.Parse(Console.ReadLine()); of code with try catch statement.

```<code>   private static int WeightIFeMale()

        {
            Console.WriteLine("How Much Do You Weigh?", Environment.NewLine);
            //int femaleWeight = int.Parse(Console.ReadLine());
            string weigt_st = Console.ReadLine();
            int femaleWeight = 0;
            try
            {
                femaleWeight = int.Parse(weigt_st);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            if (0 >= femaleWeight && 80 <= femaleWeight)
            {
                Console.WriteLine("Damn, how much crack are you smoking?", Environment.NewLine);
            }
            else if (81 >= femaleWeight && 110 <= femaleWeight)
            {
                Console.WriteLine("What the ****, are you a midget *****?", Environment.NewLine);

            }

            else if (111 >= femaleWeight && 140 <= femaleWeight)
            {
                Console.WriteLine("Holy shit, I have some protein bar coupons you can have!", Environment.NewLine);

            }

            else if (141 >= femaleWeight && 160 <= femaleWeight)
            {
                Console.WriteLine("Bro you need to hit the Gym, ASAP!", Environment.NewLine);

            }
            else if (161 >= femaleWeight && 200 <= femaleWeight)
            {
                Console.WriteLine("Really!!!, can I hit the Gym with you?", Environment.NewLine);

            }
            else if
                (201 >= femaleWeight && 240 <= femaleWeight)
            {
                Console.WriteLine("Do you Have a small ****, Steroids are a mother @#$%^&&", Environment.NewLine);

            }
            else if
                (241 >= femaleWeight && 999 <= femaleWeight)
            {
                Console.WriteLine("My condolences!", Environment.NewLine);
            }
            else if
                (femaleWeight >= 1000)
            {
                Console.WriteLine("There is absolutely no way that you weigh {0} lbs, so stop ******* around!", femaleWeight, Environment.NewLine);
            }
            else
            {
                Console.Write("What the **** is {0} It has to be a number numb nuts, lets try that again!", Environment.NewLine);
                WeightIFeMale();
            }

            return femaleWeight;
        }
</code>```

Or Way 2. Remove this statement  int femaleWeight = int.Parse(Console.ReadLine()); of code with this one

```<code>   int femaleWeight = 0;
   int.TryParse(Console.ReadLine(), out femaleWeight);
</code>```

Body:
If a user inputs anything but a number I get Unhandled Exception:

System.FormatException: Input string was not in a correct format.

Can someone explain what I am doing wrong?

Here's my code C# .NET:

private static int WeightIFeMale()
{
    Console.WriteLine("How Much Do You Weigh?", Environment.NewLine);
    int femaleWeight = int.Parse(Console.ReadLine());

    if
        (0 >= femaleWeight && 80 <= femaleWeight)
    {
        Console.WriteLine("Damn, how much crack are you smoking?", Environment.NewLine);
    }
    else if
        (81 >= femaleWeight && 110 <= femaleWeight)
    {
        Console.WriteLine("What the ****, are you a midget *****?", Environment.NewLine);

    }
    else if
        (111 >= femaleWeight && 140 <= femaleWeight)
    {
        Console.WriteLine("Holy shit, I have some protein bar coupons you can have!", Environment.NewLine);

    }
    else if
        (141 >= femaleWeight && 160 <= femaleWeight)
    {
        Console.WriteLine("Bro you need to hit the Gym, ASAP!", Environment.NewLine);

    }
    else if
        (161 >= femaleWeight && 200 <= femaleWeight)
    {
        Console.WriteLine("Really!!!, can I hit the Gym with you?", Environment.NewLine);

    }
    else if
        (201 >= femaleWeight && 240 <= femaleWeight)
    {
        Console.WriteLine("Do you Have a small ****, Steroids are a mother @#$%^&&", Environment.NewLine);

    }
    else if
        (241 >= femaleWeight && 999 <= femaleWeight)
    {
        Console.WriteLine("My condolences!", Environment.NewLine);
    }
    else if
        (femaleWeight >= 1000)
    {
        Console.WriteLine("There is absolutely no way that you weigh {0} lbs, so stop ******* around!", femaleWeight, Environment.NewLine);
    }
    else
    {
        Console.Write("What the **** is {0} It has to be a number numb nuts, lets try that again!", Environment.NewLine);
        WeightIFeMale();
    }

    return femaleWeight;
}

Body:
Here when you providing value which is not seemed like a number value int.Parse() can't Parse it as INT. See this article Int32.Parse Method (String) and see the Exceptions table FormatException description. So, 1. better you have a try catch functionality. Try the following suggestion , it is working. 2. Also You can use the    int.TryParse method

Way 1. Remove this statement  int femaleWeight = int.Parse(Console.ReadLine()); of code with try catch statement.

   private static int WeightIFeMale()

        {
            Console.WriteLine("How Much Do You Weigh?", Environment.NewLine);
            //int femaleWeight = int.Parse(Console.ReadLine());
            string weigt_st = Console.ReadLine();
            int femaleWeight = 0;
            try
            {
                femaleWeight = int.Parse(weigt_st);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            if (0 >= femaleWeight && 80 <= femaleWeight)
            {
                Console.WriteLine("Damn, how much crack are you smoking?", Environment.NewLine);
            }
            else if (81 >= femaleWeight && 110 <= femaleWeight)
            {
                Console.WriteLine("What the ****, are you a midget *****?", Environment.NewLine);

            }

            else if (111 >= femaleWeight && 140 <= femaleWeight)
            {
                Console.WriteLine("Holy shit, I have some protein bar coupons you can have!", Environment.NewLine);

            }

            else if (141 >= femaleWeight && 160 <= femaleWeight)
            {
                Console.WriteLine("Bro you need to hit the Gym, ASAP!", Environment.NewLine);

            }
            else if (161 >= femaleWeight && 200 <= femaleWeight)
            {
                Console.WriteLine("Really!!!, can I hit the Gym with you?", Environment.NewLine);

            }
            else if
                (201 >= femaleWeight && 240 <= femaleWeight)
            {
                Console.WriteLine("Do you Have a small ****, Steroids are a mother @#$%^&&", Environment.NewLine);

            }
            else if
                (241 >= femaleWeight && 999 <= femaleWeight)
            {
                Console.WriteLine("My condolences!", Environment.NewLine);
            }
            else if
                (femaleWeight >= 1000)
            {
                Console.WriteLine("There is absolutely no way that you weigh {0} lbs, so stop ******* around!", femaleWeight, Environment.NewLine);
            }
            else
            {
                Console.Write("What the **** is {0} It has to be a number numb nuts, lets try that again!", Environment.NewLine);
                WeightIFeMale();
            }

            return femaleWeight;
        }

Or Way 2. Remove this statement  int femaleWeight = int.Parse(Console.ReadLine()); of code with this one

   int femaleWeight = 0;
   int.TryParse(Console.ReadLine(), out femaleWeight);


来源: stackexchange

问:
Shell script with a cron job to kill a python file named healthcheck.py if not running and start the service again?
I am new to UNIX / Linux and need a shell script to kill a programs if it is not running. The program's name is healthcheck.py. This program is supposed to run this health check service for routers. But for every 8 hours the service is dropping with an error so I thought of putting it in cronjob that check if the service is running every minute and if it doesn't, I need a shell script to start the process. Currently I am doing it manually using these commands:

```<code>#getting the pid
 pid= ps - ef | grep -i python healthcheck.py

#kill the healthcheck.py process with the pid we got from above command
kill -9 "pid"

#running the service again
nohup python healthcheck.py &
</code>```

答:
This script worked

```<code>ps -aux | grep -i 'healthcheck' | awk {'print $2'} | xargs kill -9
nohup python <path_to_file/healthcheck.py> &
cat nohup.out
</code>```

with the crontab entry

```<code>0 1 * * * cron.sh
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to UNIX / Linux and need a shell script to kill a programs if it is not running. The program's name is healthcheck.py. This program is supposed to run this health check service for routers. But for every 8 hours the service is dropping with an error so I thought of putting it in cronjob that check if the service is running every minute and if it doesn't, I need a shell script to start the process. Currently I am doing it manually using these commands:

#getting the pid
 pid= ps - ef | grep -i python healthcheck.py

#kill the healthcheck.py process with the pid we got from above command
kill -9 "pid"

#running the service again
nohup python healthcheck.py &

Body:
This script worked

ps -aux | grep -i 'healthcheck' | awk {'print $2'} | xargs kill -9
nohup python <path_to_file/healthcheck.py> &
cat nohup.out

with the crontab entry

0 1 * * * cron.sh


问:
Problems with bar plot and tidyr when data are missing
I am trying to plot a simple bar graph with counts of certain events by year. Here's the data:

```<code>> DPUT(all.events)
structure(list(YEAR = c("1987", "1988", "1989", "1990", "1991",
"1992", "1993", "1994", "1995", "1996", "1998", "2000", "2001",
"2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009",
"2010", "2011", "2013", "2015", "2016"), count = c(3L, 4L, 2L,
3L, 1L, 2L, 6L, 1L, 7L, 1L, 6L, 1L, 2L, 3L, 3L, 4L, 1L, 1L, 1L,
2L, 2L, 10L, 1L, 2L, 1L, 3L)), .Names = c("YEAR", "count"), row.names = c(NA,
-26L), class = "data.frame")
</code>```

and here's my ggplot script:

```<code>ggplot(tidyr::complete(all.events,YEAR,fill=list(count=0)),
       aes(x=YEAR,y=count)) +
geom_bar(stat="identity") +
scale_y_continuous(limit=c(0,15),expand=c(0, 0)) +
scale_x_discrete(breaks=c(1985,1990,1995,2000,2005,2010,2015),
                 labels=c(1985,1990,1995,2000,2005,2010,2015)) +
theme_bw(base_size = 13) +
xlab("") + ylab("No of events")
</code>```

What I hoped that the complete would do, and what it has done on prior occasions, is to insert years along the x-axis also where the count=0. The plot I get is the one below, where there are years missing corresponding to where the count=0:

What am I doing wrong?

答:
complete will not create values out of nothing. From the help at ?complete:

For continuous variables, you may need to fill in values that don't appear in the data: to do so use expressions like year = 2010:2020 or year = full_seq(year)

So, as stated in the comments you should first convert YEAR to a numeric, but they key point is to specify that you want the full sequence (or manually YEAR  = 1987:2016).

```<code>tidyr::complete(all.events, full_seq(YEAR), fill = list(count=0))
</code>```

Body:
I am trying to plot a simple bar graph with counts of certain events by year. Here's the data:

> DPUT(all.events)
structure(list(YEAR = c("1987", "1988", "1989", "1990", "1991",
"1992", "1993", "1994", "1995", "1996", "1998", "2000", "2001",
"2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009",
"2010", "2011", "2013", "2015", "2016"), count = c(3L, 4L, 2L,
3L, 1L, 2L, 6L, 1L, 7L, 1L, 6L, 1L, 2L, 3L, 3L, 4L, 1L, 1L, 1L,
2L, 2L, 10L, 1L, 2L, 1L, 3L)), .Names = c("YEAR", "count"), row.names = c(NA,
-26L), class = "data.frame")

and here's my ggplot script:

ggplot(tidyr::complete(all.events,YEAR,fill=list(count=0)),
       aes(x=YEAR,y=count)) +
geom_bar(stat="identity") +
scale_y_continuous(limit=c(0,15),expand=c(0, 0)) +
scale_x_discrete(breaks=c(1985,1990,1995,2000,2005,2010,2015),
                 labels=c(1985,1990,1995,2000,2005,2010,2015)) +
theme_bw(base_size = 13) +
xlab("") + ylab("No of events")

What I hoped that the complete would do, and what it has done on prior occasions, is to insert years along the x-axis also where the count=0. The plot I get is the one below, where there are years missing corresponding to where the count=0:

What am I doing wrong?

Body:
complete will not create values out of nothing. From the help at ?complete:

For continuous variables, you may need to fill in values that don't appear in the data: to do so use expressions like year = 2010:2020 or year = full_seq(year)

So, as stated in the comments you should first convert YEAR to a numeric, but they key point is to specify that you want the full sequence (or manually YEAR  = 1987:2016).

tidyr::complete(all.events, full_seq(YEAR), fill = list(count=0))


问:
How can we set input type as textBox/CheckBox depending on the data retrieved from the collection?
My Requirement:

1. Get all the records from a collection and display each in an accordion.

2. For the records field i should check wheather it's a string/boolean.

3. If it's a string/boolean then I should get textBox/checkbox respectively.

sample.txt

```<code><div class="container">
    {{#each listjobs}}
        <i class="fa fa-close" style="font-size:30px;background-color:red;padding: 5px 10px;"></i>
        <button class="accordion">{{job}}</button>
        <div class="panel">
            <ul class="panel_elements">
                  {{params}}
                  <li><input type="submit" name="trigger" value="Trigger" /></li>
                  <li id="status">{{status}}</li>
            </ul>
        </div>
    {{/each}}
</div>
</code>```

My DB entry: this fields will change for most of the documents inside the collection.

```<code> "_id" : "8yfjmbMbv7KcNaKwz",
    "platform" : "abcd",
    "url" "http://<jenkins Address>/job/test/",
    "job" : "testing",
    "status" : "SUCCESS",
    "parameters" : [
            {
                    "name" : "DIRECTORY",
                    "value" : "def"
            },
            {
                    "name" : "BUILD_PROFILE",
                    "value" : "abc"
            }
    ]
}
</code>```

sample.js

```<code>Template.trigger.events({
'click .accordion':function(){
    var jobId = this._id;
    Session.set('selectJob', jobId);
    var selectedPlayer =Session.get('selectJob');
    console.log(selectedPlayer);
    var acc = document.getElementsByClassName("accordion");
    var i;

    for (i = 0; i < acc.length; i++) {
      acc[i].onclick = function() {
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight){
          panel.style.maxHeight = null;
        } else {
          panel.style.maxHeight = panel.scrollHeight + "px";
        }
      }
    }
},
});

Template.trigger.helpers({
'params':function(){
    var selectedJob = Session.get('selectJob');
    console.log(selectedJob);
    console.log(AddPipe.findOne({ "_id": selectedJob }));
    /*var param=AddPipe.findOne({ _id: selectedJob},{_id:0,parameters:1}).fetch();
    for(var i in param){

    }
    */
    return AddPipe.find({_id:selectedJob},{parameters:1}).map(function (c) {
    return {label: c.parameters, value:c.parameters};
    });
},
</code>```

答:
Make a couple of helpers isBoolean and isString, or a more general typeIs

```<code>Template.myTemplate.helpers({
  isBoolean(value) {
    return typeof value === 'boolean';
  },
  isString(value) {
    return typeof value === 'string';
  },
  typeIs(value, type) {
    return typeof value === type;
  }
});
</code>```

Then in your template, use an if

```<code><div class="container">
    {{#each listjobs}}
        <i class="fa fa-close" style="font-size:30px;background-color:red;padding: 5px 10px;"></i>
        <button class="accordion">{{job}}</button>
        <div class="panel">
            <ul class="panel_elements">

                {{#if isBoolean recordsField}}
                  <li><input type="checkbox"></li>
                {{/if}}
                {{#if isString recordsField}}
                  <li><input type="text"></li>
                {{/if}}

                  <li><input type="submit" name="trigger" value="Trigger" /></li>
                  <li id="status">{{status}}</li>
            </ul>
        </div>
    {{/each}}
</div>
</code>```

Note: Because helpers like this are useful everywhere, it makes sense to make them available to every template using Template.registerHelper

Body:
My Requirement:

1. Get all the records from a collection and display each in an accordion.

2. For the records field i should check wheather it's a string/boolean.

3. If it's a string/boolean then I should get textBox/checkbox respectively.

sample.txt

    {{#each listjobs}}

        <button class="accordion">{{job}}</button>

                  {{params}}

<input type="submit" name="trigger" value="Trigger" />

{{status}}

    {{/each}}

My DB entry: this fields will change for most of the documents inside the collection.

 "_id" : "8yfjmbMbv7KcNaKwz",
    "platform" : "abcd",
    "url" "http://<jenkins Address>/job/test/",
    "job" : "testing",
    "status" : "SUCCESS",
    "parameters" : [
            {
                    "name" : "DIRECTORY",
                    "value" : "def"
            },
            {
                    "name" : "BUILD_PROFILE",
                    "value" : "abc"
            }
    ]
}

sample.js

Template.trigger.events({
'click .accordion':function(){
    var jobId = this._id;
    Session.set('selectJob', jobId);
    var selectedPlayer =Session.get('selectJob');
    console.log(selectedPlayer);
    var acc = document.getElementsByClassName("accordion");
    var i;

    for (i = 0; i < acc.length; i++) {
      acc[i].onclick = function() {
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight){
          panel.style.maxHeight = null;
        } else {
          panel.style.maxHeight = panel.scrollHeight + "px";
        }
      }
    }
},
});

Template.trigger.helpers({
'params':function(){
    var selectedJob = Session.get('selectJob');
    console.log(selectedJob);
    console.log(AddPipe.findOne({ "_id": selectedJob }));
    /*var param=AddPipe.findOne({ _id: selectedJob},{_id:0,parameters:1}).fetch();
    for(var i in param){

    }
    */
    return AddPipe.find({_id:selectedJob},{parameters:1}).map(function (c) {
    return {label: c.parameters, value:c.parameters};
    });
},

Body:
Make a couple of helpers isBoolean and isString, or a more general typeIs

Template.myTemplate.helpers({
  isBoolean(value) {
    return typeof value === 'boolean';
  },
  isString(value) {
    return typeof value === 'string';
  },
  typeIs(value, type) {
    return typeof value === type;
  }
});

Then in your template, use an if

<div class="container">
    {{#each listjobs}}
        <i class="fa fa-close" style="font-size:30px;background-color:red;padding: 5px 10px;"></i>
        <button class="accordion">{{job}}</button>
        <div class="panel">
            <ul class="panel_elements">

                {{#if isBoolean recordsField}}
                  <li><input type="checkbox"></li>
                {{/if}}
                {{#if isString recordsField}}
                  <li><input type="text"></li>
                {{/if}}

                  <li><input type="submit" name="trigger" value="Trigger" /></li>
                  <li id="status">{{status}}</li>
            </ul>
        </div>
    {{/each}}
</div>

Note: Because helpers like this are useful everywhere, it makes sense to make them available to every template using Template.registerHelper


问:
Single page website navigation selected states
New to SO! Please suggest a better way to phrase this question :)

I have a single page, vertical scrolling website with a fixed navigation bar located in the footer. I am using local.scroll and anchors to link the navigation to divs on the page.

I would like the user to be able to click on one link and have it change to a selected state. I'm just not sure how to style/code the links for a single page (instead of using class="select" for each active link as in multiple page sites.)

This site has an example of what I'd like to accomplish:
http://www.kristaganelon.com/#portfolio-section

答:
Have a look at JQuerys
.toggleClass(classname)
. You could provide a fallback via css' pseudo-classes (not equal to the javascript solution since it is temporary).</p>

ContentLicense: CC BY-SA 2.5


问:
Parser that preserves comments and recover from error
I'm working on a GUI editor for a propriety config format. Basically the editor will parse the config file, display the object properties so that users can edit from GUI and then write the objects back to the file.

I've got the parse - edit - write part done, except for:

The parsed data structure only include object properties information, so comments and whitespaces are lost on write

If there is any syntax error, the rest of the file is skipped

How would you address these issues? What is the usual approach to this problem? I'm using Python and Parsec module https://pythonhosted.org/parsec/documentation.html, however and help and general direction is appreciated.

I've also tried Pylens (https://pythonhosted.org/pylens/), which is really close to what I need except it can not skip syntax errors.

答:
Eventually I ran out of research time and have to settle with a rather manual skipping. Basically each time the parser fail we try to advance the cursor one character and repeat. Any parts skipped by the process, regardless of whitespace/comment/syntax error is dump into a Text structure. The code is quite reusable, except for the part you have to incorporate it to all the places with repeated results and the original parser may fail.

Here's the code, in case it helps anyone. It is written for Parsy.

```<code>class Text(object):
    '''Structure to contain all the parts that the parser does not understand.
    A better name would be Whitespace
    '''
    def __init__(self, text=''):
        self.text = text

    def __repr__(self):
        return "Text(text='{}')".format(self.text)

    def __eq__(self, other):
        return self.text.strip() == getattr(other, 'text', '').strip()

def many_skip_error(parser, skip=lambda t, i: i + 1, until=None):
    '''Repeat the original `parser`, aggregate result into `values`
    and error in `Text`.
    '''
    @Parser
    def _parser(stream, index):
        values, result = [], None

        while index < len(stream):
            result = parser(stream, index)
            # Original parser success
            if result.status:
                values.append(result.value)
                index = result.index
            # Check for end condition, effectively `manyTill` in Parsec
            elif until is not None and until(stream, index).status:
                break
            # Aggregate skipped text into last `Text` value, or create a new one
            else:
                if len(values) > 0 and isinstance(values[-1], Text):
                    values[-1].text += stream[index]
                else:
                    values.append(Text(stream[index]))
                index = skip(stream, index)
        return Result.success(index, values).aggregate(result)
    return _parser

# Example usage
skip_error_parser = many_skip_error(original_parser)
</code>```

On other note, I guess the real issue here is I'm using a parser combinator library instead of a proper two stages parsing process. In traditional parsing, the tokenizer will handle retaining/skipping any whitespace/comment/syntax error, making them all effectively whitespace and are invisible to the parser.

Body:
Eventually I ran out of research time and have to settle with a rather manual skipping. Basically each time the parser fail we try to advance the cursor one character and repeat. Any parts skipped by the process, regardless of whitespace/comment/syntax error is dump into a Text structure. The code is quite reusable, except for the part you have to incorporate it to all the places with repeated results and the original parser may fail.

Here's the code, in case it helps anyone. It is written for Parsy.

class Text(object):
    '''Structure to contain all the parts that the parser does not understand.
    A better name would be Whitespace
    '''
    def __init__(self, text=''):
        self.text = text

    def __repr__(self):
        return "Text(text='{}')".format(self.text)

    def __eq__(self, other):
        return self.text.strip() == getattr(other, 'text', '').strip()

def many_skip_error(parser, skip=lambda t, i: i + 1, until=None):
    '''Repeat the original `parser`, aggregate result into `values`
    and error in `Text`.
    '''
    @Parser
    def _parser(stream, index):
        values, result = [], None

        while index < len(stream):
            result = parser(stream, index)
            # Original parser success
            if result.status:
                values.append(result.value)
                index = result.index
            # Check for end condition, effectively `manyTill` in Parsec
            elif until is not None and until(stream, index).status:
                break
            # Aggregate skipped text into last `Text` value, or create a new one
            else:
                if len(values) > 0 and isinstance(values[-1], Text):
                    values[-1].text += stream[index]
                else:
                    values.append(Text(stream[index]))
                index = skip(stream, index)
        return Result.success(index, values).aggregate(result)
    return _parser

# Example usage
skip_error_parser = many_skip_error(original_parser)

On other note, I guess the real issue here is I'm using a parser combinator library instead of a proper two stages parsing process. In traditional parsing, the tokenizer will handle retaining/skipping any whitespace/comment/syntax error, making them all effectively whitespace and are invisible to the parser.


问:
When zooming in, why does the footer overlap its preceding content
here is the sample html:

```<code><div id = "mainWrapperDiv">
    <div id = "mainDiv">
        <div> testing </div>
    </div>
 </div>
 <div id = "footerDiv">
 </div>
</code>```

its css:

```<code>*
{
    padding:            0px;
    margin:             0px;
}

body, html
{
    height:             100%
}

div
{
    border:             none;
}

#mainWrapperDiv
{
    min-height:         100%;
    height:             100%;
    margin-bottom:      -200px;
}

#mainDiv
{

    margin:             0px auto 0px auto;
    width:              1000px;
    min-height:         500px;
    background:         lightgreen;
}

#footerDiv
{
    height:             200px;
    width:              100%;
    position:           relative;
    clear:              both;
    background:         lightblue;
}
</code>```

答: It's because of your margin-bottom in the #mainWrapperDiv. If you take that out it appears to work okay. Check it out http://jsfiddle.net/kA6XJ/

Body:
here is the sample html:

 testing

its css:

*
{
    padding:            0px;
    margin:             0px;
}

body, html
{
    height:             100%
}

div
{
    border:             none;
}

#mainWrapperDiv
{
    min-height:         100%;
    height:             100%;
    margin-bottom:      -200px;
}

#mainDiv
{

    margin:             0px auto 0px auto;
    width:              1000px;
    min-height:         500px;
    background:         lightgreen;
}

#footerDiv
{
    height:             200px;
    width:              100%;
    position:           relative;
    clear:              both;
    background:         lightblue;
}


问:
Azure API Management - require approval of new developer signup
As we all know, the Azure API Management provides a developer portal.  You can change the way that users login to the portal with AAD, Facebook, ...  I understand how to configure those options.

I don't want new developers to have automatic access to the portal.  I want to review the signup and approve them before they get access.  How do I implement this approval process for new users?

答: If I remember correctly this can be done via the product, require subscription approval... https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-add-products#create-and-publish-a-product-1</p>


问:
Error while including c++ files and folders into iOS xcode project
In my project I need to use an external files and folders which are written in C++ relates to OpenGL framework.

I've added these C++ headers to my Xcode project, and also specified a header search path (Build Settings -> Header search paths).
Everything works fine in demo project but getting error while adding to original project which has 2 projects with a single workspace.

```<code>Error :file not found with <angled> include; use "quotes" instead
</code>```

Getting this error at the time of compilation.
If I tried with include statement with quotes again it is generating some more errors.

How to use external c++ libraries and headers in iOS objective-c project?
Unable to find the issue.It may be a duplicate question but I dint found a solution.
Need suggestions to resolve this error.

答: Resolved issue.It was problem with folder structure and path.Added proper path in Header Search Paths in Build Settings.</p>

Body:
In my project I need to use an external files and folders which are written in C++ relates to OpenGL framework.

I've added these C++ headers to my Xcode project, and also specified a header search path (Build Settings -> Header search paths).
Everything works fine in demo project but getting error while adding to original project which has 2 projects with a single workspace.

Error :file not found with <angled> include; use "quotes" instead

Getting this error at the time of compilation.
If I tried with include statement with quotes again it is generating some more errors.

How to use external c++ libraries and headers in iOS objective-c project?
Unable to find the issue.It may be a duplicate question but I dint found a solution.
Need suggestions to resolve this error.


问:
Error while trying to run project in debug mode, but works if I run the EXE file
When I am trying to run the Debugger for Visual Studio 2010 and for Visual Studio 2012, I get the below error:

Error while trying to run project: Could not load file or assembly 'MyProject' or one of its dependencies. An attempt was made to load a program with an incorrect format.

But when I go to the x64/Debug folder and run the EXE directly, it opens fine.

I've tried disabling the project that contains the 32-bit references, but it still gives me the error even when all the other projects are 64-bit (set through Configuration Manager)

Edit #1: In 32-bit compilation mode, I set everything to Any CPU except the Main startup project to x86 and it runs Debug Mode fine. When I go to 64-bit, and do the same but change Main startup project to x64 it gives the above error. I tried setting all Target values to x64, but still nothing.

答:
I've had the same problem with debugging x64 empty console application. Application ran without debugging in any case, but debugging was working only with x86/AnyCPU target platform (32 bit process), but with x64 I was getting:

Error while trying to run project: Could not load file or assembly 'ConsoleApplication1' or one of its dependencies. An attempt was made to load a program with an incorrect format.

My solution was to turn off Project -> Properties -> Debug -> Enable the Visual Studio hosting process


问:
Best practices for generic functions in python
I've read a lot about generic classes, and while those are cool, sometimes, I just need a generic function. Here's a small one I wrote:

```<code>def _matrix_map(self, mapper):
    """returns the matrix applying the mapper funcfunc"""
    return {key: mapper(value) for key, value in self._matrix.items()}
</code>```

How is this supposed to be annotated for types. In a statically typed language with generic support, I'd write it something like this

```<code>private Dictionary<KeyType, ValueType> matrix;
private Dictionary<KeyType, T> matrix_map<T>(Func<ValueType, T>)
</code>```

So, I thought I'd write it like this:

```<code>T = TypeVar('T')
def _matrix_map(self, mapper: Callable[[Tile], T]) -> Dict[Coordinate, T]:
</code>```

I got it to pass with mypy like this, but pylint hates this.

On the first line:

```<code>C0103:Invalid class attribute name "T"
</code>```

And on the second line:

```<code>E0602:Undefined variable 'T'
</code>```

So I feel like I'm doing something wrong, and I could change the variable name (ttt? typ?), but that wouldn't solve the second problem. I can't be the first person to want (statically-typed) generic functions, but I can't find any good resources anywhere. Any recommendations?

答:
I'm guessing you wrote code that looked roughly like this?

```<code>class Matrix:
    T = TypeVar('T')

    def _matrix_map(self, mapper: Callable[[Tile], T]) -> Dict[Coordinate, T]:
        # ...snip...
</code>```

There's actually no issue with this at runtime/no issue for mypy, but it seems pylint isn't happy with you putting that "T" inside the scope of the class definition. What you can do to satisfy pylint is to instead do this:

```<code>T = TypeVar('T')

class Matrix:
    def _matrix_map(self, mapper: Callable[[Tile], T]) -> Dict[Coordinate, T]:
        # ...snip...
</code>```

This is exactly equivalent to the former code snippet, and will also satisfy pylint.

(As a tangent, I'd argue that the fact that pylint isn't happy with the former is actually a bug. To be fair though, there aren't really any established style guides on best practices for type hints yet/putting a typevar inside of a nested scope is a somewhat uncommon use case, so I guess I can't really blame them for not accounting for this case.)

The only downside is that having that TypeVar on the outside does seem vaguely untidy/seems like it'll pollute the global namespace. You can partially mitigate this by renaming it to something like _T for example, to indicate it's private. You can also reuse this typevar whenever you need another generic class or function, which should also hopefully help keep the namespace pollution down.

For more information about using generics with Python type hints, see http://mypy.readthedocs.io/en/stable/generics.html

Body:
I've read a lot about generic classes, and while those are cool, sometimes, I just need a generic function. Here's a small one I wrote:

def _matrix_map(self, mapper):
    """returns the matrix applying the mapper funcfunc"""
    return {key: mapper(value) for key, value in self._matrix.items()}

How is this supposed to be annotated for types. In a statically typed language with generic support, I'd write it something like this

private Dictionary<KeyType, ValueType> matrix;
private Dictionary<KeyType, T> matrix_map<T>(Func<ValueType, T>)

So, I thought I'd write it like this:

T = TypeVar('T')
def _matrix_map(self, mapper: Callable[[Tile], T]) -> Dict[Coordinate, T]:

I got it to pass with mypy like this, but pylint hates this.

On the first line:

C0103:Invalid class attribute name "T"

And on the second line:

E0602:Undefined variable 'T'

So I feel like I'm doing something wrong, and I could change the variable name (ttt? typ?), but that wouldn't solve the second problem. I can't be the first person to want (statically-typed) generic functions, but I can't find any good resources anywhere. Any recommendations?

Body:
I'm guessing you wrote code that looked roughly like this?

class Matrix:
    T = TypeVar('T')

    def _matrix_map(self, mapper: Callable[[Tile], T]) -> Dict[Coordinate, T]:
        # ...snip...

There's actually no issue with this at runtime/no issue for mypy, but it seems pylint isn't happy with you putting that "T" inside the scope of the class definition. What you can do to satisfy pylint is to instead do this:

T = TypeVar('T')

class Matrix:
    def _matrix_map(self, mapper: Callable[[Tile], T]) -> Dict[Coordinate, T]:
        # ...snip...

This is exactly equivalent to the former code snippet, and will also satisfy pylint.

(As a tangent, I'd argue that the fact that pylint isn't happy with the former is actually a bug. To be fair though, there aren't really any established style guides on best practices for type hints yet/putting a typevar inside of a nested scope is a somewhat uncommon use case, so I guess I can't really blame them for not accounting for this case.)

The only downside is that having that TypeVar on the outside does seem vaguely untidy/seems like it'll pollute the global namespace. You can partially mitigate this by renaming it to something like _T for example, to indicate it's private. You can also reuse this typevar whenever you need another generic class or function, which should also hopefully help keep the namespace pollution down.

For more information about using generics with Python type hints, see http://mypy.readthedocs.io/en/stable/generics.html


问:
Update database using MySQL and PHP
There are no errors shown when I click the register button to register new users, but the data isn't inserted in the database.</p>

```<code><?php
    session_start();
     if(isset($_POST['name'])&&isset($_POST['password'])){
    $name=$_POST['name'];
    $password=$_POST['password'];

    $link=mysqli_connect("localhost","root","");
    $select=mysqli_select_db($link,'first_db');
    $name=mysqli_real_escape_string($link,$name);
    $password=mysqli_real_escape_string($link,$password);
    $query="SELECT * FROM users WHERE name='$name'";
    $run=mysqli_query($link,$query);
    $count = mysqli_num_rows($run);

    if ($count>0) {
    echo 'Sorry! This Username already exists!';
    } else {
        $name = $_POST['name'];
        $password=$_POST['password'];
        $sql = "INSERT INTO users (name, password)
                VALUES
                ('$_POST[name]','$_POST[password]')";
    }
     }
    else{
        echo"Cannot be blank";
    }
?>
</code>```

答:
check your else part you just created the query need to execute it</p>

```<code>if ($count>0)
{
   echo 'Sorry! This Username already exists!';
}
else
{
    $name = $_POST['name'];
    $password=$_POST['password'];
    $sql = "INSERT INTO users (name, password)VALUES('$name','$password')";
    $run=mysqli_query($link,$sql);// add this statement then your record inserted

}
</code>```

Title: Update database using MySQL and PHP

Body:
There are no errors shown when I click the register button to register new users, but the data isn't inserted in the database.

<?php
    session_start();
     if(isset($_POST['name'])&&isset($_POST['password'])){
    $name=$_POST['name'];
    $password=$_POST['password'];

    $link=mysqli_connect("localhost","root","");
    $select=mysqli_select_db($link,'first_db');
    $name=mysqli_real_escape_string($link,$name);
    $password=mysqli_real_escape_string($link,$password);
    $query="SELECT * FROM users WHERE name='$name'";
    $run=mysqli_query($link,$query);
    $count = mysqli_num_rows($run);

    if ($count>0) {
    echo 'Sorry! This Username already exists!';
    } else {
        $name = $_POST['name'];
        $password=$_POST['password'];
        $sql = "INSERT INTO users (name, password)
                VALUES
                ('$_POST[name]','$_POST[password]')";
    }
     }
    else{
        echo"Cannot be blank";
    }
?>

Body:
check your else part you just created the query need to execute it

if ($count>0)
{
   echo 'Sorry! This Username already exists!';
}
else
{
    $name = $_POST['name'];
    $password=$_POST['password'];
    $sql = "INSERT INTO users (name, password)VALUES('$name','$password')";
    $run=mysqli_query($link,$sql);// add this statement then your record inserted

}


问:
Can't change height of UINavigationBar in iOS 11
I am trying to implement something similar to the new App Store's status bar in the 'Today' tab on iPhone X.
App Store - Today

So just wondering what is the implementation. I tried to changing the height of navigation bar/overlaying a translucent UIView over the status bar, but none seems satisfactory given that the bar only exist on iPhone X. Thanks.

答:
Create class for navigation bar </p>

```<code>class NavigationBar: UINavigationBar {

    override func layoutSubviews() {
        super.layoutSubviews()

        for subview in self.subviews {
            let stringFromClass = NSStringFromClass(subview.classForCoder)

            if stringFromClass.contains("BarBackground") {
                subview.frame.origin.y = -20
                subview.frame.size.height = 64
            }
        }
    }
}
</code>```

<p>and create navigation bar with the required size </p>

```<code>let navigationBar = NavigationBar(frame: CGRect(origin: CGPoint(x: 0,
                                                                        y: 20),
                                                        size: CGSize(width: view.frame.width,
                                                                     height: 30)))
       navigationBar.isTranslucent = false
       self.view .addSubview(navigationBar)
</code>```

Body:
Create class for navigation bar

class NavigationBar: UINavigationBar {

    override func layoutSubviews() {
        super.layoutSubviews()

        for subview in self.subviews {
            let stringFromClass = NSStringFromClass(subview.classForCoder)

            if stringFromClass.contains("BarBackground") {
                subview.frame.origin.y = -20
                subview.frame.size.height = 64
            }
        }
    }
}

and create navigation bar with the required size

let navigationBar = NavigationBar(frame: CGRect(origin: CGPoint(x: 0,
                                                                        y: 20),
                                                        size: CGSize(width: view.frame.width,
                                                                     height: 30)))
       navigationBar.isTranslucent = false
       self.view .addSubview(navigationBar)


问:
Python code reflection and modification
Perhaps I'm not using the proper term, but I'm looking to take a block of Python code (in Python), get the token tree for the code, make some kind of modification, and re-assemble it to Python.

For instance, consider this block of code:

```<code>def x(y):
    b = 2
    if y == b:
        foo(y)
</code>```

I would like to be able to take this and programmatically do this:

```<code>def x(y):
    b = 2
    if y == b:
        bar(y)
</code>```

I can't imagine that there's not a library that does something like this. Thanks in advance.

EDIT

Perhaps I wasn't entirely clear. I'm looking for a tool to read and manipulate arbitrary code, not code that I'm writing. I'd like to be able to modify code on-the-fly. The project I'm working on is a test app: it uses the Netflix philosophy to try to randomly break the functionality of an app in as many ways as it can, running the test suite each time. When the tests don't fail, there's an indication that there's either a gap in code coverage and/or the code is dead.

答:
In Python functions can be passed just like any other object so you should be able to do something like:

```<code>def x(fx, y):
    b = 2
    if y == b:
        fx(y)
</code>```

and then call:

```<code>x(foo, y)
</code>```

or

```<code>x(bar, y)
</code>```

Here's a stripped down, tested snippet (v 3.1) that demonstrates the concept w/o any bizlogic, just sample execution and arbitrary numeric manipulation:

```<code>def x(fx, y): return fx(y)
def foo(x): return x
def bar(x): return x+1

print(x(foo,1))
print(x(bar,1))
</code>```

output:

```<code>>>>
1
2
</code>```

Title: Python code reflection and modification

Body:
Perhaps I'm not using the proper term, but I'm looking to take a block of Python code (in Python), get the token tree for the code, make some kind of modification, and re-assemble it to Python.

For instance, consider this block of code:

def x(y):
    b = 2
    if y == b:
        foo(y)

I would like to be able to take this and programmatically do this:

def x(y):
    b = 2
    if y == b:
        bar(y)

I can't imagine that there's not a library that does something like this. Thanks in advance.

EDIT

Perhaps I wasn't entirely clear. I'm looking for a tool to read and manipulate arbitrary code, not code that I'm writing. I'd like to be able to modify code on-the-fly. The project I'm working on is a test app: it uses the Netflix philosophy to try to randomly break the functionality of an app in as many ways as it can, running the test suite each time. When the tests don't fail, there's an indication that there's either a gap in code coverage and/or the code is dead.

Body:
In Python functions can be passed just like any other object so you should be able to do something like:

def x(fx, y):
    b = 2
    if y == b:
        fx(y)

and then call:

x(foo, y)

or

x(bar, y)

Here's a stripped down, tested snippet (v 3.1) that demonstrates the concept w/o any bizlogic, just sample execution and arbitrary numeric manipulation:

def x(fx, y): return fx(y)
def foo(x): return x
def bar(x): return x+1

print(x(foo,1))
print(x(bar,1))

output:

>>>
1
2


问:
Print out all possible strings in C using recursion
My assignment is that code takes a string as input, and if there are x's in the string replace them with either a 0 or a 1, and print out all the possible string combinations. We have to use recursion for this as well. For example, if the input string was "1x0X" the output would be:

```<code>1000
1001
1100
1101
</code>```

I'm really struggling with how I'm supposed to find all the permutations of the string without having the complete string yet. I have a series of function that combine to print out all permutations of a list of numbers, but I don't know how to make a function where it only permutes certain elements of a list.

Does anyone have any suggestions on how to accomplish this?

答:
Jonathan's initial suggestion

This code implements what I suggested in a comment essentially verbatim.  It accepts either x or X as a valid marker because the examples in the question do too.

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

static void map_x(const char *str)
{
</code>```

```<code>    size_t xloc = strcspn(str, "xX");
    if (str[xloc] == '\0')
        printf("%s\n", str);
    else
    {
        char *copy = strdup(str);
        copy[xloc] = '0';
        map_x(copy);
        copy[xloc] = '1';
        map_x(copy);
        free(copy);
    } </code>```

```<code>}

int main(void)
{
    char buffer[4096];
    while (fgets(buffer, sizeof(buffer), stdin) != 0)
    {
        buffer[strcspn(buffer, "\n")] = '\0';
        map_x(buffer);
    }
    return 0;
}
</code>```

The main() function is essentially the same in all three variants.  The use of strcspn() is a standard idiom that trims everything from the first newline onwards, or overwrites the end of the string if there is no newline in it.

Note that this solution is safe even if a read-only string literal is passed to the function; it does not modify the string that it is passed.  The following solutions will both crash or otherwise fail if the initial string is in fact a read-only string literal.

It would be possible to determine the string length, allocate a VLA (variable length array) to take the string copy, and copy the string into the VLA.  That would dramatically reduce the cost of allocating memory for the string (VLA allocation is much simpler than a general purpose memory allocator).

Gene's Suggestion

This code implements what Gene suggested in a comment.  It will be more efficient because it does no extra memory allocation, an expensive operation on most systems.

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

static void map_x(char *str)
{
</code>```

```<code>        size_t xloc = strcspn(str, "xX");
        if (str[xloc] == '\0')
            printf("%s\n", str);
        else
        {
            char letter = str[xloc];
            str[xloc] = '0';
            map_x(str);
            str[xloc] = '1';
            map_x(str);
            str[xloc] = letter;
        }</code>```

```<code>}

int main(void)
{
    char buffer[4096];
    while (fgets(buffer, sizeof(buffer), stdin) != 0)
    {
        buffer[strcspn(buffer, "\n")] = '\0';
        map_x(buffer);
    }
    return 0;
}
</code>```

Mildly optimized variant

This optimizes the work by not rescanning the prefix that is already known to be free of x's.

```<code>/* SO 4764-4683 */
#include <stdio.h>
#include <string.h>

static void map_x(char *str, size_t offset)
{
</code>```

```<code>        size_t xloc = strcspn(&str[offset], "xX") + offset;
        if (str[xloc] == '\0')
            printf("%s\n", str);
        else
        {
            char letter = str[xloc];
            str[xloc] = '0';
            map_x(str, xloc);
            str[xloc] = '1';
            map_x(str, xloc);
            str[xloc] = letter;
        }</code>```

```<code>}

int main(void)
{
    char buffer[4096];
    while (fgets(buffer, sizeof(buffer), stdin) != 0)
    {
        buffer[strcspn(buffer, "\n")] = '\0';
        map_x(buffer, 0);
    }
    return 0;
}
</code>```

The difference in performance is probably not measurable on almost any input simply because the I/O time will dominate.

With all due respect to chux, I think that the code in the answer is more complex than necessary.  The extra data structure seems like overkill.

Body:
My assignment is that code takes a string as input, and if there are x's in the string replace them with either a 0 or a 1, and print out all the possible string combinations. We have to use recursion for this as well. For example, if the input string was "1x0X" the output would be:

1000
1001
1100
1101

I'm really struggling with how I'm supposed to find all the permutations of the string without having the complete string yet. I have a series of function that combine to print out all permutations of a list of numbers, but I don't know how to make a function where it only permutes certain elements of a list.

Does anyone have any suggestions on how to accomplish this?

Body:
Jonathan's initial suggestion

This code implements what I suggested in a comment essentially verbatim.  It accepts either x or X as a valid marker because the examples in the question do too.

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

static void map_x(const char *str)
{

    size_t xloc = strcspn(str, "xX");
    if (str[xloc] == '\0')
        printf("%s\n", str);
    else
    {
        char *copy = strdup(str);
        copy[xloc] = '0';
        map_x(copy);
        copy[xloc] = '1';
        map_x(copy);
        free(copy);
    }

}

int main(void)
{
    char buffer[4096];
    while (fgets(buffer, sizeof(buffer), stdin) != 0)
    {
        buffer[strcspn(buffer, "\n")] = '\0';
        map_x(buffer);
    }
    return 0;
}

The main() function is essentially the same in all three variants.  The use of strcspn() is a standard idiom that trims everything from the first newline onwards, or overwrites the end of the string if there is no newline in it.

Note that this solution is safe even if a read-only string literal is passed to the function; it does not modify the string that it is passed.  The following solutions will both crash or otherwise fail if the initial string is in fact a read-only string literal.

It would be possible to determine the string length, allocate a VLA (variable length array) to take the string copy, and copy the string into the VLA.  That would dramatically reduce the cost of allocating memory for the string (VLA allocation is much simpler than a general purpose memory allocator).

Gene's Suggestion

This code implements what Gene suggested in a comment.  It will be more efficient because it does no extra memory allocation, an expensive operation on most systems.

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

static void map_x(char *str)
{

        size_t xloc = strcspn(str, "xX");
        if (str[xloc] == '\0')
            printf("%s\n", str);
        else
        {
            char letter = str[xloc];
            str[xloc] = '0';
            map_x(str);
            str[xloc] = '1';
            map_x(str);
            str[xloc] = letter;
        }

}

int main(void)
{
    char buffer[4096];
    while (fgets(buffer, sizeof(buffer), stdin) != 0)
    {
        buffer[strcspn(buffer, "\n")] = '\0';
        map_x(buffer);
    }
    return 0;
}

Mildly optimized variant

This optimizes the work by not rescanning the prefix that is already known to be free of x's.

/* SO 4764-4683 */
#include <stdio.h>
#include <string.h>

static void map_x(char *str, size_t offset)
{

        size_t xloc = strcspn(&str[offset], "xX") + offset;
        if (str[xloc] == '\0')
            printf("%s\n", str);
        else
        {
            char letter = str[xloc];
            str[xloc] = '0';
            map_x(str, xloc);
            str[xloc] = '1';
            map_x(str, xloc);
            str[xloc] = letter;
        }

}

int main(void)
{
    char buffer[4096];
    while (fgets(buffer, sizeof(buffer), stdin) != 0)
    {
        buffer[strcspn(buffer, "\n")] = '\0';
        map_x(buffer, 0);
    }
    return 0;
}

The difference in performance is probably not measurable on almost any input simply because the I/O time will dominate.

With all due respect to chux, I think that the code in the answer is more complex than necessary.  The extra data structure seems like overkill.


问:
create dynamic elements custom
I have a custom ImageView and work if i add my element in my activity.xml, but dont work if i  try create dynamic element.

EDIT:SOLVED

Here the repo

Note: dont execute the method onDraw

Activity class

```<code>val xpp = resources.getXml(R.xml. octocat)

        val attr = Xml.asAttributeSet(xpp)

        val octocat :  OctocatView = OctocatView(this,attr)
        octocat.invalidate()
        val layout : LinearLayout = findViewById(R.id.layout)

        layout.addView(octocat)
</code>```

** Java Class**

```<code>public class OctocatView extends android.support.v7.widget.AppCompatImageView{

    private Context mContext;

    public OctocatView(Context context, AttributeSet attrs, int defStyleAttr, Context mContext) {
        super(context, attrs, defStyleAttr);
        this.mContext = mContext;

    }

    public OctocatView(Context context, AttributeSet attrs)  {
        super(context, attrs);
        mContext = context;
    }

    public OctocatView(Context context) {
        super(context);
        mContext = context;

    }

    protected void onDraw(Canvas c) {
       //some code
    }

}
</code>```

Element XML res/xml/octocat.xml

```<code><hackro.tutorials.com.salesfacebook.widget.OctocatView android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android" />
</code>```

答:
Try to set the size of your View programmatically before adding it to the LinearLayout:

```<code>octocat.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT)

 layout.addView(octocat)
</code>```

Title: create dynamic elements custom

Body:
I have a custom ImageView and work if i add my element in my activity.xml, but dont work if i  try create dynamic element.

EDIT:SOLVED

Here the repo

Note: dont execute the method onDraw

Activity class

val xpp = resources.getXml(R.xml. octocat)

        val attr = Xml.asAttributeSet(xpp)

        val octocat :  OctocatView = OctocatView(this,attr)
        octocat.invalidate()
        val layout : LinearLayout = findViewById(R.id.layout)

        layout.addView(octocat)

** Java Class**

public class OctocatView extends android.support.v7.widget.AppCompatImageView{

    private Context mContext;

    public OctocatView(Context context, AttributeSet attrs, int defStyleAttr, Context mContext) {
        super(context, attrs, defStyleAttr);
        this.mContext = mContext;

    }

    public OctocatView(Context context, AttributeSet attrs)  {
        super(context, attrs);
        mContext = context;
    }

    public OctocatView(Context context) {
        super(context);
        mContext = context;

    }

    protected void onDraw(Canvas c) {
       //some code
    }

}

Element XML res/xml/octocat.xml

<hackro.tutorials.com.salesfacebook.widget.OctocatView android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android" />

Body:
Try to set the size of your View programmatically before adding it to the LinearLayout:

octocat.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT)

 layout.addView(octocat)


问:
bootstrap 4 making dropdown scrollable
I have a problem with my drop down menu on smaller devices. i cannot make it scroll able when i tried the solution here (that is overflow:auto/ overflow-y:scroll) it's not working even if i use !important. What i'm able to scroll was my main page even if the drop down is open.

```<code><nav class="navbar navbar-toggleable-sm ">
    <button class="navbar-toggler navbar-toggler-right main-navbar-toggler" type="button" data-toggle="collapse" data-target="#main-nav-collapse" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">
        <span class="fa fa-bars"></span>
    </button>
    <a class="navbar-brand animation" data-animation ="fadeInLeft" href="#"><img src="/093017/img/logo-tmi.png" alt="logo"/></a>
    <div class="collapse navbar-collapse" id = "main-nav-collapse" >
        <ul class="nav navbar-nav navbar-main mr-auto mt-2 mt-md-0 animation" data-animation = "fadeInRight">
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Vehicles</a>
                <div class="dropdown-menu default-menu main-menu sm-main-menu animation" data-animation = "fadeIn">
                    <!-- Nav tabs -->
                    <div class="sm-main-nav" >
                        <a class="dropdown-item" href="#">Cars</a><hr>
                        <a class="dropdown-item" href="#">Vans & Pickup</a><hr>
                        <a class="dropdown-item" href="#">SUVs & Crossover</a><hr>
                        <a class="dropdown-item" href="#">MPVs</a><hr>
                        <a class="dropdown-item" href="#">Hybrid</a><hr>
                        <a class="dropdown-item" href="#">Performance</a>
                    </div>
                </div>
            </li>
            <li class="nav-item">
                <a class="nav-link " href="#">Owners</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Shop</a>
            </li>
            <li class="nav-item">
                <a class="nav-link " href="#">Promotions</a>
            </li>
        </ul>
    </div>
</code>```

答:
just you can use @media in your css

@media (max-width: 500px) {
    .dropdown-menu{
        height:200px;
        overflow-y:auto;
    }
}
```

Title: bootstrap 4 making dropdown scrollable

Body:
I have a problem with my drop down menu on smaller devices. i cannot make it scroll able when i tried the solution here (that is overflow:auto/ overflow-y:scroll) it's not working even if i use !important. What i'm able to scroll was my main page even if the drop down is open.

    <button class="navbar-toggler navbar-toggler-right main-navbar-toggler" type="button" data-toggle="collapse" data-target="#main-nav-collapse" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                Vehicles

                        Cars

                        Vans & Pickup

                        SUVs & Crossover

                        MPVs

                        Hybrid

                        Performance

                Owners

                Shop

                Promotions

ContentLicense: CC BY-SA 4.0


问:
Sending Email with attachment from Asset folder
```<code>    //EMAIL SENDING CODE  FROM ASSET FOLDER
    email = editTextEmail.getText().toString();
    subject = editTextSubject.getText().toString();
    message = editTextMessage.getText().toString();
    final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.setType("file/html");
    emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://com.example.deepa.xmlparsing/file:///android_assets/Combination-1.html"));
    startActivity(Intent.createChooser(emailIntent, "Send email using"));
</code>```

Finally, I'm getting the file from asset folder (Combination-1.html).

It is getting

Runtime error file not found exception.

Is there any other way to send file attachment?

答:
Create a File object of your asset folder file and attach this object to your email Intent.

And as mentioned in your Question runtime error file not found exception this may be cause the URL "file:///android_asset/" doesn't point to a particular directory, it is only used by WebView to address assets. Pulled that from

you can open this as an input stream and covert this InputStream to File

```<code>in = new BufferedReader(new InputStreamReader(activity.getAssets().open(myfile.pdf)));
</code>```

Send this file object in email as follow.

```<code>Intent intent = new Intent(Intent.ACTION_SEND ,Uri.parse("mailto:"));
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Card Set ");
intent.putExtra(Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(file));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
</code>```

Where Intent.ACTION_SEND used to send Email , Intent.EXTRA_STREAM for the attachments with email. you can have multiple Intent.EXTRA_STREAMin single intent to refer multiple attachments with intent.setAction(Intent.ACTION_SEND_MULTIPLE);.

intent.setType(String mimeType) input param is represent the MIME type data that you want to get in return from firing intent(here intent instance).where setype can be

```<code>image/jpeg
audio/mpeg4-generic
text/html
audio/mpeg
audio/aac
audio/wav
audio/ogg
audio/midi
audio/x-ms-wma
video/mp4
video/x-msvideo
video/x-ms-wmv
image/png
image/jpeg
image/gif
.xml ->text/xml
.txt -> text/plain
.cfg -> text/plain
.csv -> text/plain
.conf -> text/plain
.rc -> text/plain
.htm -> text/html
.html -> text/html
.pdf -> application/pdf
.apk -> application/vnd.android.package-archive
</code>```

Body:
    //EMAIL SENDING CODE  FROM ASSET FOLDER
    email = editTextEmail.getText().toString();
    subject = editTextSubject.getText().toString();
    message = editTextMessage.getText().toString();
    final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.setType("file/html");
    emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://com.example.deepa.xmlparsing/file:///android_assets/Combination-1.html"));
    startActivity(Intent.createChooser(emailIntent, "Send email using"));

Finally, I'm getting the file from asset folder (Combination-1.html).

It is getting

Runtime error file not found exception.

Is there any other way to send file attachment?

Body:
Create a File object of your asset folder file and attach this object to your email Intent.

And as mentioned in your Question runtime error file not found exception this may be cause the URL "file:///android_asset/" doesn't point to a particular directory, it is only used by WebView to address assets. Pulled that from

you can open this as an input stream and covert this InputStream to File

in = new BufferedReader(new InputStreamReader(activity.getAssets().open(myfile.pdf)));

Send this file object in email as follow.

Intent intent = new Intent(Intent.ACTION_SEND ,Uri.parse("mailto:"));
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Card Set ");
intent.putExtra(Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(file));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);

Where Intent.ACTION_SEND used to send Email , Intent.EXTRA_STREAM for the attachments with email. you can have multiple Intent.EXTRA_STREAMin single intent to refer multiple attachments with intent.setAction(Intent.ACTION_SEND_MULTIPLE);.

intent.setType(String mimeType) input param is represent the MIME type data that you want to get in return from firing intent(here intent instance).where setype can be

image/jpeg
audio/mpeg4-generic
text/html
audio/mpeg
audio/aac
audio/wav
audio/ogg
audio/midi
audio/x-ms-wma
video/mp4
video/x-msvideo
video/x-ms-wmv
image/png
image/jpeg
image/gif
.xml ->text/xml
.txt -> text/plain
.cfg -> text/plain
.csv -> text/plain
.conf -> text/plain
.rc -> text/plain
.htm -> text/html
.html -> text/html
.pdf -> application/pdf
.apk -> application/vnd.android.package-archive


问:
jQuery How do set text in a input field then press enter?
jQuery How do set text in a input field then press enter?  I have input field if I manually enter text then submit button will get enabled but if I use jQuery to enter text, then the button won't enabled. How can I make the button enabled?  I am using jQuery with Selenium

Here is what I am looking for verizonwireless.com/support/contact-us on this page, if you enter something in search field, "X" will show up but if you enter using JQuery it won't. So how will I make the "X" show up when I use jquery to enter the text? $('#vgn_q').val('iphone').change(); I tried this but no luck

答:
Check length after set value on text box and enable disable your button.

$('#phone').val('123-123-1234')
if ($('#phone').val().length > 0)
  $('#btnSubmit').removeAttr('disabled');
else
  $('#btnSubmit').attr('disabled', 'disabled');
$('#phone').keyup(function() {
  if ($(this).val() != '') {
    $('#btnSubmit').removeAttr('disabled');
  } else {
    $('#btnSubmit').attr('disabled', 'disabled');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='phone' type='text'/>
<input type='button' disabled='disabled' id='btnSubmit' value='Submit' /></code>```

Body:
Check length after set value on text box and enable disable your button.

$('#phone').val('123-123-1234')
if ($('#phone').val().length > 0)
  $('#btnSubmit').removeAttr('disabled');
else
  $('#btnSubmit').attr('disabled', 'disabled');
$('#phone').keyup(function() {
  if ($(this).val() != '') {
    $('#btnSubmit').removeAttr('disabled');
  } else {
    $('#btnSubmit').attr('disabled', 'disabled');
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='phone' type='text'/>
<input type='button' disabled='disabled' id='btnSubmit' value='Submit' />


问:
rails whenever delete records sql
I tried to a records cleanup after certain period of time (6 month) using gem 'whenever'.

In my whenever scheduler :

```<code>every 1.month, at: '1am' do
  rake 'lib/tasks/cleanup_user.rake'
end
</code>```

In the lib/tasks/cleanup_user.rake

```<code>@user = User.all.where(:created_at > 'Time.6.month.ago').delete
</code>```

It seems about right. However, I got error 'uninitialized constant User'. I am relatively new in rails. Please assist me.

EDIT : I changed the game by run clean one line command :

```<code>set :output, "log/cron.log"
    every 1.minutes, :environment => :development do
      command 'User.where("confirmed = 0 AND created_at <= ?", 6.months.ago).delete'
    end
</code>```

I set the specific environment,and run this in command :

```<code>whenever --set environment=development --update-crontab userscleaning
</code>```

Checking at crontab, its there but still not work. Any thought?

答:
According to the answers here:

# lib/tasks/delete_old_records.rake
namespace :delete do
  desc 'Delete records older than 6 months'
  task old_records: :environment do
    User.where('created_at > ?', 6.month.ago).destroy_all
  end
end
```

<p>Run with:</p>

```RAILS_ENV=production rake delete:old_records
```

<p>In whenever:</p>

<pre class="lang-ruby prettyprint-override"><code>every 1.minutes do
  rake "delete:old_records"
end
</code>```

Or in cron:

```<code>0 8 * * * /bin/bash -l -c 'cd /my/project/releases/current && RAILS_ENV=production rake delete:old_records 2>&1'
</code>```

Title: rails whenever delete records sql

Body:
I tried to a records cleanup after certain period of time (6 month) using gem 'whenever'.

In my whenever scheduler :

every 1.month, at: '1am' do
  rake 'lib/tasks/cleanup_user.rake'
end

In the lib/tasks/cleanup_user.rake

@user = User.all.where(:created_at > 'Time.6.month.ago').delete

It seems about right. However, I got error 'uninitialized constant User'. I am relatively new in rails. Please assist me.

EDIT : I changed the game by run clean one line command :

set :output, "log/cron.log"
    every 1.minutes, :environment => :development do
      command 'User.where("confirmed = 0 AND created_at <= ?", 6.months.ago).delete'
    end

I set the specific environment,and run this in command :

whenever --set environment=development --update-crontab userscleaning

Checking at crontab, its there but still not work. Any thought?

Body:
According to the answers here:

# lib/tasks/delete_old_records.rake
namespace :delete do
  desc 'Delete records older than 6 months'
  task old_records: :environment do
    User.where('created_at > ?', 6.month.ago).destroy_all
  end
end

Run with:

RAILS_ENV=production rake delete:old_records

In whenever:

every 1.minutes do
  rake "delete:old_records"
end

Or in cron:

0 8 * * * /bin/bash -l -c 'cd /my/project/releases/current && RAILS_ENV=production rake delete:old_records 2>&1'


问:
Randomize WooCommerce "Shop By Category"
I'm currently working on a WooCommerce webstore. I have the shop by category option selected and the front page currently shows the first 3 categories.

Instead of the first three categories I would like it to show 3 random categories.

I was able to add a custom function to my function.php (code below) to increase the number of categories listed (to 10) but I'm not able to have the categories show up in a random order.

```<code>add_filter('storefront_product_categories_shortcode_args','custom_storefront_category_per_page' );

// Category Products
function custom_storefront_category_per_page( $args ) {
    $args['number'] = 10;
    return $args;
}
</code>```

I have tired setting $args['orderby'] = "rand"; with no luck. Im guessing that only works for products. What function should I be changing to have the "Shop By Category" section on the front page list 3 random categories instead of 3 categories in AESC or DESC order?

答:
if orderby = rand is not working for your case please try below technique.

-- first you need to get the random category for  products to display in the page.

-- then pass it to the shortcode.

```<code>$categories = get_terms( array(
    'taxonomy' => 'product_cat',
    'hide_empty' => true,
) );

$all_cat = array();

foreach( $categories as $cat ){

$all_cat[] = $cat->name;

}

$random_cat // get and create random category with comma seperated. and pass it to the shortcode.
 $randomCat = "tshirt, shirt";

echo do_shortcode('[products limit="8" columns="4" category="$randomCat" cat_operator="AND"]'); ?>
</code>```

Body:
I'm currently working on a WooCommerce webstore. I have the shop by category option selected and the front page currently shows the first 3 categories.

Instead of the first three categories I would like it to show 3 random categories.

I was able to add a custom function to my function.php (code below) to increase the number of categories listed (to 10) but I'm not able to have the categories show up in a random order.

add_filter('storefront_product_categories_shortcode_args','custom_storefront_category_per_page' );

// Category Products
function custom_storefront_category_per_page( $args ) {
    $args['number'] = 10;
    return $args;
}

I have tired setting $args['orderby'] = "rand"; with no luck. Im guessing that only works for products. What function should I be changing to have the "Shop By Category" section on the front page list 3 random categories instead of 3 categories in AESC or DESC order?

Body:
if orderby = rand is not working for your case please try below technique.

-- first you need to get the random category for  products to display in the page.

-- then pass it to the shortcode.

$categories = get_terms( array(
    'taxonomy' => 'product_cat',
    'hide_empty' => true,
) );

$all_cat = array();

foreach( $categories as $cat ){

$all_cat[] = $cat->name;

}

$random_cat // get and create random category with comma seperated. and pass it to the shortcode.
 $randomCat = "tshirt, shirt";

echo do_shortcode('[products limit="8" columns="4" category="$randomCat" cat_operator="AND"]'); ?>


问:
why if condition is working in a weird way
I am just trying to search the key in a binary search Tree.
Here is what I did.

```<code>int searchBST(int key,node *root){

    if(root->data == key){
        printf("The key %d is in the tree.\n",key);
        return 1;
    }
    if(root->left != NULL){
        searchBST(key,root->left);
        return 0;
    }
    if(root->right != NULL){
        searchBST(key,root->right);
        return 0;
    }
}
</code>```

In the main function,check if function return 1, if it does, the key is in the tree.

```<code>printf("Please enter the key value you wish to search for: ");
scanf("%d",&key);
if((searchBST(key,root)) != 1)
    printf("The key %d is not in the tree.\n",key);
</code>```

if the key is not in the tree it will print :

```<code>The key %d is not in the tree.
</code>```

which is correct. So here comes the weird part, if the key is in the tree, sometime system will print out :

```<code>The key %d is in the tree.
</code>```

and other time system will print both:

```<code>The key %d is in the tree.
The key %d is not in the tree.
</code>```

So what can I do to fix it?

Here is my entire code

```<code>#include<stdio.h>
#include<malloc.h>
// This program will create a binary search tree or a max-heap, as chosen from a menu.
typedef struct BSTNode{
int data;
struct Node *left;
struct Node *right;
}node;
node* getNewNode(int data){
    node *new = (node*)malloc(sizeof(node));
    new->data = data;
    new->left = new->right = NULL;
    return new;
}
void heapPreOrder(int heapRootIndex,int array[],int numOfNodes){
int i = heapRootIndex;
printf("%d\t",array[i]);
if( 2*i+1<numOfNodes)
    heapPreOrder(2*i+1,array,numOfNodes);
if(2*i+2<numOfNodes)
    heapPreOrder(2*i+2,array,numOfNodes);
}
void disLevelOrder(int array[],int numOfNodes){
int i;
for(i = 0;i < numOfNodes;i++){
    printf("%d\t",array[i]);
}
printf("\n");
}
node* insertBST(int data,node *root){
if(root == NULL){
    root = getNewNode(data);
}
else{
    if(data <= root->data){
        root->left = insertBST(data,root->left);
    }
        else if(data >= root->data)
        root->right= insertBST(data,root->right);
    }
    return root;

}

int searchBST(int key,node *root){

 if (!root) return 0;
if (root->data == key) return 1;
if (root->data > key) return searchBST(root->left, key);
return searchBST(root->right, key);
}
void levelOrder(node* root, int level){
if (root == NULL)
    return;
if (level == 1)
    printf("%d\t", root->data);
else if (level > 1)
{
    levelOrder(root->left, level-1);
    levelOrder(root->right, level-1);
}
}
int findHeight(node* root)
{
if (root==NULL)
    return 0;
else
{
    int leftHeight = findHeight(root->left);
    int rightHeight = findHeight(root->right);

    if(leftHeight >= rightHeight)
        return leftHeight+1;
    else
        return rightHeight+1;
}

}
void insertHeap(int key,int numOfNodes,int array[]){
int i,j;
i = numOfNodes-1;
if(i%2 == 1 && array[i] > array[(i-1)/2]){  //if left child is greater than parent
            swap(&array[i],&array[(i-1)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
        if(i%2 == 0 && array[i] > array[(i-2)/2]){//if right child is greater than parent
            swap(&array[i],&array[(i-2)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
}
void searchHeap(int key,int array[],int numOfNodes){
int i;
for(i = 0;i < numOfNodes;i++){
    if(key == array[i]){
        printf("The key %d is in the heap.\n",key);
        return;
    }
}
printf("The key %d is not in the heap.\n",key);
}
void preorder(node *root){
if(root!=NULL){
    printf("%d\t",root->data);
    preorder(root->left);
    preorder(root->right);
}
}
void swap(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;

}
int main(){
int i,j,numOfNodes,key,height;
char choice,option;
node *root = (node*)malloc(sizeof(node));       //initialize root;
root = NULL;
printf("Enter the number of nodes in the linked list to be initially created: ");
scanf("%d",&numOfNodes);
int array[numOfNodes];           //store all the data in the array first
printf("Enter the data value to be placed in the node: ");
scanf("%d",&array[0]);
root = insertBST(array[0],root);           //create the root
//root->left = getNewNode(array[0]);
for(i = 1;i < numOfNodes;i++){
    printf("Enter the data value to be placed in the node: ");                 //put each data into array, leave the index 0 empty
    scanf("%d",&array[i]);
}
printf("What do you wish to create a Binary search Tree (B) or a Max-Heap (H)?: ");
scanf(" %c",&choice);
if(choice == 'B' || choice == 'b'){         //if user wants to build a Binary search Tree
    for(i = 1;i<numOfNodes;i++){
        insertBST(array[i],root);
    }
        printf("Binary search tree build successfully.\n");
}

if(choice == 'H'|| choice == 'h'){         //if user wants to build a Max-Heap
        for(i = 1;i<numOfNodes;i++){          //build the max heap
        if(i%2 == 1 && array[i] > array[(i-1)/2]){  //if left child is greater than parent
            swap(&array[i],&array[(i-1)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
        if(i%2 == 0 && array[i] > array[(i-2)/2]){  //if right child is greater than parent
            swap(&array[i],&array[(i-2)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
    }
        printf("Heap successfully created.\n");
    }
while(choice == 'B'||choice == 'b'){
    printf("What do you wish to do?\n");
    printf("Show Preorder Traversal(P)\tShow Level order Traversal(L)\tSearch(S)\tInsert(I)\tQuit(Q)\n");
    printf("Please enter a choice: ");
    scanf(" %c",&option);
        if(option == 'p'||option == 'P'){
        preorder(root);
        printf("\n");
    }
    if(option == 'L'||option == 'l'){
        height = findHeight(root);
        for(i = 1;i <= height;i++){
            levelOrder(root,i);
        }
        printf("\n");
    }
    if(option == 'S'||option == 's'){     //This is the part I have trouble with
        printf("Please enter the key value you wish to search for: ");
        scanf("%d",&key);
        if((searchBST(key,root)) != 1)
        printf("The key %d is not in the tree.\n",key);
    }
    if(option == 'I'||option == 'i'){       //if user wants to insert a number
        printf("please enter the key value you wish to insert: ");
        scanf("%d",&key);
        insertBST(key,root);
        printf("The key value %d was successfully inserted.\n",key);
    }
    if(option == 'q'||option == 'Q'){
        printf("Thanks for using my program, please rate 100 as feedback! Have a wonderful day :)");
        return 0;
    }
    printf("\n");
}
while(choice == 'H'|| choice == 'h'){
    printf("What do you wish to do?\n");
    printf("Show Preorder Traversal(P)\tShow Level order Traversal(L)\tSearch(S)\tInsert(I)\tQuit(Q)\n");
    printf("Please enter a choice: ");
    scanf(" %c",&option);
    if(option == 'p'||option == 'P'){
        heapPreOrder(0,array,numOfNodes);
        printf("\n");
    }
    if(option == 'L'||option == 'l'){
        disLevelOrder(array,numOfNodes);
        printf("\n");
    }
    if(option == 'S'||option == 's'){
        printf("Please enter the key value you wish to search for: ");
        scanf("%d",&key);
        searchHeap(key,array,numOfNodes);
    }
    if(option == 'I'||option == 'i'){       //if user wants to insert a number
        printf("please enter the key value you wish to insert: ");
        scanf("%d",&key);
        numOfNodes++;
        array[numOfNodes-1] = key;
        insertHeap(key,numOfNodes,array);
        printf("The key value %d was successfully inserted.\n",key);
    }
    if(option == 'q'||option == 'Q'){
        printf("Thanks for using my program, please rate 100 as feedback! Have a wonderful day :)");
        return 0;
    }
    printf("\n");
}
</code>```

}

答:
You should not search the whole binary search tree for a key. You should follow the correct path. That is why you should compare you key with the current root value. If the value is same as key, then this is the output. If the key is less than the root value, you should go to left subtree, otherwise right one.

```<code>int searchBST(int key, node* root) {
    if (!root) return 0;
    if(root->data == key) {
        printf("The key %d is in the tree.\n",key);
        return 1;
    }
    if (root->data > key) return searchBST(key, root->left);
    return searchBST(key, root->right);
}
</code>```

In your case, you are traversing the whole tree even if you found the key. So that's why sometime you are getting both output.

Body:
I am just trying to search the key in a binary search Tree.
Here is what I did.

int searchBST(int key,node *root){

    if(root->data == key){
        printf("The key %d is in the tree.\n",key);
        return 1;
    }
    if(root->left != NULL){
        searchBST(key,root->left);
        return 0;
    }
    if(root->right != NULL){
        searchBST(key,root->right);
        return 0;
    }
}

In the main function,check if function return 1, if it does, the key is in the tree.

printf("Please enter the key value you wish to search for: ");
scanf("%d",&key);
if((searchBST(key,root)) != 1)
    printf("The key %d is not in the tree.\n",key);

if the key is not in the tree it will print :

The key %d is not in the tree.

which is correct. So here comes the weird part, if the key is in the tree, sometime system will print out :

The key %d is in the tree.

and other time system will print both:

The key %d is in the tree.
The key %d is not in the tree.

So what can I do to fix it?

Here is my entire code

#include<stdio.h>
#include<malloc.h>
// This program will create a binary search tree or a max-heap, as chosen from a menu.
typedef struct BSTNode{
int data;
struct Node *left;
struct Node *right;
}node;
node* getNewNode(int data){
    node *new = (node*)malloc(sizeof(node));
    new->data = data;
    new->left = new->right = NULL;
    return new;
}
void heapPreOrder(int heapRootIndex,int array[],int numOfNodes){
int i = heapRootIndex;
printf("%d\t",array[i]);
if( 2*i+1<numOfNodes)
    heapPreOrder(2*i+1,array,numOfNodes);
if(2*i+2<numOfNodes)
    heapPreOrder(2*i+2,array,numOfNodes);
}
void disLevelOrder(int array[],int numOfNodes){
int i;
for(i = 0;i < numOfNodes;i++){
    printf("%d\t",array[i]);
}
printf("\n");
}
node* insertBST(int data,node *root){
if(root == NULL){
    root = getNewNode(data);
}
else{
    if(data <= root->data){
        root->left = insertBST(data,root->left);
    }
        else if(data >= root->data)
        root->right= insertBST(data,root->right);
    }
    return root;

}

int searchBST(int key,node *root){

 if (!root) return 0;
if (root->data == key) return 1;
if (root->data > key) return searchBST(root->left, key);
return searchBST(root->right, key);
}
void levelOrder(node* root, int level){
if (root == NULL)
    return;
if (level == 1)
    printf("%d\t", root->data);
else if (level > 1)
{
    levelOrder(root->left, level-1);
    levelOrder(root->right, level-1);
}
}
int findHeight(node* root)
{
if (root==NULL)
    return 0;
else
{
    int leftHeight = findHeight(root->left);
    int rightHeight = findHeight(root->right);

    if(leftHeight >= rightHeight)
        return leftHeight+1;
    else
        return rightHeight+1;
}

}
void insertHeap(int key,int numOfNodes,int array[]){
int i,j;
i = numOfNodes-1;
if(i%2 == 1 && array[i] > array[(i-1)/2]){  //if left child is greater than parent
            swap(&array[i],&array[(i-1)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
        if(i%2 == 0 && array[i] > array[(i-2)/2]){//if right child is greater than parent
            swap(&array[i],&array[(i-2)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
}
void searchHeap(int key,int array[],int numOfNodes){
int i;
for(i = 0;i < numOfNodes;i++){
    if(key == array[i]){
        printf("The key %d is in the heap.\n",key);
        return;
    }
}
printf("The key %d is not in the heap.\n",key);
}
void preorder(node *root){
if(root!=NULL){
    printf("%d\t",root->data);
    preorder(root->left);
    preorder(root->right);
}
}
void swap(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;

}
int main(){
int i,j,numOfNodes,key,height;
char choice,option;
node *root = (node*)malloc(sizeof(node));       //initialize root;
root = NULL;
printf("Enter the number of nodes in the linked list to be initially created: ");
scanf("%d",&numOfNodes);
int array[numOfNodes];           //store all the data in the array first
printf("Enter the data value to be placed in the node: ");
scanf("%d",&array[0]);
root = insertBST(array[0],root);           //create the root
//root->left = getNewNode(array[0]);
for(i = 1;i < numOfNodes;i++){
    printf("Enter the data value to be placed in the node: ");                 //put each data into array, leave the index 0 empty
    scanf("%d",&array[i]);
}
printf("What do you wish to create a Binary search Tree (B) or a Max-Heap (H)?: ");
scanf(" %c",&choice);
if(choice == 'B' || choice == 'b'){         //if user wants to build a Binary search Tree
    for(i = 1;i<numOfNodes;i++){
        insertBST(array[i],root);
    }
        printf("Binary search tree build successfully.\n");
}

if(choice == 'H'|| choice == 'h'){         //if user wants to build a Max-Heap
        for(i = 1;i<numOfNodes;i++){          //build the max heap
        if(i%2 == 1 && array[i] > array[(i-1)/2]){  //if left child is greater than parent
            swap(&array[i],&array[(i-1)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
        if(i%2 == 0 && array[i] > array[(i-2)/2]){  //if right child is greater than parent
            swap(&array[i],&array[(i-2)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
    }
        printf("Heap successfully created.\n");
    }
while(choice == 'B'||choice == 'b'){
    printf("What do you wish to do?\n");
    printf("Show Preorder Traversal(P)\tShow Level order Traversal(L)\tSearch(S)\tInsert(I)\tQuit(Q)\n");
    printf("Please enter a choice: ");
    scanf(" %c",&option);
        if(option == 'p'||option == 'P'){
        preorder(root);
        printf("\n");
    }
    if(option == 'L'||option == 'l'){
        height = findHeight(root);
        for(i = 1;i <= height;i++){
            levelOrder(root,i);
        }
        printf("\n");
    }
    if(option == 'S'||option == 's'){     //This is the part I have trouble with
        printf("Please enter the key value you wish to search for: ");
        scanf("%d",&key);
        if((searchBST(key,root)) != 1)
        printf("The key %d is not in the tree.\n",key);
    }
    if(option == 'I'||option == 'i'){       //if user wants to insert a number
        printf("please enter the key value you wish to insert: ");
        scanf("%d",&key);
        insertBST(key,root);
        printf("The key value %d was successfully inserted.\n",key);
    }
    if(option == 'q'||option == 'Q'){
        printf("Thanks for using my program, please rate 100 as feedback! Have a wonderful day :)");
        return 0;
    }
    printf("\n");
}
while(choice == 'H'|| choice == 'h'){
    printf("What do you wish to do?\n");
    printf("Show Preorder Traversal(P)\tShow Level order Traversal(L)\tSearch(S)\tInsert(I)\tQuit(Q)\n");
    printf("Please enter a choice: ");
    scanf(" %c",&option);
    if(option == 'p'||option == 'P'){
        heapPreOrder(0,array,numOfNodes);
        printf("\n");
    }
    if(option == 'L'||option == 'l'){
        disLevelOrder(array,numOfNodes);
        printf("\n");
    }
    if(option == 'S'||option == 's'){
        printf("Please enter the key value you wish to search for: ");
        scanf("%d",&key);
        searchHeap(key,array,numOfNodes);
    }
    if(option == 'I'||option == 'i'){       //if user wants to insert a number
        printf("please enter the key value you wish to insert: ");
        scanf("%d",&key);
        numOfNodes++;
        array[numOfNodes-1] = key;
        insertHeap(key,numOfNodes,array);
        printf("The key value %d was successfully inserted.\n",key);
    }
    if(option == 'q'||option == 'Q'){
        printf("Thanks for using my program, please rate 100 as feedback! Have a wonderful day :)");
        return 0;
    }
    printf("\n");
}

}

Body:
You should not search the whole binary search tree for a key. You should follow the correct path. That is why you should compare you key with the current root value. If the value is same as key, then this is the output. If the key is less than the root value, you should go to left subtree, otherwise right one.

int searchBST(int key, node* root) {
    if (!root) return 0;
    if(root->data == key) {
        printf("The key %d is in the tree.\n",key);
        return 1;
    }
    if (root->data > key) return searchBST(key, root->left);
    return searchBST(key, root->right);
}

In your case, you are traversing the whole tree even if you found the key. So that's why sometime you are getting both output.


问:
iPhone image distortion
Are there any reasons why the simulator will display UIImageViews properly, but incorrectly on the iPhone?

My Process:
An image in a PNG file
Start a UIGraphicsBeginImageContext()
Draw the PNG in a CGrect
Draw text in the CGRect
Create an UIImage from the context
Set the image of a UIImaveView to the UIImage
Set the frame of the UIImageView to the size of the PNG
Add as a subview

Outcome:
The image does not display correctly. The rightmost 1-3 pixels of the image is just a vertical white line. This occurs only on the device and not on the simulator. I can fix the problem, but only by increasing the size of the UIImageView.  If I increase the size.height of the UIImageView by 1 pixel, it displays the UIImage correctly.  Of course, these leaves the iPhone to scale my image before drawing it on screen which is not desirable.

Any ideas why this occurs or any fixes for it?
(I will post my code if needed)

答: Have you checked the scaling/resize options for the UIImageView?</p>

OwnerDisplayName: Corey

Title: iPhone image distortion

LastEditorDisplayName: erickson

OwnerDisplayName: August


问:
Liquibase data loading into HSQLDB with a sequence
I'm attempting to load some data into an HSQLDB database using Liquibase 1.9.5. I have a loadData command as follows:

```<code><loadData tableName="LIST_ITEM_TYPE" file="data/global/list_item_type.csv">
    <column name="ID" type="NUMERIC" />
    <column name="NAME" type="STRING" />
    <column name="DESCRIPTION" type="STRING" />
</loadData>
</code>```

In my CSV data file I'm attempting to set the ID value to the next value from an existing sequence:

```<code>id,name,description
next value for SEQ_ITEM_TYPE_ID,Test Name,A test description
</code>```

However, this doesn't work as it generates the following SQL:

```<code>INSERT INTO LIST_ITEM_TYPE (id, description, name) VALUES ('next value for SEQ_ITEM_TYPE_ID', 'A test description', 'Test Name')
</code>```

This is almost correct, except that the single quotes that Liquibase added around the next value for SEQ_ITEM_TYPE_ID cause HSQLDB to give the following error:

```<code>java.sql.SQLException: data exception: invalid character value for cast
</code>```

If I remove the sinqle quotes and run that SQL manually, it works as expected.

So, my question is, how do I use the Liquibase loadData command pulling data from a CSV file while populating one of the columns from a sequence?

答:
You may be able to use the  tag like this:</p>

```<code><modifySql>
   <replace
        replace="'next value for SEQ_ITEM_TYPE_ID'"
        with="next value for SEQ_ITEM_TYPE_ID">
</modifySql>
</code>```

Body:
I'm attempting to load some data into an HSQLDB database using Liquibase 1.9.5. I have a loadData command as follows:

<loadData tableName="LIST_ITEM_TYPE" file="data/global/list_item_type.csv">
    <column name="ID" type="NUMERIC" />
    <column name="NAME" type="STRING" />
    <column name="DESCRIPTION" type="STRING" />
</loadData>

In my CSV data file I'm attempting to set the ID value to the next value from an existing sequence:

id,name,description
next value for SEQ_ITEM_TYPE_ID,Test Name,A test description

However, this doesn't work as it generates the following SQL:

INSERT INTO LIST_ITEM_TYPE (id, description, name) VALUES ('next value for SEQ_ITEM_TYPE_ID', 'A test description', 'Test Name')

This is almost correct, except that the single quotes that Liquibase added around the next value for SEQ_ITEM_TYPE_ID cause HSQLDB to give the following error:

java.sql.SQLException: data exception: invalid character value for cast

If I remove the sinqle quotes and run that SQL manually, it works as expected.

So, my question is, how do I use the Liquibase loadData command pulling data from a CSV file while populating one of the columns from a sequence?

Body:
You may be able to use the  tag like this:

<modifySql>
   <replace
        replace="'next value for SEQ_ITEM_TYPE_ID'"
        with="next value for SEQ_ITEM_TYPE_ID">
</modifySql>


问:
Post Image showing Size In Single.php file
i hope you are doing very well,
please open this link
https://www.pixelstalk.net/winter-backgrounds/winter-background-for-desktop/

and screen shot link here
http://myprintscreen.com/s/p0bp/49cbf6d290

How can i add this option to showing this height + width and image size in my wordpress single post?

Thanks

答:
Height & Width:

Try the following. First, add this piece of code to the template:

```<code>$image_data = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "full" );
</code>```

$image_data will now return an array containing the url, width, and height (function reference). To get width & height, you might do this:

```<code>$image_width = $image_data[1];
$image_height = $image_data[2];
</code>```

In your specific example, after adding the two pieces of code above to your template, you might do this:

```<code>echo '<label class="dimension">  '.$image_width.' x '.$image_height.'</label>';
</code>```

Size:

```<code>$image_size = size_format(filesize( get_attached_file( get_post_thumbnail_id( $post->ID ), "full" ) ));
</code>```

And in your template, add it like this:

```<code>echo '<label class="data_size"><strong>Image size: </strong>'.$image_size.'</label>';
</code>```

Body:
Height & Width:

Try the following. First, add this piece of code to the template:

$image_data = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "full" );

$image_data will now return an array containing the url, width, and height (function reference). To get width & height, you might do this:

$image_width = $image_data[1];
$image_height = $image_data[2];

In your specific example, after adding the two pieces of code above to your template, you might do this:

echo '<label class="dimension">  '.$image_width.' x '.$image_height.'</label>';

Size:

$image_size = size_format(filesize( get_attached_file( get_post_thumbnail_id( $post->ID ), "full" ) ));

And in your template, add it like this:

echo '<label class="data_size"><strong>Image size: </strong>'.$image_size.'</label>';