r"""Replace all substrings of the specified string value that match regexp with rep.

    >>> df = spark.createDataFrame([('100-200',)], ['str'])
    >>> df.select(regexp_replace('str', r'(\d+)', '--').alias('d')).collect()
    [Row(d=u'-----')]
424855
def regexp_replace(str, pattern, replacement):
    
    """
    sc = SparkContext._active_spark_context
    jc = sc._jvm.functions.regexp_replace(_to_java_column(str), pattern, replacement)
    return Column(jc)
1138287
function (regexp, replaceValue) {
      var res = maybeCallNative($replace, regexp, this, replaceValue);
      if (res.done) return res.value;

      var rx = anObject(regexp);
      var S = String(this);
      var functionalReplace = typeof replaceValue === 'function';
      if (!functionalReplace) replaceValue = String(replaceValue);
      var global = rx.global;
      if (global) {
        var fullUnicode = rx.unicode;
        rx.lastIndex = 0;
      }
      var results = [];
      while (true) {
        var result = regExpExec(rx, S);
        if (result === null) break;
        results.push(result);
        if (!global) break;
        var matchStr = String(result[0]);
        if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
      }
      var accumulatedResult = '';
      var nextSourcePosition = 0;
      for (var i = 0; i < results.length; i++) {
        result = results[i];
        var matched = String(result[0]);
        var position = max(min(toInteger(result.index), S.length), 0);
        var captures = [];
        // NOTE: This is equivalent to
        //   captures = result.slice(1).map(maybeToString)
        // but for some reason `nativeSlice.call(result, 1, result.length)` (called in
        // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and
        // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it.
        for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j]));
        var namedCaptures = result.groups;
        if (functionalReplace) {
          var replacerArgs = [matched].concat(captures, position, S);
          if (namedCaptures !== undefined) replacerArgs.push(namedCaptures);
          var replacement = String(replaceValue.apply(undefined, replacerArgs));
        } else {
          replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue);
        }
        if (position >= nextSourcePosition) {
          accumulatedResult += S.slice(nextSourcePosition, position) + replacement;
          nextSourcePosition = position + matched.length;
        }
      }
      return accumulatedResult + S.slice(nextSourcePosition);
    }
1294611
function replaceAll(str, find, replace) {
  return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
806723
def string2dt(self, s, lower_bound=None):
        """"""
        original_s = s

        result = {}
        dt = None

        # if s is completely empty, return start or end,
        # depending on what parameter is evaluated
        if s == '':
            return self.end if lower_bound else self.start

        # first try to match the defined regexes
        for idx in self.dtRegexes:
            regex = self.dtRegexes[idx]
            mo = regex.search(s)
            # if match was found, cut it out of original string and
            # store in result
            if mo:
                result[idx] = mo
                s = s[:mo.start(0)] + s[mo.end(0):]

        # handle constants
        if 'constant' in result:
            constant = result['constant'].group(0).strip()
            if constant == 'end':
                dt = self.end
            elif constant == 'start':
                dt = self.start
            elif constant == 'today':
                dt = datetime.now().replace(hour=0, minute=0, second=0,
                                            microsecond=0)
            elif constant == 'yesterday':
                dt = datetime.now().replace(hour=0, minute=0, second=0,
                                            microsecond=0) - timedelta(days=1)
            elif constant == 'now':
                dt = datetime.now()

        elif 'weekday' in result:
                weekday = result['weekday'].group(0).strip()
                # assume most-recently occured weekday in logfile
                most_recent_date = self.end.replace(hour=0, minute=0, second=0,
                                                    microsecond=0)
                offset = (most_recent_date.weekday() -
                          self.weekdays.index(weekday)) % 7
                dt = most_recent_date - timedelta(days=offset)

        # if anything remains unmatched, try parsing it with dateutil's parser
        if s.strip() != '':
            try:
                if dt:
                    dt = default_tzinfo(parser.parse(s, default=dt), tzutc)
                else:
                    # check if it's only time, then use the start dt as
                    # default, else just use the current year
                    if re.match('(?P<hour>\d{1,2}):(?P<minute>\d{2,2})'
                                '(?::(?P<second>\d{2,2})'
                                '(?:.(?P<microsecond>\d{3,3}))?)?'
                                '(?P<timezone>[0-9Z:\+\-]+)?$', s):
                        default = self.end if lower_bound else self.start
                    else:
                        default = datetime(self.end.year, 1, 1, 0, 0, 0)
                    default = default.replace(second=0, microsecond=0)

                    dt = parser.parse(s, default=default)

            except ValueError:
                raise ValueError("Error in DateTimeBoundaries: "
                                 "can't parse datetime from %s" % s)

        if not dt:
            dt = lower_bound or self.end

        # if no timezone specified, use the one from the logfile
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=self.start.tzinfo)

        # time is applied separately (not through the parser) so that string
        # containing only time don't use today as default date
        # (parser behavior)
        # if 'time' in result:
        #     dct = dict((k, int(v))
        #                for k,v in six.iteritems(result['time'].groupdict(0)))
        #     dct['microsecond'] *= 1000
        #     dt = dt.replace(**dct)

        # apply offset
        if 'offset' in result:

            # separate in operator, value, unit
            dct = result['offset'].groupdict()

            mult = 1
            if dct['unit'] in ['s', 'sec', 'secs']:
                dct['unit'] = 'seconds'
            elif dct['unit'] in ['m', 'min', 'mins']:
                dct['unit'] = 'minutes'
            elif dct['unit'] in ['h', 'hour', 'hours']:
                dct['unit'] = 'hours'
            elif dct['unit'] in ['d', 'day', 'days']:
                dct['unit'] = 'days'
            elif dct['unit'] in ['w', 'week', 'weeks']:
                dct['unit'] = 'days'
                mult = 7
            elif dct['unit'] in ['mo', 'month', 'months']:
                dct['unit'] = 'days'
                mult = 30.43
            elif dct['unit'] in ['y', 'year', 'years']:
                dct['unit'] = 'days'
                mult = 365.24

            if dct['operator'] == '-':
                mult *= -1

            dt = dt + eval('timedelta(%s=%i)' % (dct['unit'],
                                                 mult * int(dct['value'])))

        # if parsed datetime is out of bounds and no year specified,
        # try to adjust year
        year_present = re.search('\d{4,4}', original_s)

        if not year_present and 'constant' not in result:
            if (dt < self.start and
                    dt.replace(year=dt.year + 1) >= self.start and
                    dt.replace(year=dt.year + 1) <= self.end):
                dt = dt.replace(year=dt.year + 1)
            elif (dt > self.end and
                    dt.replace(year=dt.year - 1) >= self.start and
                    dt.replace(year=dt.year - 1) <= self.end):
                dt = dt.replace(year=dt.year - 1)

        return dt
