question stringlengths 11 28.2k | answer stringlengths 26 27.7k | tag stringclasses 130
values | question_id int64 935 78.4M | score int64 10 5.49k |
|---|---|---|---|---|
I'm transforming a Spring Boot application from Spring Boot 1 (with the Prometheus Simpleclient) to Spring Boot 2 (which uses Micrometer).
I'm stumped at transforming the labels we have with Spring Boot 1 and Prometheus to concepts in Micrometer. For example (with Prometheus):
private static Counter requestCounter =
... | Further digging showed that only the keys of micrometer tags have to be predeclared - but the constructor really takes pairs of key/values; the values don't matter. And the keys have to be specified when using the metric.
This works:
private static final String COUNTER_BATCHMANAGER_SENT_REQUESTS = "batchmanager.sent.re... | Micrometer | 49,170,093 | 13 |
I tried to obtains these measurements from prometheus:
increase(http_server_requests_seconds_count{uri="myURI"}[10s])
increase(http_server_requests_seconds_count{uri="myURI"}[30s])
rate(http_server_requests_seconds_count{uri="myURI"}[10s])
rate(http_server_requests_seconds_count{uri="myURI"}[30s])
Then I run a python... | Prometheus calculates increase(m[d]) at timestamp t in the following way:
It fetches raw samples stored in the database for time series matching m on a time range (t-d .. t]. Note that samples at timestamp t-d aren't included in the time range, while samples at t are included. It is expected that every selected time s... | Micrometer | 70,835,778 | 12 |
In Prometheus I've got 14 seconds for http_server_requests_seconds_max.
http_server_requests_seconds_max{exception="None",method="GET",outcome="SUCCESS",status="200",uri="/v1/**",} 14.3
Does this mean the total time for the request from the server to the client or does it only measure the time in the Spring container... | From the copy of Spring documentation at Archive.org (or current Micrometer.io page), when @Timed attribute is used on a function or a Controller, it produces the metrics http_server_requests.
which by default contains dimensions for the HTTP status of the
response, HTTP method, exception type if the request fails, an... | Micrometer | 60,206,507 | 11 |
Recently I switched to Spring Boot 2 with Micrometer. As I got these shiny new metrics, I talked with our DevOps guys and we started exporting them to Telegraf.
To distinguish between different applications and application nodes, we decided to use tags. This works perfectly for custom metrics, but now I started thinkin... | If you are looking for common tags support, you can do it by registering a MeterFilter doing it.
See this commit or this branch for an example.
With the upcoming Spring Boot 2.1.0.M1, you can use the following properties:
management.metrics.tags.*= # Common tags that are applied to every meter.
See the reference for d... | Micrometer | 51,552,889 | 11 |
After upgrading from spring-boot-parent version 2.5.5 to 2.6.0, I started seeing these error messages spamming the logs:
[INFO] [stdout] 2022-01-11 13:40:01.157 WARN 76859 --- [ udp-epoll-2] i.m.s.reactor.netty.channel.FluxReceive : [6d1243de, L:/127.0.0.1:58160 - R:localhost/127.0.0.1:8125] An exception has been ... | assuming statsd is not used and configured on your side, since it's pointed to localhost, you may disable it by setting
management.metrics.export.statsd.enabled
to false
| Micrometer | 70,667,172 | 10 |
I use MicroMeter gauges in a Spring Boot 2 application to track statuses of objects. On status change, the statusArrived() method is called. This function should update the gauge related to that object.
Here is my current implementation:
public class PrometheusStatusLogger {
private int currentStatus;
public... | Since all your gauges are referencing the same currentStatus, when the new value comes in, all the gauge's source is changed. Instead use a map to track all the current status by id:
public class PrometheusStatusLogger {
private Map<String, Integer> currentStatuses = new HashMap<>();
public void statusArrive... | Micrometer | 60,171,522 | 10 |
I'm trying out Spring Boot Actuator and looking at the "/actuator/metrics/jvm.memory.max" endpoint.
I am also running my Springboot app with the following JVM option:
-Xmx104m
I created an endpoint ("/memory" which returns the Total, Free, Used & Max memory for the app. I used Runtime.getRuntime().getXXX() methods fo... | Spring Boot uses Micrometer for its metrics support. The jvm.memory.max metrics is produced by Mirometer's JvmMemoryMetrics class using MemoryPoolMXBean.getUsage().getMax().
The MemoyPoolMXBean exposes information about both heap and non-heap memory and Micrometer separates these using tags on the jvm.memory.max metric... | Micrometer | 54,591,870 | 10 |
We are using Nagios to monitor our network with great success. However, we have a syslog for critical application errors and while I set up check_log, it doesn't seem to work as well as monitering a device.
The issues are:
It only shows the last entry
There doesn't seem to be a way to acknowledge the critical error an... | For monitoring logs with Nagios, typically the log checker will return a warning only for newly discovered error messages each time it is invoked (so it must retain some state in order to know to ignore them on subsequent runs). Therefore I usually set:
max_check_attempts 1
is_volatile ... | Nagios | 2,373,212 | 25 |
Maybe a strange and green question, however
Is there anything that Nagios or Ganglia can do that the other can't?
In terms of monitoring, alerts in general.
I'm looking for a general solution for my school's computer club, in my mind its like comparing norton vs advast. both are antivirus however are there any specifi... | Ganglia is aimed at monitoring compute grids, i.e. a bunch of servers working on the same task to achieve a common goal - such as a cluster of web servers.
Nagios is aimed at monitoring anything and everything - servers, services on servers, switches, network bandwidth via SNMP etc etc. Nagios will send alerts based on... | Nagios | 14,494,948 | 25 |
My situation: I'm working on a web monitoring dashboard that assembles informations from different applications and sources and generate graphs, info graphics and reports.
The applications I'm trying to integrate are CACTI, Nagios, and other local private monitoring tools. I had no problem to integrate these applicatio... | Nagios 4.x starting with version 4.4 now includes CGIs for JSON output. Installing the newest version of Nagios might be the easiest way to go.
See the announcement here.
Review the slides from Nagios World Conference 2013 here.
| Nagios | 7,768,215 | 16 |
I'm trying to monitor actual URLs, and not only hosts, with Nagios, as I operate a shared server with several websites, and I don't think its enough just to monitor the basic HTTP service (I'm including at the very bottom of this question a small explanation of what I'm envisioning).
(Side note: please note that I have... | I was making things WAY too complicated.
The built-in / installed by default plugin, check_http, can accomplish what I wanted and more. Here's how I have accomplished this:
My Service Definition:
define service{
host_name myers
service_description URL: my-url.... | Nagios | 9,246,557 | 13 |
I would like to monitor elasticsearch using nagios.
Basiclly, I want to know if elasticsearch is up.
I think I can use the elasticsearch Cluster Health API (see here)
and use the 'status' that I get back (green, yellow or red), but I still don't know how to use nagios for that matter ( nagios is on one server and elast... | After a while - I've managed to monitor elasticsearch using the nrpe.
I wanted to use the elasticsearch Cluster Health API - but I couldn't use it from another machine - due to security issues...
So, in the monitoring server I created a new service - which the check_command is check_command check_nrpe!check_elast... | Nagios | 10,276,989 | 10 |
I have NRPE daemon process running under xinetd on amazon ec2 instance and nagios server on my local machine.
The check_nrpe -H [amazon public IP] gives this error:
CHECK_NRPE: Error - Could not complete SSL handshake.
Both Nrpe are same versions. Both are compiled with this option:
./configure --with-ssl=/usr/bin/op... | If you are running nrpe as a service, make sure you have this line in your nrpe.cfg on the client side:
# example 192. IP, yours will probably differ
allowed_hosts=127.0.0.1,192.168.1.100
You say that is done, however, if you are running nrpe under xinetd, make sure to edit the only_from directive in the file /etc/xi... | Nagios | 20,520,334 | 10 |
I am trying read a file and split a cell in each line by a comma and then display only the first and the second cells which contain information regarding the latitude and the longitude.
This is the file:
time,latitude,longitude,type
2015-03-20T10:20:35.890Z,38.8221664,-122.7649994,earthquake
2015-03-20T10:18:13.070Z,33... | I think you've actually got a wider confusion here.
The initial error is that you're trying to call split on the whole list of lines, and you can't split a list of strings, only a string. So, you need to split each line, not the whole thing.
And then you're doing for points in Type, and expecting each such points to gi... | Split | 30,042,334 | 28 |
I have a file which contains data as follows:
recv(1178884, NULL, 4294967267, 0) = 0
......
......
My source code is:
try (BufferedReader br = new BufferedReader(new FileReader("D:\\smsTrace.txt"))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
String sysCallName = sCurr... | You have to escape the opening bracket:
sysCallName.split("\\(");
Because split() expects a regular expression, and brackets are used to mark capturing groups in a regex. So they need to be in pairs. If you just want a bracket it needs to be escaped.
| Split | 13,948,751 | 28 |
I have a concatenated string like this:
my_str = 'str1;str2;str3;'
and I would like to apply split function to it and then convert the resulted list to a tuple, and get rid of any empty string resulted from the split (notice the last ';' in the end)
So far, I am doing this:
tuple(filter(None, my_str.split(';')))
Is t... | How about this?
tuple(my_str.split(';')[:-1])
('str1', 'str2', 'str3')
You split the string at the ; character, and pass all off the substrings (except the last one, the empty string) to tuple to create the result tuple.
| Split | 11,001,247 | 28 |
I'm trying to split a string at the first space and only keep the 2nd half. So if the input was "1. top of steel", the output would be "top of steel". I'm working with a few different examples from here and I cant get it to work. Thoughts? Thanks.
| var myString = "1. top of steel";
var newString = myString.Remove(0, myString.IndexOf(' ') + 1);
| Split | 10,389,805 | 28 |
I have a string:
String str = "a + b - c * d / e < f > g >= h <= i == j";
I want to split the string on all of the operators, but include the operators in the array, so the resulting array looks like:
[a , +, b , -, c , *, d , /, e , <, f , >, g , >=, h , <=, i , ==, j]
I've got this currently:
public stati... | String[] ops = str.split("\\s*[a-zA-Z]+\\s*");
String[] notops = str.split("\\s*[^a-zA-Z]+\\s*");
String[] res = new String[ops.length+notops.length-1];
for(int i=0; i<res.length; i++) res[i] = i%2==0 ? notops[i/2] : ops[i/2+1];
This should do it. Everything nicely stored in res.
| Split | 9,856,916 | 28 |
Emacs usualy automaticaly splits the window horizontaly.
How can I change this default behaviour, so that the window is splited verticaly by default?
| Use (setq split-width-threshold nil) for vertical split.
Use (setq split-width-threshold 1 ) for horizontal split.
Use http://www.emacswiki.org/emacs/ToggleWindowSplit to toggle between them.
Use http://www.emacswiki.org/emacs/TransposeWindows to transponse them.
| Split | 7,997,590 | 28 |
In Ruby, I did:
"string1::string2".split("::")
In Scala, I can't find how to split using a string, not a single character.
| The REPL is even easier than Stack Overflow. I just pasted your example as is.
Welcome to Scala version 2.8.1.final (Java HotSpot Server VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.
scala> "string1::string2".split("::")
res0: Array[java.lang.String] = Array(string1,... | Split | 5,522,572 | 28 |
I have a source file where 2 features have been added. In order to allow cherry-picking, I'd like to commit that in 2 phases: one for each feature. Until now, in similar situations, using git add -p served me well, to commit one feature while leaving the local files in their final stage.
However, I now have the problem... | As Alan says, edit the patch by pressing e (instead of s) during git add -p. This will launch your editor with that hunk of the patch so that you can manually edit it. There are comments within the text that explain how to properly discard modifications and it's actually pretty easy.
When you are done, note that you ca... | Split | 2,333,828 | 28 |
Basically, I want to go from 1) to 2)
I usually do this by splitting horizontally first and then vertically, but as I want this to do three-way diffs, it is much handier to start vim by running:
$ vimdiff file1 file2 file3
And then doing something to open the split window below.
1)
+----+----+----+
¦ ¦ ¦... | use :botright split or :bo sp, it does what you want
| Split | 1,187,511 | 28 |
I've been switching some windows in VIM from vertical to horizontal splits and back using:
CTRL-W + K
CTRL-W + L
CTRL-W + J
CTRL-W + H
After doing this a few times the cursor disappeared. I can still type, and the status bar at the bottom still shows me my location, but there's no blinking cursor. Any ideas regardin... | I have the same problem and I have used couple of work-arounds that work for me:
Maximize gvim window and then click on the maximize button again to bring it to original size. This brings back the cursor.
Run some shell command e.g., !echo > /dev/null - this seems to bring back the cursor as well.
I am experimenting ... | Split | 1,025,762 | 28 |
I have a small problem with something I need to do in school...
My task is the get a raw input string from a user (text = raw_input())
and I need to print the first and final words of that string.
Can someone help me with that? I have been looking for an answer all day...
| You have to firstly convert the string to list of words using str.split and then you may access it like:
>>> my_str = "Hello SO user, How are you"
>>> word_list = my_str.split() # list of words
# first word v v last word
>>> word_list[0], word_list[-1]
('Hello', 'you')
From Python 3.x, you may simply d... | Split | 41,228,115 | 27 |
I want to remove digits from the end of a string, but I have no idea.
Can the split() method work? How can I make that work?
The initial string looks like asdfg123,and I only want asdfg instead.
Thanks for your help!
| No, split would not work, because split only can work with a fixed string to split on.
You could use the str.rstrip() method:
import string
cleaned = yourstring.rstrip(string.digits)
This uses the string.digits constant as a convenient definition of what needs to be removed.
or you could use a regular expression to r... | Split | 40,691,451 | 27 |
I'm looking for something along the line of
str_split_whole_word($longString, $x)
Where $longString is a collection of sentences, and $x is the character length for each line. It can be fairly long, and I want to basically split it into multiple lines in the form of an array.
For example:
$longString = 'I like apple. ... | The easiest solution is to use wordwrap(), and explode() on the new line, like so:
$array = explode( "\n", wordwrap( $str, $x));
Where $x is a number of characters to wrap the string on.
| Split | 11,254,787 | 27 |
In Java, I am trying to split on the ^ character, but it is failing to recognize it. Escaping \^ throws code error.
Is this a special character or do I need to do something else to get it to recognize it?
String splitChr = "^";
String[] fmgStrng = aryToSplit.split(splitChr);
| The ^ is a special character in Java regex - it means "match the beginning" of an input.
You will need to escape it with "\\^". The double slash is needed to escape the \, otherwise Java's compiler will think you're attempting to use a special \^ sequence in a string, similar to \n for newlines.
\^ is not a special esc... | Split | 10,695,104 | 27 |
I'm working on a project that involves parsing a large csv formatted file in Perl and am looking to make things more efficient.
My approach has been to split() the file by lines first, and then split() each line again by commas to get the fields. But this suboptimal since at least two passes on the data are required. (... | The right way to do it -- by an order of magnitude -- is to use Text::CSV_XS. It will be much faster and much more robust than anything you're likely to do on your own. If you're determined to use only core functionality, you have a couple of options depending on speed vs robustness.
About the fastest you'll get for pu... | Split | 3,065,095 | 27 |
I have an NSData object of approximately 1000kB in size. Now I want to transfer this via Bluetooth. It would be better if I have, let's say, 10 objects of 100kB. It comes to mind that I should use the -subdataWithRange: method of NSData.
I haven't really worked with NSRange. Well, I know how it works, but I can't figur... | The following piece of code does the fragmentation without copying the data:
NSData* myBlob;
NSUInteger length = [myBlob length];
NSUInteger chunkSize = 100 * 1024;
NSUInteger offset = 0;
do {
NSUInteger thisChunkSize = length - offset > chunkSize ? chunkSize : length - offset;
NSData* chunk = [NSData dataWithB... | Split | 2,899,020 | 27 |
str.rsplit([sep[, maxsplit]])
Return a
list of the words in the string, using
sep as the delimiter string. If
maxsplit is given, at most maxsplit
splits are done, the rightmost ones.
If sep is not specified or None, any
whitespace string is a separator.
Except for splitting from the right,
rsplit() behaves like split(... | String.prototype.rsplit = function(sep, maxsplit) {
var split = this.split(sep);
return maxsplit ? [ split.slice(0, -maxsplit).join(sep) ].concat(split.slice(-maxsplit)) : split;
}
This one functions more closely to the Python version
"blah,derp,blah,beep".rsplit(",",1) // [ 'blah,derp,blah', 'beep' ]
| Split | 5,202,085 | 26 |
I have a word list like below. I want to split the list by .. Is there any better or useful code in Python 3?
a = ['this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.']
result = []
tmp = []
for elm in a:
if elm is not '.':
tmp.append(elm)
else:
result.append(tmp)
tmp = [... | Using itertools.groupby
from itertools import groupby
a = ['this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.']
result = [
list(g)
for k,g in groupby(a,lambda x:x=='.')
if not k
]
print (result)
#[['this', 'is', 'a', 'cat'], ['hello'], ['she', 'is', 'nice']]
| Split | 47,604,449 | 26 |
In my Java application I need to find indices and split strings using the same "target" for both occasions. The target is simply a dot.
Finding indices (by indexOf and lastIndexOf) does not use regex, so
String target = ".";
String someString = "123.456";
int index = someString.indexOf(target); // index == 3
gives me ... | You need to escape your "target" in order to use it as a regex.
Try
String[] someStringSplit = someString.split(Pattern.quote(target));
and let me know if that helps.
| Split | 39,038,102 | 26 |
I have values being returned with 255 comma separated values. Is there an easy way to split those into columns without having 255 substr?
ROW | VAL
-----------
1 | 1.25, 3.87, 2, ...
2 | 5, 4, 3.3, ....
to
ROW | VAL | VAL | VAL ...
---------------------
1 |1.25 |3.87 | 2 ...
2 | 5 | 4 | 3.3 ...
... | Beware! The regexp_substr expression of the format '[^,]+' will not return the expected value if there is a null element in the list and you want that item or one after it. Consider this example where the 4th element is NULL and I want the 5th element and thus expect the '5' to be returned:
SQL> select regexp_substr(... | Split | 31,464,275 | 26 |
Here is the error:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 3
], [
^
at java.util.regex.Pattern.error(Pattern.java:1924)
at java.util.regex.Pattern.clazz(Pattern.java:2493)
at java.util.regex.Pattern.sequence(Pattern.java:2030)
at java.uti... |
TL;DR
You want:
.split("\\], \\[")`
Escape each square bracket twice — once for each context in which you need to strip them from their special meaning: within a Regular Expression first, and within a Java String secondly.
Consider using Pattern#quote when you need your entire pattern to be interpreted literally.
Ex... | Split | 21,816,788 | 26 |
I have the following string:
"hello.world.foo.bar"
and I want to split (with the "." as delimiter, and only want to get two elemets starting by the end) this in the following:
["hello.world.foo", "bar"]
How can I accomplish this? exist the limit by the end?
| Use str.rsplit specifying maxsplit (the second argument) as 1:
>>> "hello.world.foo.bar".rsplit('.', 1) # <-- 1: maxsplit
['hello.world.foo', 'bar']
| Split | 20,312,851 | 26 |
I have an array of 18 values:
$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r');
I want to split this array into 12 different arrays so it should look like this:
array(
0 => array('a', 'b'),
1 => array('c', 'd'),
2 => array('e', 'f'),
3 => array('g... | This simple function would work for you:
Usage
$array = range("a", "r"); // same as your array
print_r(alternate_chunck($array,12));
Output
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] ... | Split | 15,579,702 | 26 |
Is there a method in scala to get the (single) head element of a List or Seq and the (collection) tail of the list? I know there's
def splitAt(n: Int): (List[A], List[A])
and I can easily grab the single item from the first list of the tuple. But is there any built in method that is basically this?
def splitAtHead: (O... | You can use pattern matching:
val hd::tail = List(1,2,3,4,5)
//hd: Int = 1
//tail: List[Int] = List(2, 3, 4, 5)
Or just .head/.tail methods:
val hd = foo.head
// hd: Int = 1
val hdOpt = foo.headOption
// hd: Option[Int] = Some(1)
val tl = foo.tail
// tl: List[Int] = List(2, 3, 4)
| Split | 14,804,159 | 26 |
I am trying to find out if there is a way to split the value of each iteration of a list comprehension only once but use it twice in the output.
As an example of the problem I am trying to solve is, I have the string:
a = "1;2;4\n3;4;5"
And I would like to perform this:
>>> [(x.split(";")[1],x.split(";")[2]) for x in... | You could use a list comprehension wrapped around a generator expression:
[(x[1],x[2]) for x in (x.split(";") for x in a.split("\n")) if x[1] != 5]
| Split | 10,308,939 | 26 |
The default split method in Python treats consecutive spaces as a single delimiter. But if you specify a delimiter string, consecutive delimiters are not collapsed:
>>> 'aaa'.split('a')
['', '', '', '']
What is the most straightforward way to collapse consecutive delimiters? I know I could just remove empty strings ... | This is about as concise as you can get:
string = 'aaa'
result = [s for s in string.split('a') if s]
Or you could switch to regular expressions:
string = 'aaa'
result = re.split('a+', string)
| Split | 6,478,845 | 26 |
Short version -- How do I do Python rsplit() in ruby?
Longer version -- If I want to split a string into two parts (name, suffix) at the first '.' character, this does the job nicely:
name, suffix = name.split('.', 2)
But if I want to split at the last (rightmost) '.' character, I haven't been able to come up with any... | String#rpartition does just that:
name, match, suffix = name.rpartition('.')
It was introduced in Ruby 1.8.7, so if running an earlier version you can use require 'backports/1.8.7/string/rpartition' for that to work.
| Split | 1,844,118 | 26 |
If, at a command prompt, I run
vimdiff file1 file2
I get a vim instance that has two files open side-by-side, something like this:
╔═══════╤═══════╗
║ │ ║
║ │ ║
║ file1 │ file2 ║
║ │ ║
║ │ ║
╚═══════╧═══════╝
This is very nice, but sometimes I want to open a third file ... | Use
:botright split
and open a new file inside.
| Split | 859,383 | 26 |
I have the following process which uses group_split of dplyr:
library(tidyverse)
set.seed(1)
iris %>% sample_n(size = 5) %>%
group_by(Species) %>%
group_split()
The result is:
[[1]]
# A tibble: 2 x 5
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<dbl> <dbl> <dbl> <d... | Lots of good answers. You can also just do:
iris %>% sample_n(size = 5) %>%
split(f = as.factor(.$Species))
Which will give you:
$setosa
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
4 5.5 3.5 1.3 0.2 setosa
5 5.3 3.7 1.5 0.2 setosa... | Split | 57,107,721 | 25 |
I have the following Java code:
String str = "12+20*/2-4";
List<String> arr = new ArrayList<>();
arr = str.split("\\p{Punct}");
//expected: arr = {12,20,2,4}
I want the equivalent Kotlin code, but .split("\\p{Punct}") doesn't work. I don't understand the documentation here: https://kotlinlang.org/api/latest/jvm/stdl... | you should using String#split(Regex) instead, for example:
val str = "12+20*/2-4";
val arr = str.split("\\p{Punct}".toRegex());
// ^--- but the result is ["12","20","","2","4"]
val arr2 = arr.filter{ !it.isBlank() };
// ^--- you can filter it as further, and result is: ["12","20","2","4"]
OR you can split more Punc... | Split | 45,064,788 | 25 |
I'm using ruby on rails and I want to display only first word of string.
My broken code: <%= @user.name %> displaying Barack Obama.
I would want to have it display Barack and in other place Obama.
How can I split it and display it?
| > "this is ruby".split.first
#=> "this"
| Split | 30,674,244 | 25 |
An incredibly basic question in R yet the solution isn't clear.
How to split a vector of character into its individual characters, i.e. the opposite of paste(..., sep='') or stringr::str_c() ?
Anything less clunky than this:
sapply(1:26, function(i) { substr("ABCDEFGHIJKLMNOPQRSTUVWXYZ",i,i) } )
"A" "B" "C" "D" "E" "F"... | Yes, strsplit will do it. strsplit returns a list, so you can either use unlist to coerce the string to a single character vector, or use the list index [[1]] to access first element.
x <- paste(LETTERS, collapse = "")
unlist(strsplit(x, split = ""))
# [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" ... | Split | 23,028,885 | 25 |
How can I split a string such as "102:330:3133:76531:451:000:12:44412 by the ":" character, and put all of the numbers into an int array (number sequence will always be 8 elements long)? Preferably without using an external library such as boost.
Also, I'm wondering how I can remove unneeded characters from the string ... | stringstream can do all these.
Split a string and store into int array:
string str = "102:330:3133:76531:451:000:12:44412";
std::replace(str.begin(), str.end(), ':', ' '); // replace ':' by ' '
vector<int> array;
stringstream ss(str);
int temp;
while (ss >> temp)
array.push_back(temp); // done! now array={102,33... | Split | 20,755,140 | 25 |
I am using the following command in SoX to split many large audio files at each place where there is silence longer than 0.3 seconds:
sox -V3 input.wav output.wav silence 1 0.50 0.1% 1 0.3 0.1% : newfile : restart
This however ends up occasionally creating files that are entirely silent and trimming the audio before e... | if you change 0.5 to 3.0, it works fine:
sox -V3 input.wav output.wav silence 1 3.0 0.1% 1 0.3 0.1% : newfile : restart
| Split | 20,014,064 | 25 |
Can anyone help me a bit with regexs? I currently have this: re.split(" +", line.rstrip()), which separates by spaces.
How could I expand this to cover punctuation, too?
| The official Python documentation has a good example for this one. It will split on all non-alphanumeric characters (whitespace and punctuation). Literally \W is the character class for all Non-Word characters. Note: the underscore "_" is considered a "word" character and will not be part of the split here.
re.split('\... | Split | 19,894,478 | 25 |
I was designing a regex to split all the actual words from a given text:
Input Example:
"John's mom went there, but he wasn't there. So she said: 'Where are you'"
Expected Output:
["John's", "mom", "went", "there", "but", "he", "wasn't", "there", "So", "she", "said", "Where", "are", "you"]
I thought of a regex li... | Instead of regex, you can use string-functions:
to_be_removed = ".,:!" # all characters to be removed
s = "John's mom went there, but he wasn't there. So she said: 'Where are you!!'"
for c in to_be_removed:
s = s.replace(c, '')
s.split()
BUT, in your example you do not want to remove apostrophe in John's but you ... | Split | 12,705,293 | 25 |
I've been developing an Android app for the past 4 Months now and came across the following regarding the split function:
String [] arr;
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
arr = result.toString().trim().split("|");
The result variable is what I get after accessing my WebService, now this wor... | arr = result.toString().trim().split("\\|");
the param of String.split accept a regular expression.
| Split | 6,965,642 | 25 |
I have a string like:
$Order_num = "0982asdlkj";
How can I split that into the 2 variables, with the number as one element and then another variable with the letter element?
The number element can be any length from 1 to 4 say and the letter element fills the rest to make every order_num 10 characters long in total.
I... | You can use preg_split using lookahead and lookbehind:
print_r(preg_split('#(?<=\d)(?=[a-z])#i', "0982asdlkj"));
prints
Array
(
[0] => 0982
[1] => asdlkj
)
This only works if the letter part really only contains letters and no digits.
Update:
Just to clarify what is going on here:
The regular expressions look... | Split | 4,537,994 | 25 |
I've been whacking away at this for a while to no avail... Any help would be greatly
appreciated.
I have:
[{'event': 0, 'voltage': 1, 'time': 0},
{'event': 0, 'voltage': 2, 'time': 1},
{'event': 1, 'voltage': 1, 'time': 2},
{'event': 1, 'voltage': 2, 'time': 3},
{'event': 2, 'voltage': 1, 'time': 4},
{'event': 2, 'vol... | use defaultdict
import collections
result = collections.defaultdict(list)
for d in dict_list:
result[d['event']].append(d)
result_list = result.values() # Python 2.x
result_list = list(result.values()) # Python 3
This way, you don't have to make any assumptions about how many different events there are ... | Split | 4,091,680 | 25 |
How do you split a string based on some separator?
Given a string Topic1,Topic2,Topic3, I want to split the string based on , to generate:
Topic1 Topic2 Topic3
| In XSLT 1.0 you have to built a recursive template. This stylesheet:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template ma... | Split | 3,336,424 | 25 |
I looking for a function like regexp_split_to_table, but our db is version 8.2.9, so it doesn't have it. I'm really only splitting on a space, so a string like
how now brown cow
would return
+------+
|Column|
+------+
|how |
|now |
|brown |
|cow |
+------+
is there a simple function that can handle this, or... | You can split an array to a resultset by using the unnest function, and you can turn a string literal into an array by using the string_to_array function. Combine both and you get this:
alvherre=# select unnest(string_to_array('the quick lazy fox', ' '));
unnest
--------
the
quick
lazy
fox
(4 filas)
Since 8.2 d... | Split | 1,986,491 | 25 |
How can you split a word to its constituent letters?
Example of code which is not working
class Test {
public static void main( String[] args) {
String[] result = "Stack Me 123 Heppa1 oeu".split("\\a");
... | You need to use split("");.
That will split it by every character.
However I think it would be better to iterate over a String's characters like so:
for (int i = 0;i < str.length(); i++){
System.out.println(str.charAt(i));
}
It is unnecessary to create another copy of your String in a different form.
| Split | 1,521,921 | 25 |
I need to be able to take a string like:
'''foo, bar, "one, two", three four'''
into:
['foo', 'bar', 'one, two', 'three four']
I have an feeling (with hints from #python) that the solution is going to involve the shlex module.
| It depends how complicated you want to get... do you want to allow more than one type of quoting. How about escaped quotes?
Your syntax looks very much like the common CSV file format, which is supported by the Python standard library:
import csv
reader = csv.reader(['''foo, bar, "one, two", three four'''], skipinitia... | Split | 118,096 | 25 |
When std::views::split() gets an unnamed string literal as a pattern, it will not split the string but works just fine with an unnamed character literal.
#include <iomanip>
#include <iostream>
#include <ranges>
#include <string>
#include <string_view>
int main(void)
{
using namespace std::literals;
// returns... | String literals always end with a null-terminator, so ":.:" is actually a range with the last element of \0 and a size of 4.
Since the original string does not contain such a pattern, it is not split.
When dealing with C++20 ranges, I strongly recommend using string_view instead of raw string literals, which works well... | Split | 74,260,112 | 24 |
In my dataframe, I have a categorical variable that I'd like to convert into dummy variables. This column however has multiple values separated by commas:
0 'a'
1 'a,b,c'
2 'a,b,d'
3 'd'
4 'c,d'
Ultimately, I'd want to have binary columns for each possible discrete value; in other words, final column co... | Use str.get_dummies
df['col'].str.get_dummies(sep=',')
a b c d
0 1 0 0 0
1 1 1 1 0
2 1 1 0 1
3 0 0 0 1
4 0 0 1 1
Edit: Updating the answer to address some questions.
Qn 1: Why is it that the series method get_dummies does not accept the argument prefix=... while panda... | Split | 46,867,201 | 24 |
I have a pandas dataframe containing (besides other columns) full names:
fullname
martin master
andreas test
I want to create a new column which splits the fullname column along the blank space and assigns the last element to a new column. The result should look like:
fullname lastname
martin master ... | You need another str to access the last splits for every row, what you did was essentially try to index the series using a non-existent label:
In [31]:
df['lastname'] = df['fullname'].str.split().str[-1]
df
Out[31]:
fullname lastname
0 martin master master
1 andreas test test
| Split | 38,498,718 | 24 |
I'd like to split an input string on the first colon that still has characters after it on the same line.
For this, I am using the regular expression /:(.+)/
So given the string
aaa:
bbb:ccc
I'd expect an output of
["aaa:\nbbb", "ccc"]
And given the string
aaa:bbb:ccc
I'd expect an output of
["aaa", "bbb:ccc"]
Yet ... | If we change the regex to /:.+/ and perform a split on it you get:
["aaa", ""]
This makes sense as the regex is matching the :bbb:ccc.
And gives you the same output, if you were to manually split that string.
>>> 'aaa:bbb:ccc'.split(':bbb:ccc')
['aaa', '']
Adding the capture group in just saves the bbb:ccc, but shoul... | Split | 38,261,359 | 24 |
I've been using the Split() method to split strings. But this work if you set some character for condition in string.Split(). Is there any way to split a string when is see Uppercase?
Is it possible to get few words from some not separated string like:
DeleteSensorFromTemplate
And the result string is to be like:
Dele... | Use Regex.split
string[] split = Regex.Split(str, @"(?<!^)(?=[A-Z])");
| Split | 36,147,162 | 24 |
I have this mystring with the delimiter _. The condition here is if there are two or more delimiters, I want to split at the second delimiter and if there is only one delimiter, I want to split at ".Recal" and get the result as shown below.
mystring<-c("MODY_60.2.ReCal.sort.bam","MODY_116.21_C4U.ReCal.sort.bam","MODY_1... | You can do this using gsubfn
library(gsubfn)
f <- function(x,y,z) if (z=="_") y else strsplit(x, ".ReCal", fixed=T)[[1]][[1]]
gsubfn("([^_]+_[^_]+)(.).*", f, mystring, backref=2)
# [1] "MODY_60.2" "MODY_116.21" "MODY_116.3" "MODY_116.4"
This allows for cases when you have more than two "_", and you want to split o... | Split | 31,931,954 | 24 |
I HATE velocity and rarely ever use it but sometimes I am called upon at my job to do so. I can never really figure out just how to use it.
I have this
#foreach( $product in $browseSiteProducts )
alert("$product.productId");
#foreach( $stringList in $product.productId.split("|") )
alert("inner loop");
... | Velocity has extremely few objects and methods of its own. Instead, it allows you to work with real Java objects and call real Java methods on those objects. Which Velocity documentation says that the delimiter is a string?
Moreover, since Velocity is Java-based, a string is just a data type that can hold many types of... | Split | 21,288,687 | 24 |
I have a data frame with a numerical ID variable which identify the Primary, Secondary and Ultimate Sampling Units from a multistage sampling scheme. I want to split the original ID variable into three new variables, identifying the different sampling units separately:
Example:
>df[1:2,]
ID Var var1 var2 ... | You could use for example use substring:
df <- data.frame(ID = c(501901, 501902))
splitted <- t(sapply(df$ID, function(x) substring(x, first=c(1,2,4), last=c(1,3,6))))
cbind(df, splitted)
# ID 1 2 3
#1 501901 5 01 901
#2 501902 5 01 902
| Split | 15,498,235 | 24 |
Is there a regex that would work with String.split() to break a String into contiguous characters - ie split where the next character is different to the previous character?
Here's the test case:
String regex = "your answer here";
String[] parts = "aaabbcddeee".split(regex);
System.out.println(Arrays.toString(parts));
... | It is totally possible to write the regex for splitting in one step:
"(?<=(.))(?!\\1)"
Since you want to split between every group of same characters, we just need to look for the boundary between 2 groups. I achieve this by using a positive look-behind just to grab the previous character, and use a negative look-ahea... | Split | 13,596,454 | 24 |
Ok i have a string where i want to remove the last word split by \
for example:
string name ="kak\kdk\dd\ddew\cxz\"
now i want to remove the last word so that i get a new value for name as
name= "kak\kdk\dd\ddew\"
is there an easy way to do this
thanks
| How do you get this string in the first place? I assume you know that '' is the escape character in C#. However, you should get far by using
name = name.TrimEnd('\\').Remove(name.LastIndexOf('\\') + 1);
| Split | 2,155,668 | 24 |
I have a script with these two functions:
# Getting content of each page
def GetContent(url):
response = requests.get(url)
return response.content
# Extracting the sites
def CiteParser(content):
soup = BeautifulSoup(content)
print "---> site #: ",len(soup('cite'))
result = []
for cite in soup.f... | It can happen, that the string has nothing inside, than it is "None" type, so what I can suppose is to check first if your string is not "None"
# Extracting the sites
def CiteParser(content):
soup = BeautifulSoup(content)
#print soup
print "---> site #: ",len(soup('cite'))
result = []
for cite in so... | Split | 25,882,670 | 23 |
I have a string that I want to split up in 2 pieces. The first piece is before the comma (,) and the second piece is all stuff after the comma (including the commas).
I already managed to retrieve the first piece before the comma in the variable $Header, but I don't know how to retrieve the pieces after the first comm... | PowerShell's -split operator supports specifying the maximum number of sub-strings to return, i.e. how many sub-strings to return. After the pattern to split on, give the number of strings you want back:
$header,$content = "Header text,Text 1,Text 2,Text 3,Text 4," -split ',',2
| Split | 25,383,263 | 23 |
I want to split the string "aaaabbbccccaaddddcfggghhhh" into "aaaa", "bbb", "cccc". "aa", "dddd", "c", "f" and so on.
I tried this:
String[] arr = "aaaabbbccccaaddddcfggghhhh".split("(.)(?!\\1)");
But this eats away one character, so with the above regular expression I get "aaa" while I want it to be "aaaa" as the fir... | Try this:
String str = "aaaabbbccccaaddddcfggghhhh";
String[] out = str.split("(?<=(.))(?!\\1)");
System.out.println(Arrays.toString(out));
=> [aaaa, bbb, cccc, aa, dddd, c, f, ggg, hhhh]
Explanation: we want to split the string at groups of same chars, so we need to find out the "boundary" between each group. I'm ... | Split | 23,523,597 | 23 |
I am wondering about the simple task of splitting a vector into two at a certain index:
splitAt <- function(x, pos){
list(x[1:pos-1], x[pos:length(x)])
}
a <- c(1, 2, 2, 3)
> splitAt(a, 4)
[[1]]
[1] 1 2 2
[[2]]
[1] 3
My question: There must be some existing function for this, but I can't find it? Is maybe split a... | An improvement would be:
splitAt <- function(x, pos) unname(split(x, cumsum(seq_along(x) %in% pos)))
which can now take a vector of positions:
splitAt(a, c(2, 4))
# [[1]]
# [1] 1
#
# [[2]]
# [1] 2 2
#
# [[3]]
# [1] 3
And it does behave properly (subjective) if pos <= 0 or pos >= length(x) in the sense that it retu... | Split | 16,357,962 | 23 |
I know that array_chunk() allows to split an array into several chunks, but the number of chunks changes according to the number of elements. What I need is to always split the array into a specific number of arrays like 4 arrays for example.
The following code splits the array into 3 chunks, two chunks with 2 elements... | You can try
$input_array = array(
'a',
'b',
'c',
'd',
'e'
);
print_r(partition($input_array, 4));
Output
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
)
[2] => Array
(... | Split | 15,723,059 | 23 |
I am using boost::split to parse a data file. The data file contains lines such as the following.
data.txt
1:1~15 ASTKGPSVFPLAPSS SVFPLAPSS -12.6 98.3
The white space between the items are tabs. The code I have to split the above line is as follows.
std::string buf;
/*Assign the line from the file to buf*/
st... | Even though "adjacent separators are merged together", it seems like the trailing delimeters make the problem, since even when they are treated as one, it still is one delimeter.
So your problem cannot be solved with split() alone. But luckily Boost String Algo has trim() and trim_if(), which strip whitespace or delime... | Split | 15,690,389 | 23 |
I have these url strings
file:///home/we/Pictures/neededWord/3193_n.jpg
file:///home/smes/Pictures/neededWord/jds_22.png
file:///home/seede/kkske/Pictures/neededWord/3193_n.jpg
I want to extract the "neededWord" from each of them. As it appears from them, the name of the image is always after the "neededWord" and the c... | Well you would just take the second to last element:
QStringList pieces = url.split( "/" );
QString neededWord = pieces.value( pieces.length() - 2 );
Alternatively, you could use a regular expression.
| Split | 11,751,697 | 23 |
I need to split comma delimited string into a second columns
I have the following table :
CL1 POS POS2 LENGHT ALLELE
1 3015108,3015109 5 A
2 3015110,3015200 10 B
3 3015200,3015300 15 C
4 3015450,3015500 ... | MySQL doesn't have a built-in CHARINDEX() function. LOCATE() would be the MySQL equivalent.
Using SUBSTRING_INDEX() might be a more succinct way of doing this. Something like this (disclaimer: untested):
SUBSTRING_INDEX(POS, ',', 1) for POS
SUBSTRING_INDEX(POS, ',', -1) for POS2
As an aside, I may be misunderstanding ... | Split | 9,953,114 | 23 |
I have multiple strings in different cells like
CO20: 20 YR CONVENTIONAL
FH30: 30 YR FHLMC
FHA31
I need to get the substring from 1 to till index of ':' or if that is not available till ending(in case of string 3). I need help writing this in VBA. ... | Shorter:
Split(stringval,":")(0)
| Split | 6,052,337 | 23 |
Is it possible to take two files that are open in separate tabs in gVim and combine them into one tab with a split/vsplit window? I'd prefer if there was a way to specify which tabs to join, but even something that is the opposite of :tab ball would be good enough.
Thanks
| Lots of handwork but...
:tabnew
:buffers "note the numbers
:split
:bn " where n is the number of
<CTRL-W><CTRL-W>
:bn " for the other file
:tabonly " not necessary, closes every other tab
Or you can create a function for it which asks for buffer numbers, then creates the tab, and closes every other tab (for the opene... | Split | 4,615,856 | 23 |
I'm writing a program that requires a string to be inputted, then broken up into individual letters. Essentially, I need help finding a way to turn "string" into ["s","t","r","i","n","g"]. The strings are also stored using the string data type instead of just an array of chars by default. I would like to keep it that w... | Assuming you already have the string inputted:
string s("string");
vector<char> v(s.begin(), s.end());
This will fill the vector v with the characters from a string.
| Split | 2,158,943 | 23 |
Say, I have a string
"hello is it me you're looking for"
I want to cut part of this string out and return the new string, something like
s = string.cut(0,3);
s would now be equal to:
"lo is it me you're looking for"
EDIT: It may not be from 0 to 3. It could be from 5 to 7.
s = string.cut(5,7);
would return
"hellos ... | You're almost there. What you want is:
http://www.w3schools.com/jsref/jsref_substr.asp
So, in your example:
Var string = "hello is it me you're looking for";
s = string.substr(3);
As only providing a start (the first arg) takes from that index to the end of the string.
Update, how about something like:
function cut(st... | Split | 1,707,527 | 23 |
I got a string of such format:
"Wilbur Smith (Billy, son of John), Eddie Murphy (John), Elvis Presley, Jane Doe (Jane Doe)"
so basicly it's list of actor's names (optionally followed by their role in parenthesis). The role itself can contain comma (actor's name can not, I strongly hope so).
My goal is to split this s... | One way to do it is to use findall with a regex that greedily matches things that can go between separators. eg:
>>> s = "Wilbur Smith (Billy, son of John), Eddie Murphy (John), Elvis Presley, Jane Doe (Jane Doe)"
>>> r = re.compile(r'(?:[^,(]|\([^)]*\))+')
>>> r.findall(s)
['Wilbur Smith (Billy, son of John)', ' Eddie... | Split | 1,648,537 | 23 |
Use Case
I need to split large files (~5G) of JSON data into smaller files with newline-delimited JSON in a memory efficient way (i.e., without having to read the entire JSON blob into memory). The JSON data in each source file is an array of objects.
Unfortunately, the source data is not newline-delimited JSON and in ... | jq's streaming parser (the one invoked with the --stream command-line option) intentionally sacrifices speed for the sake of reduced memory requirements, as illustrated below in the metrics section. A tool which strikes a different balance (one which seems to be closer to what you're looking for) is jstream, the homep... | Split | 62,825,963 | 22 |
If I want to take
"hi, my name is foo bar"
and split it on "foo", and have that split be case insensitive (split on any of "foO", "FOO", "Foo", etc), what should I do? Keep in mind that although I would like to have the split be case insensitive, I also DO want to maintain the case sensitivity of the rest of the strin... | You can use the re.split function with the re.IGNORECASE flag (or re.I for short):
>>> import re
>>> test = "hI MY NAME iS FoO bar"
>>> re.split("foo", test, flags=re.IGNORECASE)
['hI MY NAME iS ', ' bar']
>>>
| Split | 30,834,159 | 22 |
In Scala, I want to split a string at a specific character like so:
scala> val s = "abba.aadd"
s: String = abba.aadd
scala> val (beforeDot,afterDot) = (s takeWhile (_!='.'), s dropWhile (_!='.'))
beforeDot: String = abba
afterDot: String = .aadd
This solution is slightly inefficient (maybe not asymptotically), but I ... | There is a span method:
scala> val (beforeDot, afterDot) = s.span{ _ != '.' }
beforeDot: String = abba
afterDot: String = .aadd
From the Scala documentation:
c span p is equivalent to (but possibly more efficient than) (c takeWhile p, c dropWhile p), provided the evaluation of the predicate p does not cause any side-... | Split | 23,489,107 | 22 |
I want to break a string up into lines of a specified maximum length, without splitting any words, if possible (if there is a word that exceeds the maximum line length, then it will have to be split).
As always, I am acutely aware that strings are immutable and that one should preferably use the StringBuilder class. I... | Even when this post is 3 years old I wanted to give a better solution using Regex to accomplish the same:
If you want the string to be splitted and then use the text to be displayed you can use this:
public string SplitToLines(string stringToSplit, int maximumLineLength)
{
return Regex.Replace(stringToSplit, @"(.{1... | Split | 22,368,434 | 22 |
split will always order the splits lexicographically. There may be situations where one would rather preserve the natural order. One can always implement a hand-rolled function but is there a base R solution that does this?
Reproducible example:
Input:
Date.of.Inclusion Securities.Included Securities.Excluded yearmon... | split converts the f (second) argument to factors, if it isn't already one. So, if you want the order to be retained, factor the column yourself with the desired level. That is:
df$yearmon <- factor(df$yearmon, levels=unique(df$yearmon))
# now split
split(df, df$yearmon)
# $`4_2013`
# Date.of.Inclusion Securities.Inc... | Split | 17,611,734 | 22 |
When I perform
String test="23x34 ";
String[] array=test.split("x"); //splitting using simple letter
I got two items in array as 23 and 34
but when I did
String test="23x34 ";
String[] array=test.split("X"); //splitting using capitalletter
I got one item in array 23x34
So is there any way I can use the split method a... | split uses, as the documentation suggests, a regexp. a regexp for your example would be :
"[xX]"
Also, the (?i) flag toggles case insensitivty. Therefore, the following is also correct :
"(?i)x"
In this case, x can be any litteral properly escaped.
| Split | 16,581,977 | 22 |
Just wanted to verify some thought regarding split function. I have constructed a simple code.
var array1 = [{}];
var string1 = "A, B, C, D";
array1 = string1.split(",");
The problem is based on this kind of coding for example in flash. The string1 will split all "," then transfers it to the array1 in this format ["A... | Your code should definitely work, I just ran this with a breakpoint on Logger.log(array1); The debugger shows it as an array, and the log logs it as: [A, B, C, D]. Note, that to get the output you wanted I had to add a space to the split to get: string1.split(", ");
function myFunction() {
var array1 = splitTest();... | Split | 11,752,911 | 22 |
I am trying to get name of a File object without its extension, e.g. getting "vegetation" when the filename is "vegetation.txt." I have tried implementing this code:
openFile = fileChooser.getSelectedFile();
String[] tokens = openFile.getName().split(".");
String name = tokens[0];
Unfortunately, it returns a null obje... | If you want to implement this yourself, try this:
String name = file.getName();
int pos = name.lastIndexOf(".");
if (pos > 0) {
name = name.substring(0, pos);
}
(This variation doesn't leave you with an empty string for an input filename like ".txt". If you want the string to be empty in that case, change > 0 to ... | Split | 8,393,849 | 22 |
say I have the following string:
"Hello there. My name is Fred. I am 25.5 years old."
I want to split this into sentences, so that I have the following list:
["Hello there", "My name is Fred", "I am 25.5 years old"]
As you can see, I want to split the string on all occurrences of the string ". ", not any occurrence o... | Works for me
>>> "Hello there. My name is Fr.ed. I am 25.5 years old.".split(". ")
['Hello there', 'My name is Fr.ed', 'I am 25.5 years old.']
| Split | 8,081,569 | 22 |
I am trying to split a string using 'split-string' function based on the . character. But
(split-string "1.2.3" ".") doesn't work at all. It just returns a list of variable number of empty strings. Is . a special character that needs to be escaped or specified in some different way?
| Here is the official documentation for split-string function -
https://www.gnu.org/software/emacs/manual/html_node/elisp/Creating-Strings.html
The second argument to the split-string function in (split-string "1.2.3" "\.") is a regular expression and as a result both the '.' character and '' character have special mean... | Split | 6,236,196 | 22 |
I have a string like this:
key=value, key2=value2
and I would like to parse it into something like this:
array(
"key" => "value",
"key2" => "value2"
)
I could do something like
$parts = explode(",", $string)
$parts = array_map("trim", $parts);
foreach($parts as $currentPart)
{
list($key, $value) = explode("=... | If you don't mind using regex ...
$str = "key=value, key2=value2";
preg_match_all("/([^,= ]+)=([^,= ]+)/", $str, $r);
$result = array_combine($r[1], $r[2]);
var_dump($result);
| Split | 4,923,951 | 22 |
As shown below,
Is it possible to split a Polygon by a Line? (into two Polygons). If the line doesn't go all the way across the polygon it would fail.
Is this possible? If so, how would I do this?
| I had to do this recently. Just walking the polygon won't work for concave polygons, as in your diagram. Below is a sketch of my algorithm, inspired by the Greiner-Hormann polygon clipping algorithm. Splitting is both easier and harder than polygon clipping. Easier because you only clip against a line instead of a rect... | Split | 3,623,703 | 22 |
I have a code for reading files with float numbers on line stored like this: "3.34|2.3409|1.0001|...|1.1|". I would like to read them using istringstream, but it doesn't work as I would expect:
string row;
string strNum;
istringstream separate; // textovy stream pro konverzi
while ( getline(file,row) ) {
... | After setting the row into the istringstream...
separate.str(row);
... reset it by calling
separate.clear();
This clears any iostate flags that are set in the previous iteration or by setting the string.
http://www.cplusplus.com/reference/iostream/ios/clear/
| Split | 2,767,298 | 22 |
How do you take paragraph or large amount of text and break it into sentences (perferably using Ruby) taking into account cases such as Mr. and Dr. and U.S.A? (Assuming you just put the sentences into an array of arrays)
UPDATE:
One possible solution I thought of involves using a parts-of-speech tagger (POST) and a cl... | Try looking at the Ruby wrapper around the Stanford Parser. It has a getSentencesFromString() function.
| Split | 860,809 | 22 |
I want to add a space between every 4 characters. I'm developing a webpage about credit card numbers.
example
var x = document.getElementById("card_number").value;
example :
if the value of x is 1234567890123456
I need to split this number every 4 characters and add a space. Like this
1234 5678 9012 3456
and I need t... | You can use RegEx for this
const dummyTxt = '1234567890123456';
const joy = dummyTxt.match(/.{1,4}/g);
console.log(joy.join(' '));
| Split | 53,427,046 | 21 |
What would be an idiomatic way to split a string into strings of 2 characters each?
Examples:
"" -> [""]
"ab" -> ["ab"]
"abcd" -> ["ab", "cd"]
We can assume that the string has a length which is a multiple of 2.
I could use a regex like in this Java answer but I was hoping to find a better way (i.e. using one of kotli... | Once Kotlin 1.2 is released, you can use the chunked function that is added to kotlin-stdlib by the KEEP-11 proposal. Example:
val chunked = myString.chunked(2)
You can already try this with Kotlin 1.2 M2 pre-release.
Until then, you can implement the same with this code:
fun String.chunked(size: Int): List<String> {... | Split | 45,659,916 | 21 |
I am trying to split (or explode) a string in Swift (1.2) using multiple delimiters, or seperators as Apple calls them.
My string looks like this:
KEY1=subKey1=value&subkey2=valueKEY2=subkey1=value&subkey2=valueKEY3=subKey1=value&subkey3=value
I have formatted it for easy reading:
KEY1=subKey1=value&subkey2=value
KEY2... | One can also use the following approach to split a string with multiple delimiters in case keys are single characters:
//swift 4+
let stringData = "K01L02M03"
let res = stringData.components(separatedBy: CharacterSet(charactersIn: "KLM"))
//older swift syntax
let res = stringData.componentsSeparatedByCharactersInSet(N... | Split | 32,465,121 | 21 |
I have one big array:
[(1.0, 3.0, 1, 427338.4297000002, 4848489.4332)
(1.0, 3.0, 2, 427344.7937000003, 4848482.0692)
(1.0, 3.0, 3, 427346.4297000002, 4848472.7469) ...,
(1.0, 1.0, 7084, 427345.2709999997, 4848796.592)
(1.0, 1.0, 7085, 427352.9277999997, 4848790.9351)
(1.0, 1.0, 7086, 427359.16060000006, 4848787.43... | You can find the indices where the values differ by using numpy.where and numpy.diff on the first column:
>>> arr = np.array([(1.0, 3.0, 1, 427338.4297000002, 4848489.4332),
(1.0, 3.0, 2, 427344.7937000003, 4848482.0692),
(1.0, 3.0, 3, 427346.4297000002, 4848472.7469),
(1.0, 1.0, 7084, 427345.2709999997, 4848796.592... | Split | 31,863,083 | 21 |
Really, pretty much what the title says.
Say you have this string:
var theString = "a=b=c=d";
Now, when you run theString.split("=") the result is ["a", "b", "c", "d"] as expected. And, of course, when you run theString.split("=", 2) you get ["a", "b"], which after reading the MDN page for String#split() makes sense t... | If you want the exact equivalent of the Java implementation (no error checking or guard clauses etc):
function split(str, sep, n) {
var out = [];
while(n--) out.push(str.slice(sep.lastIndex, sep.exec(str).index));
out.push(str.slice(sep.lastIndex));
return out;
}
console.log(split("a=b=c=d", /=/g, 2)... | Split | 29,998,343 | 21 |
In my SQL statement I have to extract a substring from a string at the character '_'. Strings can be for example 'A_XXX' 'AB_XXX' 'ABC_XXXX', so the extracted substrings should be like 'A' 'AB' 'ABC'.
In Oracle this is easy with the substr() and instr() functions:
select substr('AB_XXX', 1, instr('AB_XXX', '_')-1) as s... | tl;dr
Use split_part which was purposely built for this:
split_part(string, '_', 1)
Explanation
Quoting this PostgreSQL API docs:
SPLIT_PART() function splits a string on a specified delimiter and returns the nth substring.
The 3 parameters are the string to be split, the delimiter, and the part/substring number (st... | Split | 29,895,896 | 21 |
for example .. If I have a text like this
214asd
df5df8
d66f66
I want to split them into 3 strings using vb.net .
| Assuming you want to split on new lines - using String.Split will return an array containing the parts:
Dim parts As String() = myString.Split(new String() {Environment.NewLine},
StringSplitOptions.None)
This will be platform specific, so you may want to split on "\n", "\r", "\n\... | Split | 14,795,943 | 21 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.