Parses problems.txt and returns problem text
766025
def text(self):
        """"""
        def _problem_iter(problem_num):
            problem_file = os.path.join(EULER_DATA, 'problems.txt')

            with open(problem_file) as f:
                is_problem = False
                last_line = ''

                for line in f:
                    if line.strip() == 'Problem %i' % problem_num:
                        is_problem = True

                    if is_problem:
                        if line == last_line == '\n':
                            break
                        else:
                            yield line[:-1]
                            last_line = line

        problem_lines = [line for line in _problem_iter(self.num)]

        if problem_lines:
            # First three lines are the problem number, the divider line,
            # and a newline, so don't include them in the returned string.
            # Also, strip the final newline.
            return '\n'.join(problem_lines[3:-1])
        else:
            msg = 'Problem %i not found in problems.txt.' % self.num
            click.secho(msg, fg='red')
            click.echo('If this problem exists on Project Euler, consider '
                       'submitting a pull request to EulerPy on GitHub.')
            sys.exit(1)
1232461
def parse(self, format_string):
        """"""
        txt, state = '', 0
        colorstack = [(None, None)]
        itokens = self.tokenize(format_string)

        for token, escaped in itokens:
            if token == self._START_TOKEN and not escaped:
                if txt:
                    yield txt, colorstack[-1]
                    txt = ''

                state += 1
                colors = self.extract_syntax(colorise.compat.next(itokens)[0])
                colorstack.append(tuple(b or a
                                        for a, b in zip(colorstack[-1],
                                                        colors)))
            elif token == self._FMT_TOKEN and not escaped:
                # if state == 0:
                #     raise ColorSyntaxError("Missing '{0}'"
                #                            .format(self._START_TOKEN))

                if state % 2 != 0:
                    state += 1
                else:
                    txt += token
            elif token == self._STOP_TOKEN and not escaped:
                if state < 2:
                    raise ColorSyntaxError("Missing '{0}' or '{1}'"
                                           .format(self._STOP_TOKEN,
                                                   self._FMT_TOKEN))

                if txt:
                    yield txt, colorstack[-1]
                    txt = ''

                state -= 2
                colorstack.pop()
            else:
                txt += token

        if state != 0:
            raise ColorSyntaxError("Invalid color format")

        if txt:
            yield txt, colorstack[-1]
1144536
def get_input(problem):
    "
    input_data = load_input()
    pbsplit = problem.split(":")
    problem_input = input_data['input'][pbsplit[0]]
    if isinstance(problem_input, dict) and "filename" in problem_input and "value" in problem_input:
        if len(pbsplit) > 1 and pbsplit[1] == 'filename':
            return problem_input["filename"]
        else:
            return open(problem_input["value"], 'rb').read()
    else:
        return problem_input
550411
def parse_error(output_dir):
    
    sys.stderr.seek(0)
    std_err = sys.stderr.read().decode('utf-8')
    err_file = os.path.join(output_dir, "eplusout.err")
    if os.path.isfile(err_file):
        with open(err_file, "r") as f:
            ep_err = f.read()
    else:
        ep_err = "<File not found>"
    message = "\r\n{std_err}\r\nContents of EnergyPlus error file at {err_file}\r\n{ep_err}".format(**locals())
    return message
1173695
def get_requirements(cls):
        """"""
        try:
            with open("requirements.txt") as f:
                return tuple(parse_requirements(f.readlines()))
        except IOError as e:
            LOG.debug("Couldn't open requirements file: %s", e)
            return ()
87383
def x_parse_error(err, content, source):
    
    lineno, column = err.position
    if "<doc>" in content:
        #Adjust the position since we are taking the <doc> part out of the tags
        #since we may have put that in ourselves.
        column -= 5
    start = lineno - (1 if lineno == 1 else 2)
    lines = []
    tcontent = content.replace("<doc>", "").replace("</doc>", "").split('\n')
    for context in IT.islice(tcontent, start, lineno):
        lines.append(context.strip())
    last = wrap_line(lines.pop(), column)
    lines.extend(last)
    
    caret = '{:=>{}}'.format('^', len(last[-1]))
    if source is not None:
        err.msg = '\nIn: {}\n{}\n{}\n{}'.format(source, err, '\n'.join(lines), caret)
    else:
        err.msg = '{}\n{}\n{}'.format(err, '\n'.join(lines), caret)

    raise err
1086868
def scan(self, string):
        
        # In the following example, first scan the string for "good" and "bad":
        # p = Pattern.fromstring("good|bad NN")
        # for s in open("parsed.txt"):
        #     if p.scan(s):
        #         s = Sentence(s)
        #         m = p.search(s)
        #         if m:
        #             print(m)
        w = (constraint.words for constraint in self.sequence if not constraint.optional)
        w = itertools.chain(*w)
        w = [w.strip(WILDCARD) for w in w if WILDCARD not in w[1:-1]]
        if w and not any(w in string.lower() for w in w):
            return False
        return True