615746
def dmap2lin(df,idxn='index',coln='column',colvalue_name='value'):
    
#     df.columns.name=coln
    df.index.name=idxn
    return df.reset_index().melt(id_vars=[df.index.name],
                             var_name=coln,value_name=colvalue_name)
411335
function replaceAll(str = '', pattern, replacement) {
	if (arguments.length < 2 ){
		return str;
	}

	let rs = str;
	if (lodash.isPlainObject(pattern)){
		for (let key in pattern){
			rs = rs.replace(new RegExp('{' + key + '}', "gm"), pattern[key])
		}
	}else {
		rs = rs.replace(new RegExp(pattern, "gm"), replacement)
	}

	return rs;
}
476125
function ltrim(str, targetStr) {
    var retStr = "";
    var regStr;

    if (typeof str != "string") {
        return retStr;
    }

    if (typeof targetStr != "string" || !targetStr) {
        targetStr = "\\s";
    }

    regStr = "^" + targetStr + "*(.*?)";
    regStr = new RegExp(regStr);

    str = str.replace(regStr, "$1");
    return str;
}
1242663
private static void replace_glob(GlobData rdata, Context cx,
                                     Scriptable scope, RegExpImpl reImpl,
                                     int leftIndex, int leftlen)
    {
        int replen;
        String lambdaStr;
        if (rdata.lambda != null) {
            // invoke lambda function with args lastMatch, $1, $2, ... $n,
            // leftContext.length, whole string.
            SubString[] parens = reImpl.parens;
            int parenCount = (parens == null) ? 0 : parens.length;
            Object[] args = new Object[parenCount + 3];
            args[0] = reImpl.lastMatch.toString();
            for (int i=0; i < parenCount; i++) {
                SubString sub = parens[i];
                if (sub != null) {
                    args[i+1] = sub.toString();
                } else {
                    args[i+1] = Undefined.instance;
                }
            }
            args[parenCount+1] = Integer.valueOf(reImpl.leftContext.length);
            args[parenCount+2] = rdata.str;
            // This is a hack to prevent expose of reImpl data to
            // JS function which can run new regexps modifing
            // regexp that are used later by the engine.
            // TODO: redesign is necessary
            if (reImpl != ScriptRuntime.getRegExpProxy(cx)) Kit.codeBug();
            RegExpImpl re2 = new RegExpImpl();
            re2.multiline = reImpl.multiline;
            re2.input = reImpl.input;
            ScriptRuntime.setRegExpProxy(cx, re2);
            try {
                Scriptable parent = ScriptableObject.getTopLevelScope(scope);
                Object result = rdata.lambda.call(cx, parent, parent, args);
                lambdaStr = ScriptRuntime.toString(result);
            } finally {
                ScriptRuntime.setRegExpProxy(cx, reImpl);
            }
            replen = lambdaStr.length();
        } else {
            lambdaStr = null;
            replen = rdata.repstr.length();
            if (rdata.dollar >= 0) {
                int[] skip = new int[1];
                int dp = rdata.dollar;
                do {
                    SubString sub = interpretDollar(cx, reImpl, rdata.repstr,
                                                    dp, skip);
                    if (sub != null) {
                        replen += sub.length - skip[0];
                        dp += skip[0];
                    } else {
                        ++dp;
                    }
                    dp = rdata.repstr.indexOf('$', dp);
                } while (dp >= 0);
            }
        }

        int growth = leftlen + replen + reImpl.rightContext.length;
        StringBuilder charBuf = rdata.charBuf;
        if (charBuf == null) {
            charBuf = new StringBuilder(growth);
            rdata.charBuf = charBuf;
        } else {
            charBuf.ensureCapacity(rdata.charBuf.length() + growth);
        }

        charBuf.append(reImpl.leftContext.str, leftIndex, leftIndex + leftlen);
        if (rdata.lambda != null) {
            charBuf.append(lambdaStr);
        } else {
            do_replace(rdata, cx, reImpl);
        }
    }
