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 am facing a strange situation where I am using gitlab account to handle my code. I am using ssh protocol to access the repo. I am able to pull the code but I am receiving the following error while I try to push the code. This could be something silly on my side. But I have the keys stored in my gitlab profile and abl...
Finally I have been able to resolve this issue and I am posting it for other users. If the keys generated by putty is not helping you to access the gitlab repo, try generating the keys from gitbash terminal using the command ssh-keygen and save the files in .ssh folder of your user account. The linux style key generati...
GitLab
33,302,130
16
I've been following the instructions from the GitLab wiki, however, it seems as if some key pieces of information are missing. In the section "Using a Non-Bundled Web Server" it never explains how I need to reconfigure my Nginx installation to reverse proxy over to GitLab. Basically, I'd like to have GitLab installed u...
I got it working! So insanely excited! So as I said, I was attempting to follow these instructions, but I wasn't getting anywhere, since it seemed to be lacking instructions on how to make your existing Nginx install link into Gitlab. Well, further down on the page they have a more complete explanation for Using an Exi...
GitLab
29,403,212
16
I have a Git/Gitlab repository. We used to commit straight to master, but we decided to switch to using feature branches like the rest of the world for this release. We need to reset our remote master to the state it was in immediately after the last release. If someone has already committed to the master directly, how...
To reset a local branch, git branch -f master last-release To reset a remote branch, git push -f origin last-release:master where last-release is the ref (commit id or branch) you want to reset master to. (Neither of these affect your working tree; you can even do these from a bare repo, if you wish.)
GitLab
22,674,267
16
I'm new to gitlab and CI so i had tons of questions but some of them solved via google, SO, git mans, but not the last ... I can't clone repo via ssh =( If i try to clone repo via http: lesha@lesha-SeoTeam:/var/www$ git clone http://gitlab.vbox/root/virtualboxgitlab.git Cloning into 'virtualboxgitlab'... Username for '...
GitLab 5.x doesn't use gitolite anymore, but gitlab-shell. I would advise to create a dedicated account, as recommended in the installation process. ssh git@gitlab.vbox That ssh commands means you are asking for a secure shell on 'gitlab.vbox' as user 'git'. If that user doesn't exist... it won't work. There is no n...
GitLab
17,739,978
16
After the first release of our product, we will be switching to a different branches for the main development and feature development. Is there a way to create a branch in such a way, so that we can protect it from being removed (accidentally or on purpose) unless you're a specific user (based on role or username)? I ...
There are many ways to tackle this: Make another repo that's a sand box, and give readonly access to the master one. If they delete by accident they can get the branch from the master repo. This assumes you are only using github for your repos aside the local dev repos. Setup hooks in the repository that don't allow ...
GitLab
11,401,155
16
In Gitlab ci We have declared our variables like below USER_NAME: value: "" description: "Enter Username" File_Name: description: "Enter the file name" It only give a text box where We can enter the value. Can I make a drop down select box is there any option available to make it a select box.Then we ...
GitLab 15.7 (December 2022) has finally implemented this: Select predefined CI/CD variables values from a dropdown list Previously, you could pre-fill CI/CD variables in the “Run pipeline” page, with a specific value. Unfortunately, if you had multiple options for the variable’s value, you still had to manually input ...
GitLab
69,763,984
15
We are working with GitLab CI and a strange behaviour just happened. We are trying to only run a given job (e.g, lint here below) if *.py files are changed and we are in a merge request, not a simple git branch. If, for example, I am going to push a change on the Readme.MD, the pipeline's job Lint here will be executed...
The problem is in your job rules. Below are your numbered rules for better orientation: 1. $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_IID && changes 2. $CI_COMMIT_REF_NAME == "develop" 3. $CI_COMMIT_REF_NAME == "main" Let's consider some examples, variables values and job evaluation result with ...
GitLab
69,540,677
15
I have a packge script which needs to run on alpina:helm image . I have used this before but for some reason this is always giving me error as - Error: unknown command "sh" for "helm" package: <<: *artifacts stage: package image: alpine/helm variables: GIT_STRATEGY: none script: - echo $VERSION - ...
As explained in the docs, the runner in gitlab is started this way the runner starts the docker container specified in image and uses the entrypoint of this container the runner attaches itself to the container the runner combines before_script, script and after_script into a single script the runner sends the combine...
GitLab
67,289,837
15
I'm looking for the right way to set up a variable when I launch a job manually. I tried : stages: - test my_job: stage: test script: - echo "HEY" variables: FIRST_VARIABLE: "my_variable" SECOND_VARIABLE: value: "a" description: "b" when: manual I want my SECOND_VARIABLE to appear...
This is currently not implemented, it is supported on the New Pipeline Form but not for manual steps - https://gitlab.com/gitlab-org/gitlab/-/issues/30101 is a good resource, where you can easily track the progress. There are tickets in the backlog like https://gitlab.com/gitlab-org/gitlab/-/issues/22629 - but as said ...
GitLab
66,207,501
15
I have a scheduled pipeline that copies some data from one server to another once a day. The pipeline works fine on all branches but doesn't start if I select master branch (default branch) as the target branch. I have tried on an exact copy of master and it worked fine. I though it could be because master is protected...
I finally figured out the problem! The issue is that gitlab was saying Successfully scheduled a pipeline to run. Go to the Pipelines page for details. while in reality there was an error. To debug it I used the trick described here that is to run a manual pipeline and set CI_PIPELINE_SOURCE = "schedule". Running the pi...
GitLab
65,816,737
15
Git command itself supports the Signed-off-by: Person's name <persons@email> line. GitHub adds Co-authored-by: line, which then shows both the committer and the referenced person as commit authors in the UI. (See Q: GitHub co-authored-by with private noreply address for discussion how to avoid exposing email addresses....
From the OP: The git command itself supports the Signed-off-by: Person's name <persons@email> line. Starting with Git 2.32 (Q2 2021), the git command itself supports... any trailer you want! "git commit"(man) learned --trailer <key>[=<value>] option; together with the interpret-trailers command, this will make it eas...
GitLab
58,525,836
15
So after googling a little bit (which is polluted by people having trouble with Pull Secrets) I am posting this here — and to GCP Support (will update as I hear). I created a Cluster from GitLab Kubernetes integration (docs: https://about.gitlab.com/solutions/kubernetes) within the same project as my GCR registry / ima...
TL;DR — Clusters created by GitLab-Ci Kubernetes Integration will not be able to pull an image from a GCR Registry in the same project as the container images — without modifying the Node(s) permissions (scopes). While you CAN manually modify the permissions on an Individual Node machine(s) to grant the Application De...
GitLab
54,043,495
15
I'm trying to run my Gitlab CI locally using Gitlab-runner and docker before committing to make sure they work okay. But I'm having some strange issues! Unfortunately I have no choice but to use windows (I've had success in the past on Linux). Every time I run a job in powershell: C:/Gitlab-runner/gitlab-runner exec do...
Docker is not fully supported by GitLab Runner on Windows yet. The workaround is to use Windows Subsystem for Linux and install gitlab-runner there: curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh | sudo bash sudo apt-get install gitlab-runner gitlab-runner exec docker build ...
GitLab
53,472,481
15
I have a job in my .gitlab-ci.yml file which does an npm install like so: test: image: node:10 script: - npm install - npm test The problem is that I'm referencing a private GitLab repo in my package.json: "dependencies": { "internal-dep": "git+https://gitlab.com/Company/internal-dep.git", ... The npm...
There are two approaches I've found that allow Git to auth successfully against GitLab during the npm install step (which uses Git under the hood to access this dependency). First approach, as shown in this .gitlab-ci.yml job: test: image: node:10 script: - echo -e "machine gitlab.com\nlogin gitlab-ci-token\npa...
GitLab
52,784,182
15
In my gitlab-ci.yml file, I have defined 3 stages, and the 2nd and 3rd stages have 3 jobs each, resulting in the following structure: The 1st and 2nd stage works as I intended, however, for the 3rd stage what I'd actually like to have is something like this (the image is a mockup of course), i.e. "parallel sequences" ...
This feature was added in the new GitLab release (v12.2)
GitLab
52,382,718
15
I have a C++ project that is compiled and packaged for multiple OS (Linux, Windows, MacOS) as well as multiple CPU architectures (i386, x86_64, arm, Aarch64) For this I'm using Jenkins to grab the source code and run the build script in parallel on each system. It's a simple working solution, since my build script deal...
GitLab uses "runners" to execute CI jobs. Runners are installed wherever you want to run a CI job, so if you want to run on multiple architectures then you will need to install runners on systems for each architecture. Runner install documentation can be found here: https://docs.gitlab.com/runner/install/index.html F...
GitLab
52,031,860
15
I am trying to work simultaneously on more than one (two or three) GitLab (or even GitHub) projects on a single development machine. Because upon configuration the IDEs and the git service has the data of my primary user when I try to checkout or clone another project with a different username / password the system say...
By default, git is using a system-wide configuration file or the one stored at top of your home directory. But you can also set a file .git/config inside each repository, either by editing manually or using git config. Inside, you may specify the following sections : [user] name = Your name email = yourownemail...
GitLab
50,354,412
15
I want to understand the difference between projects and subgroups in GitLab. Please help me on understanding the above.
Project A project manages one git repository and adds an issue tracker, a wiki, etc: See: https://docs.gitlab.com/ee/user/project/index.html#doc-nav Groups Groups can be used to combine several projects under one topic. Examples: You could put all your JavaScript projects in a group called "js" You could create one g...
GitLab
50,272,566
15
I have a secret var : But when I do - echo %MySecretVar%, runner displays foo only How can i escape special chars like ! in Gitlab Secret Vars ?
I had the same problems with Gitlab, job running on windows, but I assume it will reproduce on Linux as well, because it seems Gitlab parsing issue or relay weird escaping. So I have set environment variable APPPOOL_PWD: 'blabla!foo$bar' and output of echo %APPPOOL_PWD% or echo $APPPOOL_PWD was 'blabla' The Gitlab see...
GitLab
48,870,664
15
For testing a command line tool against a Gitlab instance in Docker, I would like to login to Gitlab using username and password and grab the created session to authenticate my API requests. Therefore I do the following: curl the user login page with curl -i http://localhost:8080/users/sign_in -s get me the _gitlab_se...
With some helpful tips by other answers and comments, I finally came up with this solution: gitlab_host="http://localhost:8080" gitlab_user="root" gitlab_password="12341234" # curl for the login page to get a session cookie and the sources with the auth tokens body_header=$(curl -c cookies.txt -i "${gitlab_host}/users...
GitLab
47,948,887
15
Let's say I have these stages defined in .gitlab-ci.yml: stages: - build - analysis - tests - deploy - post-deploy Since analysis takes a lot of time and I don't really care about the result (I also have allow_failure: true set) - is it possible to somehow define to start analysis and then immediat...
Since v12.8, you can use needs: [] to start jobs start immediately. Docs: https://docs.gitlab.com/ee/ci/yaml/#needs
GitLab
47,286,456
15
I've created a remote branch whose name starts with a hashtag mark and I've quickly learnt it's a bad idea as # is considered as a comment mark by git. Therefore, I would like to delete that branch now but I can't find a proper way to do so… I've tried : git push origin --delete <#branch_name> git push origin --delete ...
Escape the #: git push origin --delete \#branch_name ↑
GitLab
46,402,440
15
How do I use PowerShell commands/scripts with Gitlab CI in a .gitlab-ci.yml file which is used to deploy to gitlab pages? I am trying to execute the build.ps1 file from .gitlab-ci.yml, but when it reaches the build.ps1 line, it gives an error saying /bin/bash: line 5: .build.ps1: command not found I am trying to use th...
I have been able to figure out a solution to my own question. Solution To Run PowerShell Command/Script from a .gitlab-ci.yml file on a gitlab.com using the Gitlab CI, you need to make sure that the contents of your .gitlab-ci.yml file is as shown below. Note: The .gitlab-ci.yml below works without having to install a...
GitLab
44,319,313
15
I'm starting phantomjs with specific arguments as part of my job. This is running on a custom gitlab/gitlab-ci server, I'm currently not using containers, I guess that would simplify that. I'm starting phantomjs like this: - "timeout 300 phantomjs --ssl-protocol=any --ignore-ssl-errors=true vendor/jcalderonzumba/gaston...
TL;DR; - spawn the process in a new thread with & but then you have to make sure the process is killed in successfull and failure builds. i use this (with comments): 'E2E tests': before_script: - yarn install --force >/dev/null # if there is already an instance running kill it - this is ok in my case - as thi...
GitLab
44,112,605
15
This is how I do some linter test (eslint). linter: image: ubuntu:16.04 stage: test tags: - testing before_script: - apt-get update -y - apt-get install nodejs-legacy -yqq - apt-get install curl -yqq - curl https://install.meteor.com/ | sh - meteor npm install eslint eslint-plugin-react ...
You need to edit your config.toml file which is in /etc/gitlab-runner on your runner machine with the following [runners.docker] pull_policy = "if-not-present" See related issue here.
GitLab
43,481,618
15
I have a directory which is generated during a build and it should not be deleted in the next builds. I tried to keep the directory using cache in .gitlab-ci.yml: cache: key: "$CI_BUILD_REF_NAME" untracked: true paths: - target_directory/ build-runner1: stage: build script: - ./build-platform.sh targe...
What you need is to use a job artifacts: Artifacts is a list of files and directories which are attached to a job after it completes successfully. .gitlab-ci.yml file: your job: before_script: - do something script: - do another thing - do something to generate your zip file (example...
GitLab
42,948,062
15
is it possible to exclude a directory from displaying a diff of merge request in GitLab? We started to version the bower_components folder (1 - to speed up app build, 2 - because bower has no .lock mechanism), but it makes trouble when doing code review - many changed files appear inside bower_components which makes th...
Since gitlab 8.8, gitlab support the .gitattributes. So if your project does not have .gitattributes add it, and to exclude files for diff, append: *.<whatever> -diff and to exclude directories from a diff: <mydir> -diff
GitLab
41,116,855
15
I have the following configuration as .gitlab-ci.yml but I found out after successfully pass build stage (which would create a virtualenv called venv), it seems that in test stage you would get a brand new environment(there's no venv directory at all). So I wonder should I put setup script in before_script therefor it...
Gitlab CI jobs supposed to be independent, because they could run on different runners. It is not issue. There two ways to pass files between stages: The right way. Using artefacts. The wrong way. Using cache. With cache key "hack". Still need same runner. So yes, supposed by gitlab way to have everything your job de...
GitLab
31,623,924
15
I am running the AWS AMI from gitlab. I am trying to access the postgres database directly using psql. I thought I could just use the credentials in database.yml, since the rails application is working fine: /opt/gitlab/embedded/bin/psql -U gitlab -d gitlabhq_production But I get: psql: FATAL: Peer authentication fai...
sudo -u gitlab-psql /opt/gitlab/embedded/bin/psql -h /var/opt/gitlab/postgresql/ gitlabhq_production
GitLab
30,282,149
15
I am trying to pull a repo from github and push it up to a private repo on a gitlab server that I am running. I cloned the github repo to my local machine git clone https://github.com/somepage/someproject at that point I added a new remote (my gitlab) git remote add gitlab https://mygitlabserver/mypage/myproject the...
I suspect you are getting that error because the default configuration of a repository in gitlab is to have a default branch name of master. You have only pushed a branch named develop, and when you clone the repository git is attempting to checkout the nonexistent master branch. You can: go into the repository setti...
GitLab
29,433,701
15
I started exploring Gitlab for version control management and I got an issue at the first step itsself. When ever I create a project its creating a new repository. I have few webapplications which are independent to each other. In that case do I need to use different repository for every project. What I am looking for...
Gitlab manages projects: a project has many features in addition of the Git repo it includes: issues: powerful, but lightweight issue tracking system. merge requests: you can review and discuss code before it is merged in the branch of your code. wiki: separate system for documentation, built right into GitLab snippet...
GitLab
27,282,439
15
I'm using gitlab. When I go into the interface, on each branch I can download the source code as a zip, tar or whatsoever. I am making rpm spec files for which I would need the possibility to download the tar ball using command line. since I added my rsa key i can do git clone without problems: git clone http://gitlab/...
Since GitLab 6.2 and issue 5253, it should be: GET /projects/:id/repository/archive But that seems for internal use only, since you cannot know the id of a project as a user (only its name). Don't forget, as shown in ability.rb, that downloading an archive is linked to a permission. Make sure you have that "download_c...
GitLab
22,691,197
15
when opening a project in gitlab, you will see SSH and HTTP(or HTTPS) url on the top of project home page, the SSH url is as default, but I want to set HTTP(or HTTPS) as default, so how should I do? Thanks
infact, you have to modify 2 other lines above the default_clone_protocol. def default_url_to_repo(project = nil) project = project || @project current_user ? project.http_url_to_repo : project.url_to_repo end def default_clone_protocol current_user ? "http" : "ssh" end
GitLab
21,203,344
15
I understand that gitlab has support to Jenkins CI, but what I need is a lot less than that. I have a Rails application and get the coverage from the tests using simplecov. It generates HTML output in a directory by running a rake task. I would like to see the current coverage through gitlab. Is there a simple way to ...
I fear there is still no easy way to integrate code coverage reports but Gitlab now supports (since Version 8.0 integrated) build jobs for your code. Unfortunately you have to implement your solution by writing a custom .gitlab-ci.yml to run your coverage tests. For viewing the reports, you can specify the generated "a...
GitLab
17,811,917
15
I recognize that this is a duplicate question however all the other answers I've found related to this issue have not seemed to help me... I'm installing GitLab and running through the gem dependencies when it hits the NokoGiri gem requirement and fails with the following info: ERROR: Error installing nokogiri: ERROR:...
first make sure you have all the dependencies, as mentioned in "Installing Nokogiri with RVM on Ubuntu" (which mentions the very same error message) I have no idea why it can't find the package "libxslt". Instead of worrying about that, I'm going to install the dependencies listed on Nokogiri GitHub page: $ sudo apt...
GitLab
16,084,144
15
I'm dealing with a GitLab Community Edition 13.10.1. At the moment there are about a hundred small projects on this. By selecting a project it is possible to search for specific code within all its files, but if instead I go to the GitLab search and select "Any" project, the "Code" tab is no longer visible. Is there a...
You can use GitLab Advanced Search to search for code if you are subscribed to the premium tier. Another option would be to use the opensource gitlab-search tool if you are using the community edition.
GitLab
69,466,442
14
Some time ago, our Gitlab (self-hosted) instance started to throw errors that the archives are too big: ERROR: Uploading artifacts as "archive" to coordinator... too large archive id=something responseStatus=413 Request Entity Too Large status=413 token=something FATAL: too large ERROR: Job failed: exit code 1 The o...
From gitlab official docs: The maximum size of the job artifacts can be set at: The value is in MB and the default is 100MB per job. To change it at the instance level: On the top bar, select Menu > Admin. On the left sidebar, select Settings > CI/CD. Change the value of maximum artifacts size (in MB). Select Save ch...
GitLab
64,329,087
14
I have a remote runner: ci$ gitlab-runner --version Version: 12.2.0 The .gitlab-ci.yml : stages: - build - deploy variables: LANG: "en_US.UTF-8" LC_ALL: "en_US.UTF-8" build: tags: - ios stage: build script: - bundle exec fastlane build except: - develop - master - /^rc\/.*$...
You have to make sure that the remote runner you are referring to is: Actually running Listed as an activated runner in your project's Runners section Configured to follow/listen to the same tags Go to your repo's Gitlab project settings. Then find the section for CI / CD > Runners. You should see something like the ...
GitLab
60,109,622
14
I have created a pipeline in gitlab, with image: name: hashicorp/terraform:light entrypoint: - '/usr/bin/env' - 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' variables: PLAN: dbrest.tfplan STATE: dbrest.tfstate cache: paths: - .terraform before_script: - terraform --ver...
You have mixed a job with when: manual to when you trigger a pipeline manually. This is the one you want: https://docs.gitlab.com/ee/ci/pipelines/#run-a-pipeline-manually You could use this together with an only for some variable. Something like: ... apply: stage: deploy environment: name: production script: ...
GitLab
58,710,222
14
The error below is triggered when executing kubectl -n gitlab-managed-apps logs install-helm. I've tried regenerating the certificates, and bypassing the certificate check. Somehow it is using my internal certificate instead of the certificate of the source. root@dev # kubectl -n gitlab-managed-apps logs install-helm ...
After having the same issue I finally found the solution for it: In the /etc/resolv.conf file on your Master and Worker nodes you have to search and remove the search XYZ.com entry. If you are using Jelastic you have to remove this entry every time after a restart. It gets added by Jelastic automatically. I already con...
GitLab
54,163,478
14
I am using Gitlab for repository and ci/cd. Currently trying to set up pipeline that creates a docker image from a build stage. All examples I have seen have a simple naming of image where e.g. the branch is used(master) My question is if I want to tag the image based on the current tag in the repository how do I do th...
There are a lot of predefined variables in Gitlab CI. I think you are looking for CI_COMMIT_TAG. So you could use it this way: docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_TAG So the image would look like registry.example.com/group/project:tag
GitLab
51,431,684
14
Is it possible to have one git repo placed on both github and gitlab? So that if you push to a remote repo that its both on Github and Gitlab.
You have misunderstood how Git works. Or how content hosting works. First of all, your repo is not on GitHub nor GitLab. Your repo is on your hard disk, right there where you cloned or created it. This is a repository. Local one. This is where you do the work *) On GitHub and on GitLab you can setup remote copy of your...
GitLab
50,686,889
14
I have my .gitlab-ci.yml file set up in the typical three stages: test, build, deploy. During the build stage, I run a command that compiles my project and puts it in a tarball. The build stage appears to execute successfully because it moves on to the deploy stage, but the deploy stage then says it can't find the tarb...
For each test gitlab-ci clean the build folder, therefore the output files of the build stage are not available in the deploy stage. You need to rebuild your project also in the deploy stage. The "stages" are only useful to order your tests, i.e. avoid to try to do a deploy test if a build test failed. EDIT: Since Gitl...
GitLab
33,409,863
14
We are using Gitlab (7.10.2) and Redmine (3.0.2). All issues are managed in Redmine and Gitlab manages all git-repositories. We set up Gitlab via the UI so far that commits with the message 'Close #234' are clickable and pointing to the corresponding Redmine ticket website. We now want to achieve that tickets in Redmin...
You can use Redmine as an issue tracker with setting the redmine service in Gitlab (In your project -> Services -> Redmine -> fill the URLs, and set active). If this works, when you press "new issue" button in Gitlab, you are redirected to Redmine new issue page. In Gitlab you should have WebHook to inform the Redmine ...
GitLab
30,177,291
14
Scenario: we are 3 developers. Developer 1 (admin) created the main repo. Developer 2 forked admin's repo. Developer 3 forked admin's repo. Developer 2 created a feature branch "Feature 1" Developer 3 checked out "Feature 1" from developer 2 repo. When Developer 3 tries to create a Merge Request he only sees his own a...
No forks, maybe? You may utilise the fact, that merge requests can be made within the same repository. So maybe all three may use the same repository as developers, the admin should set the crucial branches as protected. If any change is made, anyone can create a merge request from one branch to another... and anyone c...
GitLab
28,950,433
14
I don't think I'm really understanding how Gerrit can fit into my group's existing workflow. Is Gerrit intended to be the central "hub" of code? I have been imagining it as similar to Atlassian's Crucible, which fits in with Atlassian's Stash or Bitbucker. My group currently uses a very active Gitlab installation but t...
Gerrit expects to "own" the repositories you use it with, i.e. it expects the git directories to be present in a mounted file system. If you want it to interact with GitLab (or GitHub) you can set up one way replication from Gerrit to GitLab so that changes made in Gerrit will be pushed to GitLab within a few seconds. ...
GitLab
25,880,670
14
This is what I tried: curl http://git.ep.petrobras.com.br/api/v3/session --data-urlencode 'login=myUser&password=myPass' Answer: {"message":"401 Unauthorized"}
The problem is the data-urlencode CURL option. Since it's an HTTP POST you don't need to URL encode the data, and is actually encoding the & into &amp; and causing your issue. Instead use the --data option. curl http://git.ep.petrobras.com.br/api/v3/session --data 'login=myUser&password=myPass' Also, be careful sendin...
GitLab
23,640,961
14
I just recently install GitLab v5.0 on an Ubuntu 12.04 server and am now having issues with email notifications. I can't get GitLab to send any emails of any kind. I've got my config/environments/production.rb file setup to use sendmail as the transport service: config.action_mailer.delivery_method = :sendmail config....
This is my entries at the end in /config/environment/production.rb and that is working for me. Comment out sendmail options and use external SMTP relays ##config.action_mailer.delivery_method = :sendmail ## Comment out this # Defaults to: ## config.action_mailer.sendmail_settings = { ## :location => '/usr/sb...
GitLab
16,201,090
14
I have a file (say called list.txt) that contains relative paths to files, one path per line, i.e. something like this: foo/bar/file1 foo/bar/baz/file2 goo/file3 I need to write a bash script that processes one path at a time, splits it at the last slash and then launches another process feeding it the two pieces of t...
Use basename and dirname, that's all you need. part1=$(dirname "$p") part2=$(basename "$p")
Split
13,767,252
108
I have a data frame with 10 columns, collecting actions of "users", where one of the columns contains an ID (not unique, identifying user)(column 10). the length of the data frame is about 750000 rows. I am trying to extract individual data frames (so getting a list or vector of data frames) split by the column contain...
You can just as easily access each element in the list using e.g. path[[1]]. You can't put a set of matrices into an atomic vector and access each element. A matrix is an atomic vector with dimension attributes. I would use the list structure returned by split, it's what it was designed for. Each list element can hold ...
Split
18,527,051
107
I need help with the split() method. I have the followingString: String values = "0|0|0|1|||0|1|0|||"; I need to put the values into an array. There are 3 possible strings: "0", "1", and "" My problem is, when i try to use split(): String[] array = values.split("\\|"); My values are saved only until the last 0. Se...
This behavior is explicitly documented in String.split(String regex) (emphasis mine): This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array. If you want those trailing empty str...
Split
14,414,582
107
I need to split a JavaScript array into n sized chunks. E.g.: Given this array ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"] and a n equals to 4, the output should be this: [ ["a1", "a2", "a3", "a4"], ["a5", "a6", "a7", "a8"], ["a9", "a10", "a11", "a12"], ["a13"] ] I aware o...
Take a look at lodash' chunk: https://lodash.com/docs#chunk const data = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"]; const chunks = _.chunk(data, 3); console.log(chunks); // [ // ["a1", "a2", "a3"], // ["a4", "a5", "a6"], // ["a7", "a8", "a9"], // ["a10", "a11", "a12...
Split
8,566,667
106
On a Linux desktop (RHEL4) I want to extract a range of bytes (typically less than 1000) from within a large file (>1 Gig). I know the offset into the file and the size of the chunk. I can write code to do this but is there a command line solution? Ideally, something like: magicprogram --offset 102567 --size 253 < inpu...
Try dd: dd skip=102567 count=253 if=input.binary of=output.binary bs=1 The option bs=1 sets the block size, making dd read and write one byte at a time. The default block size is 512 bytes. The value of bs also affects the behavior of skip and count since the numbers in skip and count are the numbers of blocks that dd...
Split
1,423,346
105
I am new in Java although had a good experience in PHP, and looking for perfect replacement for explode and implode (available in PHP) functions in Java. I have Googled for the same but not satisfied with the results. Anyone has the good solution for my problem will be appreciated. For example: String s = "x,y,z"; //He...
The Javadoc for String reveals that String.split() is what you're looking for in regard to explode. Java does not include a "implode" of "join" equivalent. Rather than including a giant external dependency for a simple function as the other answers suggest, you may just want to write a couple lines of code. There's a n...
Split
16,773,599
104
I have a small function I found that takes a string from a textarea and then puts it into a canvas element and wraps the text when the line gets too long. But it doesn't detect line breaks. This is what it's doing and what it should do: Input: Hello This is dummy text that could be inside the text area. It will then g...
Using .split(): var str = `your text that spans multiple lines` // Split the string on \n or \r characters var separateLines = str.split(/\r?\n|\r|\n/g); alert("Total number of separate lines is: " + separateLines.length); Or using .match() instead: var str = `your text that sp...
Split
21,711,768
103
I have string for example: "238 NEO Sports". I want to split this string only at the first space. The output should be ["238","NEO Sports"]. One way I could think of is by using split() and finally merging the last two strings returned. Is there a better way?
Just pass the count as second parameter to str.split function. >>> s = "238 NEO Sports" >>> s.split(" ", 1) ['238', 'NEO Sports']
Split
30,636,248
101
I'm trying to convert some code from Python to C++ in an effort to gain a little bit of speed and sharpen my rusty C++ skills. Yesterday I was shocked when a naive implementation of reading lines from stdin was much faster in Python than C++ (see this). Today, I finally figured out how to split a string in C++ with m...
As a guess, Python strings are reference counted immutable strings, so that no strings are copied around in the Python code, while C++ std::string is a mutable value type, and is copied at the smallest opportunity. If the goal is fast splitting, then one would use constant time substring operations, which means only re...
Split
9,378,500
100
How can I split a string only once, i.e. make 1|Ceci n'est pas une pipe: | Oui parse to: ["1", "Ceci n'est pas une pipe: | Oui"]? The limit in split doesn't seem to help...
You'd want to use String.indexOf('|') to get the index of the first occurrence of '|'. var i = s.indexOf('|'); var splits = [s.slice(0,i), s.slice(i+1)];
Split
2,878,703
100
I want to split a 400k line long log file from a particular line number. For this question, lets make this an arbitrary number 300k. Is there a linux command that allows me to do this (within the script)? I know split lets me split the file in equal parts either by size or line numbers but that's not what I want. I wan...
file_name=test.log # set first K lines: K=1000 # line count (N): N=$(wc -l < $file_name) # length of the bottom file: L=$(( $N - $K )) # create the top of file: head -n $K $file_name > top_$file_name # create bottom of file: tail -n $L $file_name > bottom_$file_name Also, on second thought, split will work in ...
Split
3,066,948
99
I have the following String: String str = "\nHERE\n\nTHERE\n\nEVERYWHERE\n\n"; If you just print this, it would output like this (Of course the \n wouldn't be "literally" printed): \n HERE\n \n THERE\n \n EVERYWHERE\n \n \n When I call the method split("\n"), I want to get all strings between the new line (\n) charac...
use str.split("\n", -1) (with a negative limit argument). When split is given zero or no limit argument it discards trailing empty fields, and when it's given a positive limit argument it limits the number of fields to that number, but a negative limit means to allow any number of fields and not discard trailing empty ...
Split
13,939,675
97
I have a String like this : String attributes = " foo boo, faa baa, fii bii," and I want to get a result like this : String[] result = {"foo boo", "faa baa", "fii bii"}; So my issue is how should to make split and trim in one shot i already split: String[] result = attributes.split(","); But the spaces still in the ...
Use regular expression \s*,\s* for splitting. String result[] = attributes.split("\\s*,\\s*"); For Initial and Trailing Whitespaces The previous solution still leaves initial and trailing white-spaces. So if we're expecting any of them, then we can use the following solution to remove the same: String result[] = attr...
Split
41,953,388
94
I'm trying to find a Delphi function that will split an input string into an array of strings based on a delimiter. I've found a lot from searching the web, but all seem to have their own issues and I haven't been able to get any of them to work. I just need to split a string like: "word:doc,txt,docx" into an array bas...
you can use the TStrings.DelimitedText property for split an string check this sample program Project28; {$APPTYPE CONSOLE} uses Classes, SysUtils; procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ; begin ListOfStrings.Clear; ListOfStrings.Delimiter := Delimiter; ListOfString...
Split
2,625,707
94
What is the best method of splitting a String into a Stream? I saw these variations: Arrays.stream("b,l,a".split(",")) Stream.of("b,l,a".split(",")) Pattern.compile(",").splitAsStream("b,l,a") My priorities are: Robustness Readability Performance A complete, compilable example: import java.util.Arrays; import java....
Arrays.stream/String.split Since String.split returns an array String[], I always recommend Arrays.stream as the canonical idiom for streaming over an array. String input = "dog,cat,bird"; Stream<String> stream = Arrays.stream(input.split( "," )); stream.forEach(System.out::println); Stream.of/String.split Stream.of i...
Split
40,932,813
93
In JavaScript this is how we can split a string at every 3-rd character "foobarspam".match(/.{1,3}/g) I am trying to figure out how to do this in Java. Any pointers?
You could do it like this: String s = "1234567890"; System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)"))); which produces: [123, 456, 789, 0] The regex (?<=\G...) matches an empty string that has the last match (\G) followed by three characters (...) before it ((?<= ))
Split
2,297,347
93
I would like to split a String but I would like to keep white space like: var str = "my car is red"; var stringArray []; stringArray [0] = "my"; stringArray [1] = " "; stringArray [2] = "car"; stringArray [3] = " "; stringArray [4] = "is"; stringArray [5] = " "; stringArray [6] = "red"; How I can proceed to do that?...
Using regex: var str = "my car is red"; var stringArray = str.split(/(\s+)/); console.log(stringArray); // ["my", " ", "car", " ", "is", " ", "red"] \s matches any character that is a whitespace, adding the plus makes it greedy, matching a group starting with characters and ending with whitespace, and the next gro...
Split
26,425,637
92
I have comma separated data in a column: Column ------- a,b,c,d I want to split the comma separated data into multiple columns to get this output: Column1 Column2 Column3 Column4 ------- ------- ------- ------- a b c d How can this be achieved?
split_part() does what you want in one step: SELECT split_part(col, ',', 1) AS col1 , split_part(col, ',', 2) AS col2 , split_part(col, ',', 3) AS col3 , split_part(col, ',', 4) AS col4 FROM tbl; Add as many lines as you have items in col (the possible maximum). Columns exceeding data items will be em...
Split
8,584,967
92
I'd like to split strings like these 'foofo21' 'bar432' 'foobar12345' into ['foofo', '21'] ['bar', '432'] ['foobar', '12345'] Does somebody know an easy and simple way to do this in python?
I would approach this by using re.match in the following way: import re match = re.match(r"([a-z]+)([0-9]+)", 'foofo21', re.I) if match: items = match.groups() print(items) >> ("foofo", "21")
Split
430,079
91
I have a string that looks like this: "Name1=Value1;Name2=Value2;Name3=Value3" Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this: dict = { "Name1": "Value1", "Name2": "Value2", "Name3": "Value3" } I have looked through the modules...
There's no builtin, but you can accomplish this fairly simply with a generator comprehension: s= "Name1=Value1;Name2=Value2;Name3=Value3" dict(item.split("=") for item in s.split(";")) [Edit] From your update you indicate you may need to handle quoting. This does complicate things, depending on what the exact format...
Split
186,857
91
Let's say I need to split string like this: Input string: "My. name. is Bond._James Bond!" Output 2 strings: "My. name. is Bond" "_James Bond!" I tried this: int lastDotIndex = inputString.LastIndexOf(".", System.StringComparison.Ordinal); string firstPart = inputString.Remove(lastDotIndex); string secondPart= inputS...
Updated Answer (for C# 8 and above) C# 8 introduced a new feature called ranges and indices, which offer a more concise syntax for working with strings. string s = "My. name. is Bond._James Bond!"; int idx = s.LastIndexOf('.'); if (idx != -1) { Console.WriteLine(s[..idx]); // "My. name. is Bond" Console.WriteL...
Split
21,733,756
90
I have a string "4,6,8\n9,4" I want to split this based on ,and \n Output array should be 4 6 8 9 4 Edit : Now i am reading string from console , when i enter a string as above in console , in the code behind i get as "4,6,8\\n9,4" . Now that i want to split using "," and "\\n" . How can i change the expression ?
Use string.Split(char []) string strings = "4,6,8\n9,4"; string [] split = strings .Split(new Char [] {',' , '\n' }); EDIT Try following if you get any unnecessary empty items. String.Split Method (String[], StringSplitOptions) string [] split = strings .Split(new Char [] {',' , '\n' }, ...
Split
7,605,785
89
Okay, here is my code with details of what I have tried to do: var str = "Hello m|sss sss|mmm ss"; //Now I separate them by "|" var str1 = str.split("|"); //Now I want to get the first word of every split-ed sting parts: for (var i = 0; i < codelines.length; i++) { //What to do here to get the first word of every s...
Use regular expression var totalWords = "foo love bar very much."; var firstWord = totalWords.replace(/ .*/,''); $('body').append(firstWord); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Split
18,558,417
88
I want to remove square brackets from a string, but I don't know how. String str = "[Chrissman-@1]"; str = replaceAll("\\[\\]", ""); String[] temp = str.split("-@"); System.out.println("Nickname: " + temp[0] + " | Power: " + temp[1]); But my result is: [Chrissman | 1] The square brackets doesn't get removed. I tried ...
The replaceAll method is attempting to match the String literal [] which does not exist within the String try replacing these items separately. String str = "[Chrissman-@1]"; str = str.replaceAll("\\[", "").replaceAll("\\]","");
Split
14,442,162
88
Suppose I have a table like this: subject flag this is a test 2 subject is of type text, and flag is of type int. I would like to transform this table to something like this in Postgres: token flag this 2 is 2 a 2 test 2 Is there an easy way to do this?
Use a LATERAL join - with string_to_table() in Postgres 14+. Minimal form: SELECT token, flag FROM tbl, string_to_table(subject, ' ') token WHERE flag = 2; The comma in the FROM list is (almost) equivalent to CROSS JOIN, LATERAL is automatically assumed for set-returning functions (SRF) in the FROM list. Why "almos...
Split
29,419,993
86
I want to split a string by whitespaces, , and ' using a single ruby command. word.split will split by white spaces; word.split(",") will split by ,; word.split("\'") will split by '. How to do all three at once?
word = "Now is the,time for'all good people" word.split(/[\s,']/) => ["Now", "is", "the", "time", "for", "all", "good", "people"]
Split
19,509,307
86
I have this code : stringCutted = myString.Split("/"). // ??? and I'd like to store in stringCutted the last element of the string[] after the split, directly, quickly, without storing the splitted array in a variable and access to that element with array[array.length]. Is this possible in C#?
If you're using .NET 3.5 or higher, it's easy using LINQ to Objects: stringCutted = myString.Split('/').Last(); Note that Last() (without a predicate) is optimized for the case where the source implements IList<T> (as a single-dimensional array does) so this won't iterate over the whole array to find the last element....
Split
7,256,873
86
String is ex="test1, test2, test3, test4, test5" when I use ex.split(",").first it returns "test1" Now I want to get the remaining items, i.e. `"test2, test3, test4, test5". If I use ex.split(",").last it returns only "test5" How to get all the remaining items skipping first one?
Try this: first, *rest = ex.split(/, /) Now first will be the first value, rest will be the rest of the array.
Split
1,333,347
86
I'm looking for an equivalent to sscanf() in Python. I want to parse /proc/net/* files, in C I could do something like this: int matches = sscanf( buffer, "%*d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %*X %*X:%*X %*X:%*X %*X %*d %*d %ld %*512s\n", local_addr, &local_port, rem_addr, &rem_port, &inode...
There is also the parse module. parse() is designed to be the opposite of format() (the newer string formatting function in Python 2.6 and higher). >>> from parse import parse >>> parse('{} fish', '1') >>> parse('{} fish', '1 fish') <Result ('1',) {}> >>> parse('{} fish', '2 fish') <Result ('2',) {}> >>> parse('{} fish...
Split
2,175,080
84
I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split. For instance: >>> c = "help, me" >>> print c.split() ['help,', 'me'] What I really want the list to look like is: ['help', ',', 'me'] So, I want the string split at whitespace with the punctuation spl...
This is more or less the way to do it: >>> import re >>> re.findall(r"[\w']+|[.,!?;]", "Hello, I'm a string!") ['Hello', ',', "I'm", 'a', 'string', '!'] The trick is, not to think about where to split the string, but what to include in the tokens. Caveats: The underscore (_) is considered an inner-word character. Rep...
Split
367,155
82
How do I split a string by . delimiter in PHP? For example, if I have the string "a.b", how do I get "a"?
explode does the job: $parts = explode('.', $string); You can also directly fetch parts of the result into variables: list($part1, $part2) = explode('.', $string);
Split
5,159,086
80
I have a string such as: "0123456789" And I need to split each character into an array. I, for the hell of it, tried: explode('', '123545789'); But it gave me the obvious: Warning: No delimiter defined in explode) .. How would I come across this? I can't see any method off hand, especially just a function.
$array = str_split("0123456789bcdfghjkmnpqrstvwxyz"); str_split takes an optional 2nd param, the chunk length (default 1), so you can do things like: $array = str_split("aabbccdd", 2); // $array[0] = aa // $array[1] = bb // $array[2] = cc etc ... You can also get at parts of your string by treating it as an array: ...
Split
2,170,320
80
Suppose I have a string "AAA BBB CCC DDD EEE FFF". How can I split the string and retrieve the nth substring, in a batch file? The equivalent in C# would be "AAA BBB CCC DDD EEE FFF".Split()[n]
Three possible solutions to iterate through the words of the string: Version 1: @echo off & setlocal set s=AAA BBB CCC DDD EEE FFF for %%a in (%s%) do echo %%a Version 2: @echo off & setlocal set s=AAA BBB CCC DDD EEE FFF set t=%s% :loop for /f "tokens=1*" %%a in ("%t%") do ( echo %%a set t=%%b ) if defined t...
Split
1,707,058
80
In Perl I can do: my ($x, $y) = split /:/, $str; And it will work whether or not the string contains the pattern. In Python, however this won't work: a, b = "foo".split(":") # ValueError: not enough values to unpack What's the canonical way to prevent errors in such cases?
If you're splitting into just two parts (like in your example) you can use str.partition() to get a guaranteed argument unpacking size of 3: >>> a, sep, b = 'foo'.partition(':') >>> a, sep, b ('foo', '', '') str.partition() always returns a 3-tuple, whether the separator is found or not. Another alternative for Pytho...
Split
38,149,470
79
I need to split a number into even parts for example: 32427237 needs to become 324 272 37 103092501 needs to become 103 092 501 How does one go about splitting it and handling odd number situations such as a split resulting in these parts e.g. 123 456 789 0?
If you have to do that in many places in your code you can create a fancy extension method: static class StringExtensions { public static IEnumerable<String> SplitInParts(this String s, Int32 partLength) { if (s == null) throw new ArgumentNullException(nameof(s)); if (partLength <= 0) throw new A...
Split
4,133,377
77
I want to something as simple as turning "this is a test" into new string[] {"t","h","i","s"," ","i","s"," ","a"," ","t","e","s","t"} Would I really have to do something like test = "this is a test".Select(x => x.ToString()).ToArray(); edit: To clarify, I don't want a char array, ideally I want an array of string. I...
I believe this is what you're looking for: char[] characters = "this is a test".ToCharArray();
Split
9,846,948
76
How can I split a string without removing the delimiters? Let's say I have a string: var string = "abcdeabcde"; When I do var newstring = string.split("d"), I get something like this: ["abc","eabc","e"] But I want to get this: ["abc","d","eabc","d","e"] When I tried to do my "split2" function, I got all entangled in sp...
Try: "abcdeabcde".split(/(d)/);
Split
4,514,144
76
My program reads a line from a file. This line contains comma-separated text like: 123,test,444,"don't split, this",more test,1 I would like the result of a split to be this: 123 test 444 "don't split, this" more test 1 If I use the String.split(","), I would get this: 123 test 444 "don't split this" more test 1 In...
You can try out this regex: str.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); This splits the string on , that is followed by an even number of double quotes. In other words, it splits on comma outside the double quotes. This will work provided you have balanced quotes in your string. Explanation: , // Split o...
Split
18,893,390
75
I need to split/divide up a continuous variable into 3 equal sized groups. Example data frame: das <- data.frame(anim = 1:15, wt = c(181,179,180.5,201,201.5,245,246.4, 189.3,301,354,369,205,199,394,231.3)) After being cut up (according to the value of wt), I would need to hav...
Or see cut_number from the ggplot2 package, e.g. das$wt_2 <- as.numeric(cut_number(das$wt,3)) Note that cut(...,3) divides the range of the original data into three ranges of equal lengths; it doesn't necessarily result in the same number of observations per group if the data are unevenly distributed (you can replicat...
Split
6,104,836
74
Our application is mining names from people using Twitter to login. Twitter is providing full names in a single string. Examples 1. "Froederick Frankenstien" 2. "Ludwig Van Beethoven" 3. "Anne Frank" I'd like to split the string into only two vars (first and last) based on the first " " (space) found. Example Firs...
String#split takes a second argument, the limit. str.split(' ', 2) should do the trick.
Split
5,253,439
74
I am trying to print the last part of a string before a certain character. I'm not quite sure whether to use the string .split() method or string slicing or maybe something else. Here is some code that doesn't work but I think shows the logic: x = 'http://test.com/lalala-134' print x['-':0] # beginning at the e...
You are looking for str.rsplit(), with a limit: print x.rsplit('-', 1)[0] .rsplit() searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once. Another option is to use str.rpartition(), which will only ever split just once: print x.rpartitio...
Split
15,851,568
73
I have an array with a list of objects. I want to split this array at one particular index, say 4 (this in real is a variable). I want to store the second part of the split array into another array. Might be simple, but I am unable to think of a nice way to do this.
Use slice, as such: var ar = [1,2,3,4,5,6]; var p1 = ar.slice(0,4); console.log({p1}); var p2 = ar.slice(4); console.log({p2});
Split
6,872,630
72
I'm using the boost::split method to split a string as this: I first make sure to include the correct header to have access to boost::split: #include <boost/algorithm/string.hpp> then: vector<string> strs; boost::split(strs,line,boost::is_any_of("\t")); and the line is like "test test2 test3" This is how I consu...
The problem is somewhere else in your code, because this works: string line("test\ttest2\ttest3"); vector<string> strs; boost::split(strs,line,boost::is_any_of("\t")); cout << "* size of the vector: " << strs.size() << endl; for (size_t i = 0; i < strs.size(); i++) cout << strs[i] << endl; and testing your ap...
Split
5,734,304
72
I have a comma separated file with many lines similar to one below. Sachin,,M,"Maths,Science,English",Need to improve in these subjects. Quotes is used to escape the delimiter comma used to represent multiple values. Now how do I split the above value on the comma delimiter using String.split() if at all its possible...
public static void main(String[] args) { String s = "Sachin,,M,\"Maths,Science,English\",Need to improve in these subjects."; String[] splitted = s.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); System.out.println(Arrays.toString(splitted)); } Output: [Sachin, , M, "Maths,Science,English", Need to improve in th...
Split
15,738,918
71
I'm trying to help out a coworker who accidentally created one feature branch from another feature branch, rather than creating the second one from master. Here is essentially what we have now… Master ---A---B---C \ Foo E---F---F---H \ ...
For a more general answer that will help us understand things a bit better than just "run this command", we need a larger example. So, let's pretend you're actually in this situation: ---A---B---C <= Master \ E---F---F---H <= Foo \ J---K---L-...
Split
12,355,904
71
I am making a method so your password needs at least one captial and one symbol or number. I was thinking of splitting the string in to lose chars and then use preggmatch to count if it contains one capital and symbol/number. however i did something like this in action script but can't figure out how this is called in ...
you can convert a string to array with str_split and use foreach $chars = str_split($str); foreach($chars as $char){ // your code }
Split
1,293,950
70
What's the best way to slice the last word from a block of text? I can think of Split it to a list (by spaces) and removing the last item, then reconcatenating the list. Use a regular expression to replace the last word. I'm currently taking approach #1, but I don't know how to concatenate the list... content = con...
Actually you don't need to split all words. You can split your text by last space symbol into two parts using rsplit. Example: >>> text = 'Python: Cut off the last word of a sentence?' >>> text.rsplit(' ', 1)[0] 'Python: Cut off the last word of a' rsplit is a shorthand for "reverse split", and unlike regular split wo...
Split
6,266,727
69
I think in Python 3 I'll be able to do: first, *rest = l which is exactly what I want, but I'm using 2.6. For now I'm doing: first = l[0] rest = l[1:] This is fine, but I was just wondering if there's something more elegant.
first, rest = l[0], l[1:] Basically the same, except that it's a oneliner. Tuple assigment rocks. This is a bit longer and less obvious, but generalized for all iterables (instead of being restricted to sliceables): i = iter(l) first = next(i) # i.next() in older versions rest = list(i)
Split
3,513,947
69
I have a string in the following format: string1:string2:string3:string4:string5 I'm trying to use sed to split the string on : and print each sub-string on a new line. Here is what I'm doing: cat ~/Desktop/myfile.txt | sed s/:/\\n/ This prints: string1 string2:string3:string4:string5 How can I get it to split on ea...
To split a string with a delimiter with GNU sed you say: sed 's/delimiter/\n/g' # GNU sed For example, to split using : as a delimiter: $ sed 's/:/\n/g' <<< "he:llo:you" he llo you Or with a non-GNU sed: $ sed $'s/:/\\\n/g' <<< "he:llo:you" he llo you In this particular case, you missed the g after the substitu...
Split
18,234,378
68
To make things simple: string streamR = sr.ReadLine(); // sr.Readline results in: // one "two two" I want to be able to save them as two different strings, remove all spaces EXCEPT for the spaces found between quotation marks. Therefore, what I need is: string ...
string input = "one \"two two\" three \"four four\" five six"; var parts = Regex.Matches(input, @"[\""].+?[\""]|[^ ]+") .Cast<Match>() .Select(m => m.Value) .ToList();
Split
14,655,023
67
First I set a variable, and set it to empty: var str = ""; Then I split it through "&": var strs = str.split('&'); In the end, I show strs's length: alert( strs.length); It alert "1". But I assign nothing to the 'str' variable. Why does it still have a length, should't it be zero?
From the MDC doc center: Note: When the string is empty, split returns an array containing one empty string, rather than an empty array. Read the full docs here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split In other words, this is by design, and not an error :)
Split
5,164,883
66
Given a character string test_1<-"abc def,ghi klm" test_2<-"abc, def ghi klm" I wish to obtain "abc" "def" "ghi" However, using strsplit, one must know the order of the splitting values in the string, as strsplit uses the first value to do the first split, the second to do the second... and then recycles. But this do...
Actually strsplit uses grep patterns as well. (A comma is a regex metacharacter whereas a space is not; hence the need for double escaping the commas in the pattern argument. So the use of "\\s" would be more to improve readability than of necessity): > strsplit(test_1, "\\, |\\,| ") # three possibilities OR'ed [[1]] ...
Split
10,738,729
66