787689
def parse_strings(content="", filename=None):
    
    if filename is not None:
        content = _get_content(filename=filename)

    stringset = []
    f = content
    if f.startswith(u'\ufeff'):
        f = f.lstrip(u'\ufeff')
    #regex for finding all comments in a file
    cp = r'(?:/\*(?P<comment>(?:[^*]|(?:\*+[^*/]))*\**)\*/)'
    p = re.compile(r'(?:%s[ \t]*[\n]|[\r\n]|[\r]){0,1}(?P<line>(("(?P<key>[^"\\]*(?:\\.[^"\\]*)*)")|(?P<property>\w+))\s*=\s*"(?P<value>[^"\\]*(?:\\.[^"\\]*)*)"\s*;)'%cp, re.DOTALL|re.U)
    #c = re.compile(r'\s*/\*(.|\s)*?\*/\s*', re.U)
    c = re.compile(r'//[^\n]*\n|/\*(?:.|[\r\n])*?\*/', re.U)
    ws = re.compile(r'\s+', re.U)
    end=0
    start = 0
    for i in p.finditer(f):
        start = i.start('line')
        end_ = i.end()
        key = i.group('key')
        comment = i.group('comment') or ''
        if not key:
            key = i.group('property')
        value = i.group('value')
        while end < start:
            m = c.match(f, end, start) or ws.match(f, end, start)
            if not m or m.start() != end:
                print("Invalid syntax: %s" %\
                        f[end:start])
            end = m.end()
        end = end_
        key = _unescape_key(key)
        stringset.append({'key': key, 'value': _unescape(value), 'comment': comment})
    return stringset
1162829
function parseError (err) {
    var filePath, lineNum, splitLines
    var result = {}

    // For root files that syntax-error doesn't pick up:
    var parseFilePrefix = 'Parsing file '
    if (err.indexOf(parseFilePrefix) === 0) {
      var pathWithErr = err.substring(parseFilePrefix.length)
      filePath = getFilePath(pathWithErr)
      if (!filePath) return result
      result.path = filePath
      var messageAndLine = pathWithErr.substring(filePath.length)
      lineNum = /\((\d+):(\d+)\)/.exec(messageAndLine)
      if (!lineNum) return result
      result.message = messageAndLine.substring(1, lineNum.index).trim()
      result.line = parseInt(lineNum[1], 10)
      result.column = parseInt(lineNum[2], 10)
      result.format = true
      return result
    }

    // if module not found
    var cannotFindModule = /^Cannot find module '(.+)' from '(.+)'(?:$| while parsing file: (.*)$)/.exec(err.trim())
    if (cannotFindModule) {
      result.missingModule = cannotFindModule[1]
      result.path = cannotFindModule[3] || cannotFindModule[2]
      result.message = "Cannot find module '" + result.missingModule + "'"
      result.format = true
      return result
    }

    // syntax-error returns the path and line number, also a \n at start
    err = err.trim()
    filePath = getFilePath(err)
    if (!filePath) return result
    result.path = filePath

    var restOfMessage = err.substring(filePath.length)
    var parsedSyntaxError = /^:(\d+)/.exec(restOfMessage)
    if (parsedSyntaxError) { // this is a syntax-error
      lineNum = parseInt(parsedSyntaxError[1], 10)
      if (isFinite(lineNum)) result.line = lineNum
      splitLines = restOfMessage.split('\n')
      var code = splitLines.slice(1, splitLines.length - 1).join('\n')
      result.code = code
      result.message = splitLines[splitLines.length - 1]
      result.format = true
      return result
    }

    // remove colon
    restOfMessage = restOfMessage.substring(1).trim()
    var whileParsing = 'while parsing file: '
    var whileParsingIdx = restOfMessage.indexOf(whileParsing)
    if (whileParsingIdx >= 0) {
      var beforeWhile = restOfMessage.substring(0, whileParsingIdx)
      lineNum = /\((\d+):(\d+)\)/.exec(beforeWhile.split('\n')[0])
      var messageStr = beforeWhile
      if (lineNum) {
        var line = parseInt(lineNum[1], 10)
        var col = parseInt(lineNum[2], 10)
        if (isFinite(line)) result.line = line
        if (isFinite(col)) result.column = col
        messageStr = messageStr.substring(0, lineNum.index)
      }
      result.message = messageStr.trim()
      splitLines = restOfMessage.split('\n')
      result.code = splitLines.slice(2).join('\n')
      result.format = true
    }

    return result
  }