756543
def replace_wildcards(string, wildcard, regex):
        
        replaced = False
        match = wildcard.search(string)

        if match:
            string = wildcard.sub(regex, string)
            logging.getLogger('agentml.trigger').debug('Parsing Pattern wildcards: {pattern}'.format(pattern=string))
            replaced = True

        return string, replaced
959491
private StringGrabber replaceCaseTo(int startPos, int endPos, ECase toCase) {

		StringBuilder sbRange = new StringBuilder();

		try {
			for (int i = startPos; i < endPos; i++) {
				sbRange.append(String.valueOf(sb.charAt(i)));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		final String caseConvertedRangeStr;

		if (ECase.LOWER == toCase) {
			caseConvertedRangeStr = sbRange.toString().toLowerCase();
		} else {
			caseConvertedRangeStr = sbRange.toString().toUpperCase();
		}
		try {
			sb.replace(startPos, endPos, caseConvertedRangeStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return StringGrabber.this;
	}
139687
def _filter_data_frame(df, data_col, filter_col, filter_str=None):
    """"""
    if filter_str is not None:
        relevant_cols = data_col + [filter_col]
        df.dropna(inplace=True, subset=relevant_cols)
        row_filter = df[filter_col].str.contains(filter_str, case=False)
        data_list = df[row_filter][data_col].to_dict()
    else:
        data_list = df[data_col].to_dict()
    return data_list
1090373
def substitution_set(string, indexes):
    
    strlen = len(string)
    return {mutate_string(string, x) for x in indexes if valid_substitution(strlen, x)}
1053123
def split(self, s):
        """"""

        normalized = "".join(map(lambda c: " " if c.isspace() else c, s))

        string = False
        quote = False
        v = []
        for col, char in enumerate(normalized.rstrip(), 1):
            if char == '\\':
                quote = True
            if char == '"' and not quote:
                if string:
                    v[-1] = (v[-1][0], v[-1][1] + '"')
                string = not string

            if char.isspace() and not string:
                v.append((col, ""))
            else:
                if len(v) == 0:
                    v.append((col, char))
                else:
                    col, part = v[-1]
                    v[-1] = (col, part + char)

            if char != '\\' and quote:
                quote = False

        return [t_p for t_p in v if t_p[1] != ""]
132286
function extractFromRow(row, context, asString)
{
  var map    = row._arrayProcessedColumns;
  var values = row.values;

  // get the value
  var columnIndex = this.getIndex();
  var ret = values[columnIndex];

  // if we want the value as a string, and the column is of type variant, and we
  // haven't already processed the value before, we don't need to process the
  // value, so only process if none of the aforementioned conditions are true
  if (!(asString && this.isVariant() && !map[columnIndex]))
  {
    // if the column value has not been processed yet, process it, put it back
    // in the values array, and remember that the value has been processed
    if (!map[columnIndex])
    {
      if (ret !== null)
      {
        ret = values[columnIndex] =
            context.convert(values[columnIndex], this, context);
      }
      map[columnIndex] = true;
    }

    // use the appropriate extraction function depending on whether
    // we want the value or a string representation of the value
    var extractFn = !asString ? context.toValue : context.toString;
    ret = extractFn(ret);
  }

  return ret;
}
67938
function replace( str, regexp, replacement )
	{
		var headBookmark = '',
			tailBookmark = '';

		str = str.replace( /(^<span[^>]+data-cke-bookmark.*?\/span>)|(<span[^>]+data-cke-bookmark.*?\/span>$)/gi,
			function( str, m1, m2 ){
					m1 && ( headBookmark = m1 );
					m2 && ( tailBookmark = m2 );
				return '';
			} );
		return headBookmark + str.replace( regexp, replacement ) + tailBookmark;
	}
983991
def flatten(self, df, column_name):
        """"""
        _exp_list = [[md5, x] for md5, value_list in zip(df['md5'], df[column_name]) for x in value_list]
        return pd.DataFrame(_exp_list, columns=['md5',column_name])
832840
private static Pattern replacePlaceHolders(String s) {
    s = Pattern.quote(s);
    return Pattern.compile(s.replaceAll("\\{\\d+\\}", "\\\\E.*\\\\Q"));
  }