365524
def _parse(self, line):
        """"""
        try:
            result = line.split(':', maxsplit=4)
            filename, line_num_txt, column_txt, message_type, text = result
        except ValueError:
            return

        try:
            self.line_num = int(line_num_txt.strip())
            self.column = int(column_txt.strip())
        except ValueError:
            return

        self.filename = filename
        self.message_type = message_type.strip()
        self.text = text.strip()
        self.valid = True
1057240
def FormatProblem(self, d=None):
    
    if not d:
      d = self.GetDictToFormat()

    output_error_text = self.__class__.ERROR_TEXT % d
    if ('reason' in d) and d['reason']:
      return '%s\n%s' % (output_error_text, d['reason'])
    else:
      return output_error_text
218937
def read_text(forfn, nrows=None, verbose=True):
    
    """
    tqdm_prog = tqdm if verbose else no_tqdm
    nrows = wc(forfn, nrows=nrows)  # not necessary when nrows==None
    lines = np.empty(dtype=object, shape=nrows)
    with ensure_open(forfn) as f:
        for i, line in enumerate(tqdm_prog(f, total=nrows)):
            if i >= len(lines):
                break
            lines[i] = ensure_str(line).rstrip('\n').rstrip('\r')
        if all('\t' in line for line in lines):
            num_tabs = [sum([1 for c in line if c == '\t']) for line in lines]
            del lines
            if all(i == num_tabs[0] for i in num_tabs):
                f.seek(0)
                return read_csv(f, sep='\t', header=None, nrows=nrows)
        elif sum((1 for line in lines if any((tag.lower() in line.lower() for tag in HTML_TAGS)))
                ) / float(len(lines)) > .05:
            return np.array(html2text(EOL.join(lines)).split(EOL))
    return lines
334576
def get_issues():
        """"""
        issues = []
        for entry in Logger.journal:
            if entry.level >= WARNING:
                issues.append(entry)
        return issues
291500
def parse(text):
    
    ret = Docstring()
    if not text:
        return ret

    text = inspect.cleandoc(text)
    match = re.search('^:', text, flags=re.M)
    if match:
        desc_chunk = text[:match.start()]
        meta_chunk = text[match.start():]
    else:
        desc_chunk = text
        meta_chunk = ''

    parts = desc_chunk.split('\n', 1)
    ret.short_description = parts[0] or None
    if len(parts) > 1:
        long_desc_chunk = parts[1] or ''
        ret.blank_after_short_description = long_desc_chunk.startswith('\n')
        ret.blank_after_long_description = long_desc_chunk.endswith('\n\n')
        ret.long_description = long_desc_chunk.strip() or None

    for match in re.finditer(
            r'(^:.*?)(?=^:|\Z)', meta_chunk, flags=re.S | re.M
    ):
        chunk = match.group(0)
        if not chunk:
            continue
        try:
            args_chunk, desc_chunk = chunk.lstrip(':').split(':', 1)
        except ValueError:
            raise ParseError(
                'Error parsing meta information near "{}".'.format(chunk)
            )
        args = args_chunk.split()
        desc = desc_chunk.strip()
        if '\n' in desc:
            first_line, rest = desc.split('\n', 1)
            desc = first_line + '\n' + inspect.cleandoc(rest)
        ret.meta.append(DocstringMeta(args, description=desc, type=None))

    return ret
1374267
def parser_help_text(help_text):
    """"""
    if help_text is None:
        return None, {}

    main_text = ''
    params_help = {}

    for line in help_text.splitlines():
        line = line.strip()
        match = re.search(r':\s*param\s*(?P<param>\w+)\s*:(?P<help>.*)$', line)
        if match:
            params_help[match.group('param')] = match.group('help').strip()
        else:
            main_text += line + ' '

    main_text = main_text.strip()
    return main_text, params_help
289592
def from_string(cls, s):
        """"""
        for num, text in cls._STATUS_TABLE.items():
            if text == s: return cls(num)
        else:
            #raise ValueError("Wrong string %s" % s)
            logger.warning("Got unknown status: %s" % s)
            return cls.from_string("UNKNOWN")
313083
def _format_issue(issue):
    '''
    
    '''
    ret = {'id': issue.get('id'),
           'issue_number': issue.get('number'),
           'state': issue.get('state'),
           'title': issue.get('title'),
           'user': issue.get('user').get('login'),
           'html_url': issue.get('html_url')}

    assignee = issue.get('assignee')
    if assignee:
        assignee = assignee.get('login')

    labels = issue.get('labels')
    label_names = []
    for label in labels:
        label_names.append(label.get('name'))

    milestone = issue.get('milestone')
    if milestone:
        milestone = milestone.get('title')

    ret['assignee'] = assignee
    ret['labels'] = label_names
    ret['milestone'] = milestone

    return ret