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 like the GitHub Mac app, which I use with my GitHub account. I have joined a GitLab project and I was wondering whether I can use the GitHub app with a GitLab repository. I found a post that discuss that the Windows GitHub app works with GitLab and one that show how to add a repo. Both these posts gave me hope that the GitHub Mac App would work with GitLab. I also see that you can use BitBucket with the GitHub Mac app, but I don't understand whether and how to link a GitLab repository to my GitHub Mac app. Many thanks!
With the mac app, you have to do the clone on the command line. Open a terminal, navigate to directory that you want to be the parent of your local repo, and git clone the repo. As soon as this is done, go into the github mac app and Go to File->Add Local Repo You can then add the repo directory file picker, and from there you should be set. The first time you push back to origin through the app, it will ask for your gitlab username and password, and optionally store them in the keychain.
GitLab
25,548,236
21
I have a private repository on a GitLab server and using the SSH I can pull a project using git clone. But I want to run a script on linux command line directly from the server (more specific, a Drupal / Drush .make file) I tried to run it using the raw file: drush make http://server.com/user/project/raw/master/file.make (for the convenience of non Drupal users let’s say) curl http://server.com/user/project/raw/master/file.make Without success. Of course, it returns me the login page. Is it possible?
With Chris's valuable help, here is how you can run a script (drupal .make file in my case) from a GitLab server. (Probably it works for GitHub but I didn't test it. Maybe the syntax will be a bit different). (Of course this works for any type of script) It can be done using the authentication tokens. Here is the documentation of the GitLab's API and here is the GitHub's API For convenient I will use the https://gitlab.com as the example server. Go to https://gitlab.com/profile/account and find your "Private token" Then print the list of the projects and find the id of your project you are looking for curl https://gitlab.com/api/v3/projects?private_token=<your_private_token> or go there with your browser (a json viewer will help a lot) Then print the list of the files that are on this project and find the id of your file you are looking for curl https://gitlab.com/api/v3/projects/<project_id>/repository/tree?private_token=<your_private_token> Finally get / run the file! curl https://gitlab.com/api/v3/projects/<project_id>/repository/raw_blobs/<file_id>?private_token=<your_private_token> In case you want to run the script (drupal .make) drush make https://gitlab.com/api/v3/projects/<project_id>/repository/raw_blobs/<file_id>?private_token=<your_private_token> <drupal_folder> (If you are here looking for a workflow to integrate GitLab with Aegir .make platforms without using tokens (maybe SSH?) please make a thread and paste here the link.) EDIT You can get the file without the project_id by using the encoded project name. For example the my-user-name/my-project will become: my-user-name%2Fmy-project
GitLab
24,207,644
21
In my gitlab project there are 3 main branches: develop, stage and master. Each time when updated code is pushed to develop branch, I have to merge it to stage branch and then merge it again to master branch manually. This doesn't seem efficient. Is there any way to merge branches automatically when there is no conflict? Furthermore, it is possible to use a file named "gitlab-ci.yml " for auto merge something like # merge develop branch to stage branch merge-to-stage: only: - develop script: - merge (develop) to (stage) << something like this # merge stage branch to master branch when the job above is completed stage-to-master: only: - stage script: - merge (stage) to (master) << something like this Please give me your kind advice.
There is no way to automate this within GitLab. But you can automate this using GitLab CI. Be aware that the GitLab CI Runners are independent from GitLab and just get a local copy of a Git repository. So your CI script wont be able to run git merge & git push out of the box. What you need to do is set up a SSH connection from the GitLab CI Runner to your GitLab instance. Use a before script for this. There are several answers on StackOverflow and a good blog post on GitLab how to achive this. merge-job: before_script: - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )' - eval $(ssh-agent -s) - ssh-add <(echo "$GIT_SSH_PRIV_KEY") - mkdir -p ~/.ssh - cat gitlab-known-hosts >> ~/.ssh/known_hosts Then run your Git commands like git merge. Then push. merge-to-stage: only: - develop script: # If this is the last job you can stay here, otherwise better clone the repo into a working directory # git clone <URL> <working-directory> && cd <working directory> - git checkout stage - git merge develop - git push origin stage The schema of your next pipeline jobs depend on what you mean with when there is no conflict. In your example code you merge all stage branches into the higher branch (feature to develop, develop to stage, stage to main). If so, then you should make sure that there is a merge job for each stage and these merge jobs are placed at the end of the pipeline. Then the merge won't happen if there was a CI error or a merge conflict before. Alternatively you could also have just one job, which uses GitLabs push options. With these options you may create merge requests for your feature branch which are automatically merged and closed when a CI Pipeline is successful. This strategy would only merge your feature branch changes and not the whole stage branches. merge-to-stage-branches: only: - <feature branch names that are no WIP anymore> script: # <scripts to merge feature into develop> git push -o merge_request.create -o merge_request.target=develop -o merge_request.merge_when_pipeline_succeeds # <repeat merge for each stage branch> # <repeat push for each stage branch>
GitLab
67,516,773
20
We're working on a few project hosted on Gitlab and it would be really convenient for us to have a bot to automate some issues handling. E.g.: automatically close issues that have been tagged as 'waiting answer from client' more than 20 days ago I can't find any guide nor tutorial on how doing this, I don't even know if it could be done entirely in GitHub or do I need to create my bot from an external service.
Depending on exactly what you want to do, there are a number of options. I've used all of these approaches for different tasks: If you want to write something from scratch, and have full control over every aspect of the bot's workflow, the python-gitlab library is very nice. If you want something that mainly responds to events gidgetlab is great for this. If you want something that automates a merge-request workflow, you might just want to run an instance of marge-bot. If you want something more sophisticated, and you don't want to start from scratch, it might be worth forking some of GitLab's internal bot repos. The triage-ops repo automates triage on labels and MRs, using the gitlab-triage gem. The async-retrospectives repo automates the generation of end-of-sprint information, which is then posted as an issue. There's a blog post you can read about it. In your case, if it's mostly a matter of closing stale issues, etc. I would be inclined to fork triage-ops, which already has policies for this already. The policies themselves are written as YAML files, and run as scheduled GitLab pipelines, so it's pretty easy to get started, you just have to specialise the policies to suit your workflow.
GitLab
62,672,281
20
I currently have two jobs in my CI file which are nearly identical. The first is for manually compiling a release build from any git branch. deploy_internal: stage: deploy script: ....<deploy code> when: manual The second is to be used by the scheduler to release a daily build from develop branch. scheduled_deploy_internal: stage: deploy script: ....<deploy code from deploy_internal copy/pasted> only: variables: - $MY_DEPLOY_INTERNAL != null This feels wrong to have all that deploy code repeated in two places. It gets worse. There are also deploy_external, deploy_release, and scheduled variants. My question: Is there a way that I can combine deploy_internal and scheduled_deploy_internal such that the manual/scheduled behaviour is retained (DRY basically)? Alternatively: Is there is a better way that I should structure my jobs? Edit: Original title: Deploy job. Execute manually except when scheduled
You can use YAML anchors and aliases to reuse the script. deploy_internal: stage: deploy script: - &deployment_scripts | echo "Deployment Started" bash command 1 bash command 2 when: manual scheduled_deploy_internal: stage: deploy script: - *deployment_scripts only: variables: - $MY_DEPLOY_INTERNAL != null Or you can use extends keyword. .deployment_script: script: - echo "Deployment started" - bash command 1 - bash command 2 deploy_internal: extends: .deployment_script stage: deploy when: manual scheduled_deploy_internal: extends: .deployment_script stage: deploy only: variables: - $MY_DEPLOY_INTERNAL != null
GitLab
61,357,650
20
I know that there are already countless questions in this direction, but unfortunately I was not able to find the right answer yet. If a post already exists, please just share the link here. I have several gitlab CI / CD pipelines. The first pipeline uses Terraform to build the complete infrastructure for an ECS cluster based on Fargate. The second / third pipeline creates nightly builds of the frontend and the backend and pushes the Docker Image with the tag "latest" into the ECR of the (staging) AWS account. What I now want to achieve is that the corresponding ECS tasks are redeloyed so that the latest Docker images are used. I actually thought that there is a way to do this via CloudWatch Events or whatsoever, but I don't find a really good starting point here. A workaround would be to install the AWS CLI in the CI / CD pipeline and then do a service update with "force new deployment". But that doesn't seem very elegant to me. Is there any better way here? Conditions: The solution must be fully automated (either in AWS or in gitlab CI / CD) Switching to AWS CodePipeline is out of discussion Ideally as close as possible to AWS standards. I would like to avoid extensive lambda functions that perform numerous actions due to their maintainability. Thanks a lot!
Ok, for everybody who is interested in an answer. I solved it that way: I execute the following AWS CLI command in the CICD pipeline aws ecs update-service --cluster <<cluster-name>> --service <<service-name>> --force-new-deployment --region <<region>> Not the solution I was looking for but it works.
GitLab
60,325,351
20
Is there any way in GitLab UI to reject a merge request because code has issue? If not what is the right way to track this?
I agree with Phil Lucks. In my opinion gitlab is missing functionality. A merge request is a request and as such should be able to be rejected/denied. The following thread gives insight into the thought process that was going on with Closing a request versus denying one. https://gitlab.com/gitlab-org/gitlab-foss/-/issues/23355
GitLab
57,577,180
20
I'm trying to register a new runner on gitlab following these steps : https://docs.gitlab.com/runner/register/index.html But when I enter the url, token and tags, an error message pops-up saying: ERROR: Registering runner... failed runner=CS-XXX status=couldn't execute POST against https://example.com/api/v4/runners: Post https://example.com/api/v4/runners: x509: certificate signed by unknown authority I'm working on a new server and already installed the gitlab-runner.
you need to use tls-ca-file option during registration or in the configuration of your runner. Here is an example of non-interactive registration with tls-ca-file option : gitlab-runner register \ --non-interactive \ --registration-token YOUTOKEN \ --url https://example.com/ \ --tls-ca-file /path/to/your/ca.crt Other way, you can refer the tls-ca-file option in your config.toml under the [[runners]] section more info : https://docs.gitlab.com/runner/configuration/tls-self-signed.html
GitLab
55,622,960
20
Is there a way to restrict merging from a specific branch into other branches? Allow me to explain: I have a 'testing' branch and a 'master' branch in Gitlab. The team creates feature branches, merges them into 'testing' for approval and then merge the feature branch into 'master' once approved. Sometimes, it can take months to get approval of some features, and therefore code is sat in the 'testing' branch for a while. Meanwhile, another feature branch may try to merge into 'testing' and conflicts will arise. This is expected, however, we are only human, and occasionally someone may accidentally merge 'testing' into their feature branch when handling the conflict, which is obviously wrong. Instead, we should switch to 'testing' and merge our feature branch into 'testing' thus managing the conflict within the testing branch. Any advise is appreciated.
To begin, be sure your needs is very normal and traditional. The answer is ... Yes. How to prevent merging from a branch to another, setting up a server Git Hook These are some useful links: Git Hook explanations in Official Git Book GitLab server-side Hook explanations An example with a Git Hook written in Ruby to prevent merging 'staging' branch to 'master' one To help you (and for fun ^^), I wrote a dedicated hook in Python to reach your specific needs (you just need to adapt FORBIDDEN_SOURCE_BRANCH and FORBIDDEN_IF_NOT_DEST_BRANCH if you want to work with some other branches). #!/bin/python ## ## Author: Bertrand Benoit <mailto:[email protected]> ## Description: Git Hook (server-side) allowing to prevent merge from some branches to anothers ## Version: 0.9 import sys, subprocess, re FORBIDDEN_SOURCE_BRANCH='testing' FORBIDDEN_IF_NOT_DEST_BRANCH='master' # Considers only merge commit. if not (len(sys.argv) >=2 and sys.argv[2] == 'merge'): sys.exit(0) # Defines which is the source branch. with open(sys.argv[1], 'r') as f: mergeMessage=f.readline() mergeBranchExtract=re.compile("Merge branch '([^']*)'.*$").search(mergeMessage) if not mergeBranchExtract: print('Unable to extract branch to merge from message: ', mergeMessage) sys.exit(0) # Ensures normal merge as failback # Checks if the merge (source) branch is one of those to check. mergeBranch=mergeBranchExtract.group(1) if mergeBranch != FORBIDDEN_SOURCE_BRANCH: sys.exit(0) # It is NOT the forbidden source branch, so keeps on normal merge # Defines which is the current branch. currentBranchFullName=subprocess.check_output(['git', 'symbolic-ref', 'HEAD']) currentBranchExtract=re.compile("^.*/([^/]*)\n$").search(currentBranchFullName) if not currentBranchExtract: print('Unable to extract current branch from: ', currentBranchFullName) sys.exit(1) # Ensures normal merge as failback # Checks if the current (destination) branch is one of those to check. currentBranch=currentBranchExtract.group(1) if currentBranch != FORBIDDEN_IF_NOT_DEST_BRANCH: print("FORBIDDEN: Merging from '" + mergeBranch + "' to '" + currentBranch + "' is NOT allowed. Contact your administrator. Now, you should use git merge --abort and keep on your work.") sys.exit(1) # This is exactly the situation which is forbidden # All is OK, so keeps on normal merge sys.exit(0) To share all this work, I created a new Gitlab repository, in which I'll add further hooks when needed :) For information, you can also setup protected branches to keep them safe from some users This is the complete documentation about that. Let me know if you need further help.
GitLab
53,115,040
20
I got following error in the Gitlab: Sorry, we cannot cherry-pick this merge request automatically. This merge request may already have been cherry picked, or a more recent commit may have updated some of its content. I have branch X from which I have to cherry pick commits to the branch Y. Maybe I have already done cherry pick, which is after this failed cherry pick. I have about 10 cherry picks to do. What I should to do? I was thinking if I create new branch Z (before Y) and try add cherry picks in the right order. Maybe that would be solution? What you think?
I did the cherry picks so that I picked up the merge request commits with commands like this: git cherry-pick -m 1 <merge request commit hash 1> git cherry-pick -m 1 <merge request commit hash 2> ... git cherry-pick -m 1 <merge request commit hash N> The -m 1 parameter is a little bit cryptical in the documentation, but I have done a lot of cherry picks and this is working.
GitLab
49,670,336
20
I'm wondering what the -T option in the following command does, cannot see this option in the manual somehow: $ ssh -T [email protected] Welcome to GitLab, Simeon ! Could somebody explain?
I explained before what TTY was: a text terminal is needed when you open an interactive session to a remote server. But: in the context of a remote Git repository hosting server (GitHub, Gitlab, BitBucket, ...), no remote server will ever allow you to open an interactive session (for security reason) Then only reason why you would still do an ssh -T [email protected] would be to test if you are correctly authenticated, and the session would immediately end with: Hi username! You've successfully authenticated, but GitHub does not provide shell access. Since no tty is needed for that test, you should use the -T option when making this test.
GitLab
47,245,185
20
I have a GitLab pipeline that I want to: Build a Java app Test using docker-compose Push to my Docker repository The primary issue I'm having is that this works: services: - docker:dind docker_test: stage: docker_test image: docker:latest script: - docker version The output is printed as expected: > gitlab-ci-multi-runner exec docker --docker-privileged docker_test ... $ docker version Client: Version: 17.06.0-ce ... Server: Version: 17.06.0-ce ... Build succeeded While this does not (installation steps for docker-ce omitted): services: - docker:dind docker_test: stage: docker_test image: ubuntu:latest << note change script: - docker version It fails with: $ docker version Client: Version: 17.06.0-ce API version: 1.30 Go version: go1.8.3 Git commit: 02c1d87 Built: Fri Jun 23 21:23:31 2017 OS/Arch: linux/amd64 Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? ERROR: Build failed: exit code 1 FATAL: exit code 1 How do I make my ubuntu image (or whatever image is going to build my project) connect to the linked Docker-in-Docker service? What is docker:latest doing that I'm not? I've read up on the GitLab services documentation, but it only makes sense to me from a hostname perspective. (If you have a mysql service, you can connect over mysql:3306.) Edit: Updating the command to echo $DOCKER_HOST, I see in the docker:latest image: $ echo $DOCKER_HOST tcp://docker:2375 And in the ubuntu:latest image I see: $ echo $DOCKER_HOST (nothing - but SO doesn't let me add a blank code line)
As the information you've added, I hope that this does work: services: - docker:dind docker_test: stage: docker_test image: ubuntu:latest variables: DOCKER_HOST: "tcp://docker:2375" script: - docker version Alternatively: services: - docker:dind docker_test: stage: docker_test image: ubuntu:latest script: - export DOCKER_HOST=tcp://docker:2375 - docker version It seems that Gitlab does not set the DOCKER_HOST variable for custom images.
GitLab
45,316,098
20
We are working on Gitlab and each time I start merging a branch, Gitlab makes the option "Remove source branch" checked by default (which is -I think- dangerous). As I don't guarantee that me or a colleague can forget to uncheck this option and make the mistake of removing the branch, I'm wondering if there is a solution to make it unchecked by default (which is -I think- will be more secure)?
Go to Settings > General > Merge requests Uncheck the box: Enable 'Delete source branch' option by default This option is only available for the maintaniner role.
GitLab
45,055,731
20
We are using Gitlab (the gitlab.com free version). My colleague is creating merge requests and we are merging from one branch (development) into another (master). When my colleague merges into master the MR is shown as Merged. I am then running some tests on the merged branch (not done automatically through GL currently) and when happy with the merge I am wanting to close the merge request. However I do not have any option to close it - I do not have a close button and if I type /close in the comments it does not do anything. Neither my colleague or myself are able to close the MRs. We both have Master status and have tried changing various MR project settings but to no avail. PLease can anyone help?
In Gitlab, the merged status means the relevant commits have been merged and no action is needed. A closed merge request is one that has been put aside or considered irrelevant. It is therefore not merged into the code base. Therefore, you only merge MRs when you're happy with the changes and close them if you think the changes are not worthy of being integrated into the code base ever. A typical workflow would be the following: User A works on a new feature in a feature branch and pushes their work to that branch. They can open a merge request to merge their feature branch into master. User B pulls the feature branch, eventually rebasing it onto master, and runs the tests they want. If User B is happy with the changes/new feature, they can merge the MR into master (or whatever branch you merge into) The merge request will be shown as merged Of course it's better if the tests run automatically in a CI.
GitLab
43,340,029
20
I get the following error after installing gitlab.. root@Blase:~# sudo /opt/lampp/lampp start Starting XAMPP for Linux 7.0.9-1... XAMPP: Starting Apache...fail. [XAMPP: Another web server is already running.][1] XAMPP: Starting MySQL...already running. I cannot access my localhost/phpmyadmin or any projects folder as am redirected to Gitlab. I tried to view which program is using port 80 by running: "netstat -tulpn | grep --color :80" and i got the output shown in attached image. Any help guys?
I had to stop all the services, $sudo /etc/init.d/apache2 stop $sudo /etc/init.d/mysql stop $sudo /etc/init.d/proftpd stop Then I restarted the server sudo /opt/lampp/lampp restart
GitLab
40,480,843
20
I have uploaded some files to my Gitlab repository on "gitlab.com" while creating wiki for my private project. Now my questions are: Can I see list of the uploaded files? Is there any way to remove some of them? Why permission of uploaded file is public? Can I change it to private? Current version of gitlab is Enterprise Edition 8.9.4-ee.
Attached files trough the wiki editor are uploaded to /uploads/. As of GitLab version 8.9.0 you are unable to manage these files (i.e. deleting them). If you want to manage attached files yourself you can clone the wiki as repository. You can find the clone URL in Wiki -> Git Access. It should look something like this: git@<link to gitlab>:<group/user name>/<project name>.wiki.git. In the cloned repository you'll not find the /uploads/ directory, because it is located outside of the repository. Bun there you can put your images or other attachments, and link them within your wiki. The link to the image is relative to the repo root so if your image image.png is in the root folder you can link it with markdown like this![Image title](image.png). Permission wise these files will only be visible to Users which have at least Guest access to your project, even if they have a direct link.
GitLab
38,228,508
20
How do I uninstall gitlab? I deleted the /home/gitlab directory but it still opens up when I browse to my hostname.
This worked on ubuntu 16.04 sudo apt-get remove gitlab-ce sudo rm -rf /var/opt/gitlab --kill all process live sudo pkill -f gitlab -- Remove paths sudo rm -rf /opt/gitlab sudo rm -rf /etc/gitlab rm -rf /var/opt/gitlab
GitLab
35,796,485
20
I've been just handed the access to a VPS at work, and I thought of installing GitLab CE on it for better teamwork organisation. Does the GitLab CE license allow me to do so?
Yup, it is under the MIT license. There is nothing preventing you from using it for commercial projects. The other editions simply add more features and support.
GitLab
30,937,953
20
I stuck here now for like 2 Days a week. I've got a CentOs machine with Gitlab4 and gitolite. Everything worked fine for weeks, but suddenly last weekend something strange happend quite all binaries disappeared from the mashine ( like yum, python, ruby, mysql ect. ) i've really no clue how that can happn... After hours of reinstalling and compiling gitlab was working again. But i cant get the ssh keys between the gitlab and git user working. I already deleted and recreated the git user, set again all permissions, recreated the ssh keys, reinstalld gitolite ect. But nothing worked i keep getting the same error. git user .ssh folder -rwx------ 1 git git 557 Mar 27 16:46 authorized_keys gitlab user .ssh folder -rw------- 1 gitlab gitlab 1671 Mar 27 16:45 id_rsa -rw-r--r-- 1 gitlab gitlab 406 Mar 27 16:45 id_rsa.pub -rw-r--r-- 1 gitlab gitlab 391 Mar 27 16:50 known_hosts SSH error: ssh -vvvT git@localhost OpenSSH_4.3p2, OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008 debug1: Reading configuration data /etc/ssh/ssh_config debug1: Applying options for * debug2: ssh_connect: needpriv 0 debug1: Connecting to localhost [127.0.0.1] port 22. debug1: Connection established. debug1: identity file /home/gitlab/.ssh/identity type -1 debug3: Not a RSA1 key file /home/gitlab/.ssh/id_rsa. debug2: key_type_from_name: unknown key type '-----BEGIN' debug3: key_read: missing keytype debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug2: key_type_from_name: unknown key type '-----END' debug3: key_read: missing keytype debug1: identity file /home/gitlab/.ssh/id_rsa type 1 debug1: identity file /home/gitlab/.ssh/id_dsa type -1 debug1: Remote protocol version 2.0, remote software version OpenSSH_4.3p2 debug1: match: OpenSSH_4.3p2 pat OpenSSH* debug1: Enabling compatibility mode for protocol 2.0 debug1: Local version string SSH-2.0-OpenSSH_4.3p2 debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1 debug2: kex_parse_kexinit: ssh-rsa,ssh-dss debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc,[email protected],aes128-ctr,aes192-ctr,aes256-ctr debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc,[email protected],aes128-ctr,aes192-ctr,aes256-ctr debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96 debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96 debug2: kex_parse_kexinit: none,zlib debug2: kex_parse_kexinit: none,zlib debug2: kex_parse_kexinit: debug2: kex_parse_kexinit: debug2: kex_parse_kexinit: first_kex_follows 0 debug2: kex_parse_kexinit: reserved 0 debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1 debug2: kex_parse_kexinit: ssh-rsa,ssh-dss debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc,[email protected],aes128-ctr,aes192-ctr,aes256-ctr debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc,[email protected],aes128-ctr,aes192-ctr,aes256-ctr debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96 debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96 debug2: kex_parse_kexinit: none,zlib debug2: kex_parse_kexinit: none,zlib debug2: kex_parse_kexinit: debug2: kex_parse_kexinit: debug2: kex_parse_kexinit: first_kex_follows 0 debug2: kex_parse_kexinit: reserved 0 debug2: mac_init: found hmac-md5 debug1: kex: server->client aes128-cbc hmac-md5 none debug2: mac_init: found hmac-md5 debug1: kex: client->server aes128-cbc hmac-md5 none debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP debug2: dh_gen_key: priv key bits set: 132/256 debug2: bits set: 502/1024 debug1: SSH2_MSG_KEX_DH_GEX_INIT sent debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY debug3: check_host_in_hostfile: filename /home/gitlab/.ssh/known_hosts debug3: check_host_in_hostfile: match line 1 debug1: Host 'localhost' is known and matches the RSA host key. debug1: Found key in /home/gitlab/.ssh/known_hosts:1 debug2: bits set: 505/1024 debug1: ssh_rsa_verify: signature correct debug2: kex_derive_keys debug2: set_newkeys: mode 1 debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug2: set_newkeys: mode 0 debug1: SSH2_MSG_NEWKEYS received debug1: SSH2_MSG_SERVICE_REQUEST sent debug2: service_accept: ssh-userauth debug1: SSH2_MSG_SERVICE_ACCEPT received debug2: key: /home/gitlab/.ssh/identity ((nil)) debug2: key: /home/gitlab/.ssh/id_rsa (0x848ba50) debug2: key: /home/gitlab/.ssh/id_dsa ((nil)) debug1: Authentications that can continue: publickey,password debug3: start over, passed a different list publickey,password debug3: preferred publickey,keyboard-interactive,password debug3: authmethod_lookup publickey debug3: remaining preferred: keyboard-interactive,password debug3: authmethod_is_enabled publickey debug1: Next authentication method: publickey debug1: Trying private key: /home/gitlab/.ssh/identity debug3: no such identity: /home/gitlab/.ssh/identity debug1: Offering public key: /home/gitlab/.ssh/id_rsa debug3: send_pubkey_test debug2: we sent a publickey packet, wait for reply debug1: Authentications that can continue: publickey,password debug1: Trying private key: /home/gitlab/.ssh/id_dsa debug3: no such identity: /home/gitlab/.ssh/id_dsa debug2: we did not send a packet, disable method debug3: authmethod_lookup password debug3: remaining preferred: ,password debug3: authmethod_is_enabled password debug1: Next authentication method: password The auth log gives me: Apr 2 10:19:13 venus sshd[15693]: User git not allowed because account is locked Apr 2 10:19:13 venus sshd[15693]: Failed none for illegal user git from ::ffff:127.0.0.1 port 56906 ssh2 Thanks for any Help.
You mention: Apr 2 10:19:13 venus shd[15693]: User git not allowed because account is locked Apr 2 10:19:13 venus sshd[15693]: Failed none for illegal user git from ::ffff:127.0.0.1 port 56906 ssh2 This article mentions: OpenSSH now checks for locked accounts by default. On Linux systems, locked accounts are defined as those that have !! in the password field of /etc/shadow. This is the default entry for accounts created with the useradd command. Even if you are using GSI authentication and do not need local passwords, sshd won't let the user login with this message: Too many authentication failures for username In the sshd debugging info it will indicate that the account is locked: User username not allowed because account is locked Here is some additional information from the sshd Manual: Regardless of the authentication type, the account is checked to ensure that it is accessible. An account is not accessible if it is locked, listed in DenyUsers or its group is listed in DenyGroups. The definition of a locked account is system dependant. Some platforms have their own account database (eg AIX) and some modify the passwd field ( "*LK*" on Solaris and UnixWare, "*" on HP-UX, containing "Nologin" on Tru64, a leading "*LOCKED*" on FreeBSD and a leading "!!" on Linux). If there is a requirement to disable password authentication for the account while allowing still public-key, then the passwd field should be set to something other than these values (eg "NP" or "*NP*" ). Fix: Replace !! with (for example) NP in /etc/shadow. As mentioned by jszakmeister (comments) and Yongcan-Frank-Lv (comments): sudo passwd -u git would be enough to unlock the account.
GitLab
15,664,561
20
I have a two private repositories: MyProject, MyProjetUtils. My project uses the MyProjectUtils as a submodule. My .gitsubmodules looks like this: [submodule "MyProjetUtils"] path = MyProjetUtils url = [email protected]:MyCompany/MyProjetUtils.git My .gitlab-ci.yml file looks like this: default: image: python:latest variables: GIT_SUBMODULE_STRATEGY: recursive all_test: stage: test script: - apt-get update - pip install -r requirements.txt - python tests/run_tests.py The error I'm getting during the job run: Updating/initializing submodules recursively with git depth set to 50... Submodule 'MyProjetUtils' ([email protected]:MyCompany/MyProjetUtils.git) registered for path 'MyProjetUtils' Cloning into '/builds/MyCompany/MyProject/MyProjetUtils'... error: cannot run ssh: No such file or directory fatal: unable to fork fatal: clone of '[email protected]:MyCompany/MyProjetUtils.git' into submodule path '/builds/MyCompany/MyProject/MyProjetUtils' failed Failed to clone 'MyProjetUtils'. Retry scheduled This error occur before the test stage. I've looked for answer here, and here but could not find an answer.
The first link you posted has the solution you are looking for: When your submodule is on the same GitLab server, you should use relative URLs in your .gitmodules file. Then you can clone with HTTPS in all your CI/CD jobs. You can also use SSH for all your local checkouts. Assuming that your submodules are in the same group, update your .gitmodules to use a relative URL. ie: [submodule "MyProjetUtils"] path = MyProjetUtils url = ../../MyCompany/MyProjetUtils.git May need to update ../../ to work for your groups.
GitLab
68,299,491
19
I'm currently setting up GitLab CI/CD. We use GitVersion in our project, which throws the following error: /root/.nuget/packages/gitversiontask/5.3.7/build/GitVersionTask.targets(46,9): error : InvalidOperationException: Could not find a 'develop' or 'master' branch, neither locally nor remotely. According to this blog this happens, when the CI-server does not fetch the full repository (we have both a develop and a master branch, but I'm working on a different one). For Jenkins we solved this problem by expanding the checkout stage: stage("Checkout") { gitlabCommitStatus(name: "Checkout") { // These are the normal checkout instructions cleanWs() checkout scm // This is the additional checkout to get all branches checkout([ $class: 'GitSCM', branches: [[name: 'refs/heads/'+env.BRANCH_NAME]], extensions: [[$class: 'CloneOption', noTags: false, shallow: false, depth: 0, reference: '']], userRemoteConfigs: scm.userRemoteConfigs, ]) sh "git checkout ${env.BRANCH_NAME}" sh "git reset --hard origin/${env.BRANCH_NAME}" }} I'm essentially looking for something equivalent to this for the .gitlab-ci.yml file.
By default, runners download your code with a 'fetch' rather than a 'clone' for speed's sake, but it can be configured a number of ways. If you want all jobs in your project's pipeline to be cloned rather than fetched, you can change the default in your CI Settings: If you don't want all your jobs to clone since it's slower, you can change it in your .gitlab-ci.yml for your job: my_job: stage: deploy variables: GIT_STRATEGY: clone script: - ./deploy You can read more about the GIT_STRATEGY variable here: https://docs.gitlab.com/ee/ci/runners/configure_runners.html#git-strategy Note: You can also set this variable to none, which is useful if you don't need the code but maybe an artifact created by a previous job. Using this, it won't checkout any code, but skip straight to your script.
GitLab
65,686,740
19
Operating system: Linux git version: 2.26.2 Git repo provider of my repo: gitlab Repo provider of the failing submodules: Github .gitmodules [submodule "libraries/stb"] path = libraries/stb url = https://github.com/nothings/stb.git branch = master [submodule "libraries/harfbuzz"] path = libraries/harfbuzz url = https://github.com/harfbuzz/harfbuzz.git branch = master [submodule "libraries/shaderc"] path = libraries/shaderc url = https://github.com/google/shaderc.git branch = master [submodule "libraries/freetype2"] path = libraries/freetype2 url = https://github.com/aseprite/freetype2.git branch = master [submodule "libraries/VulkanMemoryAllocator"] path = libraries/VulkanMemoryAllocator url = https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git branch = master [submodule "libraries/googletest"] path = libraries/googletest url = https://github.com/google/googletest.git branch = master [submodule "libraries/Eigen"] path = libraries/Eigen url = https://gitlab.com/libeigen/eigen.git branch = master [submodule "libraries/benchmark"] path = libraries/benchmark url = https://github.com/google/benchmark.git [submodule "libraries/rapidcheck"] path = libraries/rapidcheck url = https://github.com/emil-e/rapidcheck.git branch = master [submodule "libraries/magic_get"] path = libraries/magic_get url = https://github.com/apolukhin/magic_get.git branch = master command and output: git pull --recurse-submodules=true Fetching submodule libraries/Eigen Fetching submodule libraries/VulkanMemoryAllocator Fetching submodule libraries/benchmark Fetching submodule libraries/freetype2 Fetching submodule libraries/googletest Fetching submodule libraries/harfbuzz Could not access submodule 'libraries/magic_get' Could not access submodule 'libraries/rapidcheck' Could not access submodule 'libraries/shaderc' Could not access submodule 'libraries/stb' git submodule status: git submodule status a145e4adf5e71391d64c0ab150a8c26851cf332d libraries/Eigen (before-git-migration-159-ga145e4adf) 755fd47121ce0c77ef11818e4987790ae99c2eba libraries/VulkanMemoryAllocator (v2.1.0-334-g755fd47) d3ad0b9d11c190cb58de5fb17c3555def61fdc96 libraries/benchmark (v1.5.0-56-gd3ad0b9) fbbcf50367403a6316a013b51690071198962920 libraries/freetype2 (VER-2-10-0) dcc92d0ab6c4ce022162a23566d44f673251eee4 libraries/googletest (release-1.8.0-2331-gdcc92d0a) 89ad3c6cc520517af15174391a9725e634929107 libraries/harfbuzz (2.6.5-71-g89ad3c6c) git tree git ls-tree -r HEAD 160000 commit a145e4adf5e71391d64c0ab150a8c26851cf332d Eigen 160000 commit 755fd47121ce0c77ef11818e4987790ae99c2eba VulkanMemoryAllocator 160000 commit d3ad0b9d11c190cb58de5fb17c3555def61fdc96 benchmark 160000 commit fbbcf50367403a6316a013b51690071198962920 freetype2 160000 commit dcc92d0ab6c4ce022162a23566d44f673251eee4 googletest 160000 commit 89ad3c6cc520517af15174391a9725e634929107 harfbuzz 160000 commit 762a4ec1f4458a84bc19cd6efc1e993add90ec95 libigl 160000 commit 03afd0b83ce67062a105cfcbe80bbca152743f0a magic_get 160000 commit 7bc7d302191a4f3d0bf005692677126136e02f60 rapidcheck 160000 commit 011139094ec790ff7f32ea2d80286255fc9ed18b shaderc 160000 commit b42009b3b9d4ca35bc703f5310eedc74f584be58 stb This used to work about 6 months ago
Just in case, make sure all submodules are initialized: git submodule update --init --recursive Then, try the pull --recurse-submodules=true again. Somehow, activating the traces improve the situation: git -c trace2.eventTarget=1 pull --recurse-submodules=true
GitLab
64,190,258
19
I want to add a tag when building a Docker image, I'm doing this so far but I do not know how to get the latest tag on the repository being deployed. docker build -t company/app . My goal docker build -t company/app:$LATEST_TAG_IN_REPO? .
Since you're looking for the "latest" git tag which is an ancestor of the currently building commit you probably want to use git describe --tags --abbrev=0 to get it and use it like: docker build -t company/app:$(git describe --tags --abbrev=0) . Read here for the finer points on git describe
GitLab
56,584,835
19
I have installed and configured: an on-premises GitLab Omnibus on ServerA running on HTTPS an on-premises GitLab-Runner installed as Docker Service in ServerB ServerA certificate is generated by a custom CA Root The Configuration I've have put the CA Root Certificate on ServerB: /srv/gitlab-runner/config/certs/ca.crt Installed the Runner on ServerB as described in Run GitLab Runner in a container - Docker image installation and configuration: docker run -d --name gitlab-runner --restart always \ -v /srv/gitlab-runner/config:/etc/gitlab-runner \ -v /var/run/docker.sock:/var/run/docker.sock \ gitlab/gitlab-runner:latest Registered the Runner as described in Registering Runners - One-line registration command: docker run --rm -t -i -v /srv/gitlab-runner/config:/etc/gitlab-runner --name gitlab-docker-runner gitlab/gitlab-runner register \ --non-interactive \ --executor "docker" \ --docker-image alpine:latest \ --url "https://MY_PRIVATE_REPO_URL_HERE/" \ --registration-token "MY_PRIVATE_TOKEN_HERE" \ --description "MyDockerServer-Runner" \ --tag-list "TAG_1,TAG_2,TAG_3" \ --run-untagged \ --locked="false" This command gave the following output: Updating CA certificates... Runtime platform arch=amd64 os=linux pid=5 revision=cf91d5e1 version=11.4.2 Running in system-mode. Registering runner... succeeded runner=8UtcUXCY Runner registered successfully. Feel free to start it, but if it's running already the config should be automatically reloaded! I checked with $ docker exec -it gitlab-runner bash and once in the container with $ awk -v cmd='openssl x509 -noout -subject' ' /BEGIN/{close(cmd)};{print | cmd}' < /etc/ssl/certs/ca-certificates.crt and the custom CA root is correctly there. The Problem When running Gitlab-Runner from GitLab-CI, the pipeline fails miserably telling me that: $ git clone https://gitlab-ci-token:${CI_BUILD_TOKEN}@ServerA/foo/bar/My-Project.wiki.git Cloning into 'My-Project.wiki'... fatal: unable to access 'https://gitlab-ci-token:xxxxxxxxxxxxxxxxxxxx@ServerA/foo/bar/My-Project.wiki.git/': server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none ERROR: Job failed: exit code 1 It does not recognize the Issuer (my custom CA Root), but according to The self-signed certificates or custom Certification Authorities, point n.1, it should out-of-the-box: Default: GitLab Runner reads system certificate store and verifies the GitLab server against the CA’s stored in system. I've then tried the solution from point n.3, editing /srv/gitlab-runner/config/config.toml: and adding: [[runners]] tls-ca-file = "/srv/gitlab-runner/config/certs/ca.crt" But it still doesn't work. How can I make Gitlab Runner read the CA Root certificate?
You have two options: Ignore SSL verification Put this at the top of your .gitlab-ci.yml: variables: GIT_SSL_NO_VERIFY: "1" Point GitLab-Runner to the proper certificate As outlined in the official documentation, you can use the tls-*-file options to setup your certificate, e.g.: [[runners]] ... tls-ca-file = "/etc/gitlab-runner/ssl/ca-bundle.crt" [runners.docker] ... As the documentation states, "this file will be read every time when runner tries to access the GitLab server." Other options include tls-cert-file to define the certificate to be used if needed.
GitLab
53,159,258
19
I have to migrate from jenkins to gitlab and I would like to be able to use dynamic job names in order to have some information directly in the pipeline summary without having to click on each job etc.... in jenkins we can immediately see the parameters passed to our job and this is not the case in gitlab-ci. My test runner being on a windows I tried to define the yml as follows: job_%myParam%: stage: build script: - set>varList.txt artifacts: paths: - varList.txt When I start my job with %myParam%=true, the variable is not interpreted in the job name and so it takes the name of job_%myParam% instead of expected "job_true". Is that even possible? thks :)
As of gitlab 12.9, this can be done using trigger and child pipelines — although a little involved: Quoting the example from the gitlab doc: generate-config: stage: build script: generate-ci-config > generated-config.yml artifacts: paths: - generated-config.yml child-pipeline: stage: test trigger: include: - artifact: generated-config.yml job: generate-config In your case, you would put the definition of job_%myParam% in job.yml.in, then have the script generate-ci-config be e.g. sed "s/%myParam%/$PARAM/g" job.yml.in. This is probably a bit much for just changing the names of course, and there will be a cost associated to the additional stage; but it does answer the question, and may be useful to do more, like start with different versions of the parameter in the same pipeline.
GitLab
52,260,381
19
I want to change my git mergetool kdiff3 to p4merge. because I'm getting an error on my windows system using kdiff3 mergetool. /mingw32/libexec/git-core/git-mergetool--lib: line 128: C:\Program Files\KDiff3\kdiff3: cannot execute binary file: Exec format error application/config/constants.php seems unchanged. So that I want to change to kdiff3 to p4merge, Here also I'm getting an error like warning: merge.tool has multiple values error: cannot overwrite multiple values with a single value Use a regexp, --add or --replace-all to change merge.tool. How can I solve this problem? Either kdiff3 or p4merge
It is possible your kdiff3 installation is broken since it is not working. Or maybe you tried to edit config file manually and messed its content. why? Because windows executables have .exe extension in general. you may try editing config again. Anyways, that is not important anymore. This is what you need to use if you want to try any other tool. git mergetool --tool=p4merge There are possibly others already installed with your git. You can see all of them in addition to compatible others. git mergetool --tool-help Edit: This command works only if you set your path to the tool correctly. Otherwise, you always get No files need merging result. You already know how to set the path, but I will include here for anyone else that might need. Get the list of configuration items: git config -l See if you already have values set correctly, if any. then set to correct value or remove. git config --unset mergetool.p4merge.path git config --add mergetool.p4merge.path "c:/somewhere/p4merge.exe" EDIT: I will offer a cleaning process so, these additional commands will help. first steps are to make a backup of current settings. The simplest way is using these listings, then copy paste results. git config --list git config --global --list then with these edit commands, just get config files' path and backup them (vim shows path) or save to a different location inside the editor. git config --edit git config --global --edit now backups are ready, just exit editor. do not try to edit manually if it is not really needed. git config --unset name git config --global --unset name git config --remove-section name git config --global --remove-section name merge.tool, mergetool.name, diff.tool and difftool.name are the ones to clean here. when you list the configs again, you should not see these names. local and global should be cleaned separately. Then set back those we just cleaned one by one. but this time first try them on local configuration first then if successful set on global too. git config merge.tool name git config mergetool.name.property value git config diff.tool name git config difftool.name.property value Here property is those like cmd and path, and value is their values which you can copy from your backups. Now the important thing here is to set only 1 tool at a time at first. One last thing about paths. You (the OP) seem to use Linux-like environment, so using / instead of \\ would make path and cmd better to understand.
GitLab
50,245,867
19
To reproduce it: Create issue Open Merge Request (MR) from the issue Make changes with multiple commits Check "squash commits" and Merge the MR Why on earth this creates TWO commits in history with exactly the same changes? The commits titles: Merge branch '123-branch-name' into 'dev' Full Issue name What is the point of that?
Sounds like you create one commit containing your changes (commit Full Issue name) and a merge commit, merging changes from that commit into dev branch. The merge commit is usually created for every merge request. This can be changed in Settings->Merge Request Settings by choosing e.g. Fast Forward Merge instad of Merge Commit. This will lead to only one commit on top of your current dev HEAD, which will only work if dev can be fast forwarded. Checking squash commits will squash all commits in the feature branch you want to merge before merging it. Thus, if you had more than one commit in your feature branch, they would be squashed into one commit, which would be merged, creating a merge commit as you described (as long as your merge request settings are set to merge commit, see above). The point of that is that you might want to see that changes were performed on a different branch. This is done by not fast forwarding the branch you merge into, but create a merge request instead. This displays that two lines of development were merged, while a fast forward merge (not creating a merge commit) would not.
GitLab
50,134,937
19
My problem is the bash script I created got this error "/bin/sh: eval: line 88: ./deploy.sh: not found" on gitlab. Below is my sample script .gitlab-ci.yml. I suspect that gitlab ci is not supporting bash script. image: docker:latest variables: IMAGE_NAME: registry.gitlab.com/$PROJECT_OWNER/$PROJECT_NAME DOCKER_DRIVER: overlay services: - docker:dind stages: - deploy before_script: - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN registry.gitlab.com - docker pull $IMAGE_NAME:$CI_BUILD_REF_NAME || true production-deploy: stage: deploy only: - master@$PROJECT_OWNER/$PROJECT_NAME script: - echo "$PRODUCTION_DOCKER_FILE" > Dockerfile - docker build --cache-from $IMAGE_NAME:$CI_BUILD_REF_NAME -t $IMAGE_NAME:$CI_BUILD_REF_NAME . - docker push $IMAGE_NAME:$CI_BUILD_REF_NAME - echo "$PEM_FILE" > deploy.pem - echo "$PRODUCTION_DEPLOY" > deploy.sh - chmod 600 deploy.pem - chmod 700 deploy.sh - ./deploy.sh environment: name: production url: https://www.example.com And this also my deploy.sh. #!/bin/bash ssh -o StrictHostKeyChecking=no -i deploy.pem ec2-user@targetIPAddress << 'ENDSSH' // command goes here ENDSSH All I want is to execute deploy.sh after docker push but unfortunately got this error about /bin/bash thingy. I really need your help guys. I will be thankful if you can solve my problem about gitlab ci bash script got error "/bin/sh: eval: line 88: ./deploy.sh: not found".
This is probably related to the fact you are using Docker-in-Docker (docker:dind). Your deploy.sh is requesting /bin/bash as the script executor which is NOT present in that image. You can test this locally on your computer with Docker: docker run --rm -it docker:dind bash It will report an error. So rewrite the first line of deploy.sh to #!/bin/sh After fixing that you will run into the problem that the previous answer is addressing: ssh is not installed either. You will need to fix that too!
GitLab
49,722,185
19
This morning I got emails for each of my Gitlab Pages that are hosted on custom domains, saying that the domain verification failed. That's fine, because I don't think I ever verified them in the first place - good on Gitlab for getting this going. When I head on over the the Settings>Pages>Domain_Details on each repo, I see the instructions to create the following record: _gitlab-pages-verification-code.blog.ollyfg.com TXT gitlab-pages-verification-code={32_digit_long_code} On creating this record, and clicking the "Verify Ownership" button, I get the message "Failed to verify domain ownership". I have ensured that the record is set, and calling dig -t txt +short _gitlab-pages-verification-code.blog.ollyfg.com Returns: "gitlab-pages-verification-code={same_32_digit_long_code}" Is this a bug in Gitlab? Am I doing something wrong? Thanks!
The docs (and the verification page) were a little confusing for me. Here's what worked for me, on GoDaddy: A Record: Name: @ Value: 35.185.44.232 CNAME: Name: example.com Value: username.gitlab.io TXT Record: Name: @ Value: gitlab-pages-verification-code=00112233445566778899aabbccddeeff Verified with Gitlab, and also: dig -t txt +short example.com
GitLab
48,913,026
19
I have two different project repositories: my application repository, and an API repository. My application communicates with the API. I want to set up some integration and E2E tests of my application. The application will need to use the latest version of the API project when running these tests. The API project is already setup to deploy when triggered deploy_integration_tests: stage: deploy script: - echo "deploying..." environment: name: integration_testing only: - triggers My application has an integration testing job set up like this: integration_test stage: integration_test script: - echo "Building and deploying API..." - curl.exe -X POST -F token=<token> -F ref=develop <url_for_api_trigger> - echo "Now running the integration test that depends on the API deployment..." The problem I am having is that the trigger only queues the API pipeline (both projects are using the same runner) and continues before the API pipeline has actually run. Is there a way to wait for the API pipeline to run before trying to run the integration test? I can do something like this: integration_test_dependency stage: integration_test_dependency script: - echo "Building and deploying API..." - curl.exe -X POST -F token=<token> -F ref=develop <url_for_api_trigger> integration_test stage: integration_test script: - echo "Now running the integration test that depends on the API deployment..." But that still doesn't grantee that the API pipeline runs and finishes before moving on to the integration_test stage. Is there a way to do this?
I've come across this limitation recently and have set up an image that can be re-used to make this a simple build step: https://gitlab.com/finestructure/pipeline-trigger So in your case this would look like this using my image: integration_test stage: integration_test image: registry.gitlab.com/finestructure/pipeline-trigger script: - echo "Now running the integration test that depends on the API deployment..." - trigger -a <api token> -p <token> <project id> Just use the project id (instead of having to find the whole url) and create a personal access token, which you supply here (best do this via a secret). The reason the latter is needed is for polling the pipeline status. You can trigger without it but getting the result needs API authorisation. See the project description for more details and additional things pipeline-trigger can do.
GitLab
44,336,447
19
I have a gitlab Repository and I want it to update it on the bitbucket account. Please provide me steps to follow, so that it can be helpful to me to migrate it in bitbucket from Gitlab.
1) Create the repository in Bitbucket using the UI 2) Clone the Gitlab repository using the "--bare" option git clone --bare GITLAB-URL 3) Add the Bitbucket remote cd REPO-NAME git remote add bitbucket BITBUCKET-URL 4) Push all commits, branches and tags to Bitbucket git push --all bitbucket git push --tags bitbucket 5) Remove the temp repository cd .. rm -rf REPO-NAME
GitLab
44,106,103
19
We are facing a problem where we need to run one specific job in gitlab CI. We currently not know how to solve this problem. We have multitple jobs defined in our .gitlab-ci.yml but we only need to run a single job within our pipelines. How could we just run one job e.g. job1 or job2? We can't use tags or branches as a software switch in our environment. .gitlab-ci.yml: before_script: - docker info job1: script: - do something job2: script: - do something
You can use a gitlab variable expression with only/except like below and then pass the variable into the pipeline execution as needed. This example defaults to running both jobs, but if passed 'true' for "firstJobOnly" it only runs the first job. Old Approach -- (still valid as of gitlab 13.8) - only/except variables: firstJobOnly: 'false' before_script: - docker info job1: script: - do something job2: script: - do something except: variables: - $firstJobOnly =~ /true/i Updated Approach - rules While the above still works, the best way to accomplish this now would be using the rules syntax. A simple example similar to my original reply is below. If you explore the options in the rules syntax, depending on the specific project constraints there are many ways this could be achieved. variables: firstJobOnly: 'false' job1: script: - do something job2: script: - do something rules: - if: '$firstJobOnly == "true"' when: never - when: always
GitLab
42,986,385
19
I'm trying to implement a GitLab continuous integration (CI) pipeline with the following .gitlab-ci.yml file: image: docker:latest # When using dind, it's wise to use the overlayfs driver for # improved performance. variables: DOCKER_DRIVER: overlay services: - docker:dind before_script: - docker info - curl -L "https://github.com/docker/compose/releases/download/1.10.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose - chmod +x /usr/local/bin/docker-compose - export PATH=/usr/local/bin:$PATH - echo $PATH stages: - build - test build: stage: build script: - docker-compose build - docker-compose up -d test: stage: test script: - cd tests/tester - pytest test_run_tester.py except: - /^.*skip_tests$/ However, in GitLab I'm getting the following error message: Running with gitlab-ci-multi-runner 1.10.4 (b32125f) Using Docker executor with image docker:latest ... Starting service docker:dind ... Pulling docker image docker:dind ... Waiting for services to be up and running... Pulling docker image docker:latest ... Running on runner-2e54fd37-project-13-concurrent-0 via scw-de9c9c... Fetching changes... HEAD is now at 2504a08 Update CI config From https://lab.iperlane.com/gio/ipercron-compose 2504a08..5c2f23f CI -> origin/CI Checking out 5c2f23f1 as CI... Skipping Git submodules setup $ docker info Containers: 0 Running: 0 Paused: 0 Stopped: 0 Images: 0 Server Version: 1.13.1 Storage Driver: overlay Backing Filesystem: extfs Supports d_type: true Logging Driver: json-file Cgroup Driver: cgroupfs Plugins: Volume: local Network: bridge host macvlan null overlay Swarm: inactive Runtimes: runc Default Runtime: runc Init Binary: docker-init containerd version: aa8187dbd3b7ad67d8e5e3a15115d3eef43a7ed1 runc version: 9df8b306d01f59d3a8029be411de015b7304dd8f init version: 949e6fa Security Options: seccomp Profile: default Kernel Version: 4.8.14-docker-2 Operating System: Alpine Linux v3.5 (containerized) OSType: linux Architecture: x86_64 CPUs: 4 Total Memory: 7.751 GiB Name: 90395a030c02 ID: 7TKR:5PQN:XLFM:EJST:NF2V:NLQC:I2IZ:6OZG:TR4U:ZEAK:EVXE:HIF7 Docker Root Dir: /var/lib/docker Debug Mode (client): false Debug Mode (server): false Registry: https://index.docker.io/v1/ Experimental: false Insecure Registries: 127.0.0.0/8 Live Restore Enabled: false WARNING: bridge-nf-call-iptables is disabled WARNING: bridge-nf-call-ip6tables is disabled $ curl -L "https://github.com/docker/compose/releases/download/1.10.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 100 600 0 600 0 0 1175 0 --:--:-- --:--:-- --:--:-- 1176 0 0 0 0 0 0 0 0 --:--:-- 0:00:01 --:--:-- 0 3 7929k 3 254k 0 0 116k 0 0:01:08 0:00:02 0:01:06 258k 17 7929k 17 1358k 0 0 433k 0 0:00:18 0:00:03 0:00:15 704k 61 7929k 61 4861k 0 0 1164k 0 0:00:06 0:00:04 0:00:02 1636k 100 7929k 100 7929k 0 0 1703k 0 0:00:04 0:00:04 --:--:-- 2300k $ chmod +x /usr/local/bin/docker-compose $ export PATH=/usr/local/bin:$PATH $ docker-compose build /bin/sh: eval: line 51: docker-compose: not found ERROR: Build failed: exit code 127 The system seems not to be able to find docker-compose, even after installing it and adding it to the path. Is there perhaps another image such that docker-compose commands can be made, or a different way to install it in the .gitlab-ci.yml?
The problem This is complex problem. The docker:latest image is based on alpine (Alpine Linux), which is built using musl-libc. This system is very barebones, and as such doesn't have everything a full-fledged desktop Linux might have. In fact, dynamic executables need to be compiled specifically for this system. docker-compose is a Python application, bundled into a Linux executable using PyInstaller. These executables are really only expected to be able to run on the system which they were built. If you run an alpine container, and apk add file, you can see that the (dynamically-linked) executable you downloaded is expecting a specific interpreter. # file /usr/local/bin/docker-compose /usr/local/bin/docker-compose.pyinstaller: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=00747fe5bcde089bb4c2f1ba7ab5348bc02ac5bf, stripped The problem is /lib64/ld-linux-x86-64.so.2 doesn't exist in alpine. In fact, /lib64 doesn't even exist. The solution Because docker-compose is a Python application, it can also be installed using pip: Testing this inside an alpine container: $ docker run --rm -it alpine /bin/bash Here are the commands you can run manually, or add to your .gitlab-ci.yml before_script: # apk add --no-cache python py2-pip ... # pip install --no-cache-dir docker-compose ... # docker-compose -v docker-compose version 1.11.1, build 7c5d5e4 It turns out there is actually an open issue for this: https://github.com/docker/compose/issues/3465
GitLab
42,295,457
19
Question What is the best way to carry artifacts (jar, class, war) among projects when using docker containers in CI phase. Let me explain my issue in details, please don't stop the reading... =) Gitlabs project1 unit tests etc... package Gitlabs project2 unit test etc... build (failing) here I need one artifact (jar) generated in project1 Current scenario / comments I'm using dockers so in each .gitlab-ci.yml I'll have independent containers All is working fine in project1 If I use "shell" instead of dockers in my .gitlab-ci.yml I can keep the jar file from the project1 in the disk and use when project2 kicks the build Today my trigger on call project2 when project1 finish is working nicely My artifact is not an RPM so I'll not add into my repo Possible solutions I can commit the artifact of project1 and checkout when need to build project2 I need to study if cache feature from gitlabs is designed for this purpose (gitlab 8.2.1, How to use cache in .gitlab-ci.yml)
In GitLab silver and premium, there is the $CI_JOB_TOKEN available, which allows the following .gitlab-ci.yaml snippet: build_submodule: image: debian stage: test script: - apt update && apt install -y unzip - curl --location --output artifacts.zip "https://gitlab.example.com/api/v4/projects/1/jobs/artifacts/master/download?job=test&job_token=$CI_JOB_TOKEN" - unzip artifacts.zip only: - tags However, if you do not have silver or higher gitlab subscriptions, but rely on free tiers, it is also possible to use the API and pipeline triggers. Let's assume we have project A building app.jar which is needed by project B. First, you will need an API Token. Go to Profile settings/Access Tokens page to create one, then store it as a variable in project B. In my example it's GITLAB_API_TOKEN. In the CI / CD settings of project B add a new trigger, for example "Project A built". This will give you a token which you can copy. Open project A's .gitlab-ci.yaml and copy the trigger_build: section from project B's CI / CD settings trigger section. Project A: trigger_build: stage: deploy script: - "curl -X POST -F token=TOKEN -F ref=REF_NAME https://gitlab.example.com/api/v4/projects/${PROJECT_B_ID}/trigger/pipeline" Replace TOKEN with that token (better, store it as a variable in project A -- then you will need to make it token=${TRIGGER_TOKEN_PROJECT_B} or something), and replace REF_NAME with your branch (e.g. master). Then, in project B, we can write a section which only builds on triggers and retrieves the artifacts. Project B: download: stage: deploy only: - triggers script: - "curl -O --header 'PRIVATE-TOKEN: ${GITLAB_API_TOKEN}' https://gitlab.example.com/api/v4/projects/${PROJECT_A_ID}/jobs/${REMOTE_JOB_ID}/artifacts/${REMOTE_FILENAME}" If you know the artifact path, then you can replace ${REMOTE_FILENAME} with it, for example build/app.jar. The project ID can be found in the CI / CD settings. I extended the script in project A to pass the remaining information as documented in the trigger settings section: Add variables[VARIABLE]=VALUE to an API request. Variable values can be used to distinguish between triggered pipelines and normal pipelines. So the trigger passes the REMOTE_JOB_ID and the REMOTE_FILENAME, but of course you can modify this as you need it: curl -X POST \ -F token=TOKEN \ -F ref=REF_NAME \ -F "variables[REMOTE_FILENAME]=build/app.jar" \ -F "variables[REMOTE_JOB_ID]=${CI_JOB_ID}" \ https://gitlab.example.com/api/v4/projects/${PROJECT_B_ID}/trigger/pipeline
GitLab
39,462,371
19
Is there a way to set a default assignee for newly cerated issues? All new issues are set to Unassigned. This way no notifications about this issue are sent out unless people set their notification levels to watching. And notification settings can only be set for entire groups or projects you are explicitly set as member.
I have finally found a solution for this myself. It's possible to implement default assignees using templates and quick actions: Simply put /assign @username into the templates. This way you can even define multiple default assignees for different kinds of issues.
GitLab
35,294,878
19
I know you can use Github issues on the command line by installing ghi. ghi However, is there any way to use similar tools for listing/adding/removing/editing issues of repositories on Gitlab ?
GLab seems to be a great option. GLab is an open source Gitlab Cli tool written in Go (golang) to help work seamlessly with Gitlab from the command line. Work with issues, merge requests, watch running pipelines directly from your CLI among other features. https://github.com/profclems/glab
GitLab
31,870,653
19
I am having troubles when I connect with my repository through Xcode. I have a Gitlab version (full pre-)installed on TurnkeyLinux Virtual Appliance on a remote server. In the Gitlab Web interface, I've created a new test user: "testuser" with a password "password" and a new project "testproject". This user was assigned to this project. The git url project are: HTTP: http://example.com/testuser/testproject.git SSH: [email protected]:testuser/testproject.git I can see the repositories folder rightly created with a "Terminal" through SSH connection. Now, I want add this git repository to my Xcode repositories. So, In XCode > Preferences > Account I'm trying add it, using both urls and my user credentials, but always receive the following message: "Authentication failed because the name or password was incorrect." Could anyone help me?
The user/password would only be needed for an http url, not an ssh one. When using the http url to add a repo in your XCode Accounts, make sure there is no proxy which would prevent the resolution of the example.com server. If it is still not working, then, as in "Authentification issue when pushing Xcode project to GitHub", try to use an url like: https://testuser:[email protected]/testuser/testproject.git
GitLab
20,266,294
19
Is there a way I can run GitLab (http://gitlab.org/gitlab-ce) and GitLab CI (http://gitlab.org/gitlab-ci) on a Raspberry Pi device running Raspbian? I want to have my own internal Git box where I can store code and possibly allow other friends access to upload their code too. Is it possible? Thanks.
Official way for the Pi 2 There is a very easy way to install it on the Raspberry Pi 2. wget https://s3-eu-west-1.amazonaws.com/downloads-packages/raspberry-pi/gitlab_7.9.0-omnibus.pi-1_armhf.deb sudo dpkg -i gitlab_7.9.0-omnibus.pi-1_armhf.deb You might prefer to go to the official page in order to get latest version. It's fast and easy, they recommend at least 1Gb swap. On the Pi B and B+ you will hit the memory limit very soon and get degraded performance as you grow, but on the Pi 2 it works nicely, specially if you mount your repos on an external USB hard disk.
GitLab
19,606,735
19
How can one create a table on gitlab wiki? It uses github flavored markdown, and this flavor of markdown support tables but I can't make the following example work: Colons can be used to align columns. | Tables | Are | Cool | | ------------- |:-------------:| -----:| | col 3 is | right-aligned | $1600 | | col 2 is | centered | $12 | | zebra stripes | are neat | $1 | The outer pipes (|) are optional, and you don't need to make the raw Markdown line up prettily. You can also use inline Markdown. Markdown | Less | Pretty --- | --- | --- *Still* | `renders` | **nicely** 1 | 2 | 3 Is there a trick to activate tables?
Update: See GitLab 14.1 (July 2021) Create tables and upload images in the Wiki Content Editor Create tables and upload images in the Wiki Content Editor We began improving your wiki editing experience in GitLab 14.0, when we introduced the MVC of a new WYSIWYG Markdown editor. It supported the most common Markdown formatting options, but with some notable gaps. GitLab 14.1 continues to improve your editing experience for images and tables. You can now upload images directly into the editor. You can also insert and edit tables, including copying and pasting content from popular spreadsheet applications to bring tables from other sources into your wiki. ​ See Documentation and Issue. And: See GitLab 14.3 (September 2021) Edit a table’s structure visually in the new wiki editor Edit a table’s structure visually in the new wiki editor Editing a Markdown table that has 9 columns and 25 rows is one thing. But adding a tenth column to that table in Markdown? That involves very repetitive and error-prone edits to every row. One mistake or misplaced | and the table fails to render. The new WYSIWYG Markdown editor in the wiki lets you quickly and easily insert a table using the button in the toolbar. After selecting the initial number of rows and columns, however, dealing with the structure of the table can be more difficult. In GitLab 14.3, you can now click on the caret icon in the top right corner of any selected cell to add or remove columns and rows, either before or after the selected cell. Now, as your content scales, the complexity doesn’t follow suit. See Documentation and Issue. See GitLab 14.5 (November 2021) Tables in wikis support block-level elements GitLab 14.1 introduced WYSIWYG editing for tables in the new wiki editor, but the types of content supported in table cells were limited by the underlying Markdown implementation: you couldn’t add block-level elements like lists, code blocks, or pull quotes inside a table. Now, in GitLab 14.5, these block-level elements are fully supported inside table cells. You can insert lists, code blocks, paragraphs, headings, and even nested tables inside a table cell, giving you more flexibility and freedom to format your content to meet your needs. See Documentation and Issue. Original answer: 2013: It seems to be still the case, as described in Issue 3651 and issue 1238, even though Flavored Markdown is supported: This wouldn't work: | parameters | desc | | :--------- | :------------------- | | -w | --word | Parameter for Word | So contributions are welcome on this specific bug. However, AJNeufeld suggest (in 2016) in the comments: You need to use the &#124; entity code to get the vertical pipe between "-w" and "--word", so it appears as "-w | --word" in the rendered table. Ie, the full line should be: | -w &#124; --word | Parameter for Word |
GitLab
17,604,270
19
I'm trying to commit my first Git repository to a gitlab instance, which I've set up on a debian-VM. Everything is going to happen via local network. The following commands are shown in gitlab after creating a new repo. mkdir test cd test git init touch README git add README git commit -m 'first commit' git remote add origin [email protected]:1337:Matt/test.git git push -u origin master After entering git push -u origin master this happens: [email protected]'s password: fatal: '1337:Matt/test.git' does not appear to be a Git repository fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. Could the problem be the port on which Git is running at? Gitlab is accessible through port 617 so I'am able to reach the GUI via http://xxx.xxx.xxx.xxx:617/Matt/test The password I've entered seems to be correct, because a wrong password will end up in a "permission denied" message. OT: I don't know why I've to enter a passwd, because I've generated and added ssh-keys, as described in gitlab, but that's an other problem.
I've solved my problem. The given port 1337 wasn't the problem, although it was wrong too, because ssh does not seem to be able to handle a port in url: Using a remote repository with non-standard port The Git-url which worked for me was: [email protected]:repositories/Matt/test.git My Git user home dir is located in /home/git/ and the repositories are stored in /home/git/repositories so i had to add repositories to my Git-path. The reason why GitLab told me to use the url [email protected]:1337:Matt/test.git seems to be a wrong configured Git path in GitLab. I'll try to fix this now. Edit: The wrong host was configured in /home/git/gitlab/config/gitlab.yml. The "host" there must be without port... There is an extra option for the port if needed. Edit3: Still unable to push or fetch my test-repository without repositories in path.. https://github.com/gitlabhq/gitlab-public-wiki/wiki/Trouble-Shooting-Guide#could-not-read-from-remote-repository Maybe something to do with rsa-keys but I don't understand how this belongs together. Edit4: (Problem(s) seem to be solved) My rsa-keys were ok. The problem was that I've configured my sshd_config to allow only a certain user for ssh-login. I've simply added Git to the list of allowed users AllowUsers mylogin git Now I don't have to login via password anymore (You never have to login via password if ssh rsa keys are set up correctly) and the path works without "repositories" as it should. Now I understand, that this is just a normal ssh-connection - I hadn't realized this before.. The way I figured it out: login via terminal as root: service ssh stop #Current SSH-Connection won't be closed.. /usr/sbin/sshd -d ====debugging mode=== Then in Git Bash: ssh -Tv [email protected] Afterwards the terminal with sshd running in debug mode has thrown an error that Git is not allowed to login because of AllowUsers... Don't forget to start your ssh service afterwards: service ssh start
GitLab
16,912,542
19
I have an existing Gitolite configuration with many users and repositories. It is setup in the default way as the Gitolite installation guide suggests. Now I would like to add GitLab to be able to do code reviews and bug tracking. What's the most convenient way to achieve this?
Original answer (January 2013) You can follow the standard installation, and indicate in your gitlab.yml config file the location of your gitolite repo, as well as the gitolite admin user. However, GitLab requires from the user to register themselves in GitLab and copy their public ssh key. That means you might need to adapt the way gitolite has stored existing gitolite users, since the name you have used is likely to be different than the name used by GitLab (it uses a name based on the login_email_auuid). Update (August 2018, 5 years later): As commented below by Thomas, a few months after this answer, GitLab released GitLab 5.0, without gitolite. Now I would like to add GitLab to be able to do code reviews and bug tracking. What's the most convenient way to achieve this? These days (2018, GitLab 11.2.x), code review is supported through merge request (it has been so since a few years already). See: "Demo: Mastering code review with GitLab" from Emily von Hoffmann, "Code Review Via GitLab Merge Requests" from Maxim Letushov.
GitLab
14,523,876
19
In the gitlab documentation you find a list of predefined variables HERE, where the variable CI_PIPELINE_SOURCE is explained to have the possible values "push, web, schedule, api, external, chat, webide, merge_request_event, external_pull_request_event, parent_pipeline, trigger, or pipeline." However, it is not explained, what they mean. push: When you push something to a branch? web: When you trigger a pipeline from the web GUI? schedule: When a pipeline is triggered by a schedule api: When the pipeline is triggered by an API request external: ??? chat: ??? webide: ??? merge_request_event: Seems to be triggered when a merge request is created. Does not trigger when a change is actually merged external_pull_request_event: ??? parent_pipeline: ??? trigger: ??? pipeline: another pipeline? If someone knows where the documentation for that is hiding, I appreciate if you can let me know where to find it. In addition, how can I figure out when some changes are actually merged into a branch? How can I trigger a pipeline in that event?
Regarding your first set of questions, i have to point you forward to the gitlab CI Documentation and the rules:if section. They have their a good explanation of the states and also some addtion https://docs.gitlab.com/ee/ci/jobs/job_control.html#common-if-clauses-for-rules - i am just screenshoting this, so people can relate to it in the future if the link gets outdated: Regarding your additional question: A merge is a push. We do not check on some branches for CI_PIPELINE_SOURCE but for the branch name and do checks simply against that like: rules: - if: '$CI_COMMIT_BRANCH == "master"' - if: '$CI_COMMIT_BRANCH == "develop"' - if: '$CI_COMMIT_BRANCH =~ /^release.*$/i' - if: '$CI_PIPELINE_SOURCE == "merge_request_event"' This works eg perfectly in our case for gitflow. But you can vary your rules and easily define them to your own needs - the rules documentation gives a lot of good examples see: https://docs.gitlab.com/ee/ci/jobs/job_control.html#common-if-clauses-for-rules
GitLab
69,734,612
18
I'm deploying the front-end of my website to amazon s3 via Gitlab pipelines. My previous deployments have worked successfully but the most recent deployments do not. Here's the error: Completed 12.3 MiB/20.2 MiB (0 Bytes/s) with 1 file(s) remaining upload failed: dist/vendor.bundle.js.map to s3://<my-s3-bucket-name>/vendor.bundle.js.map Unable to locate credentials Under my secret variables I have defined four. They are S3 credential variables (AWS_ACCESS_KEY_ID & AWS_SECRET_ACCESS_KEY) for two different buckets. One pair is for the testing branch and the other is for the production branch. Not - the production environment variables are protected and the other variables are not. Here's the deploy script that I run: #/bin/bash #upload files aws s3 cp ./dist s3://my-url-$1 --recursive --acl public-read So why am I getting this credential location error? Surely it should just pick up the environment variables automatically (the unprotected ones) and deploy them. Do I need to define the variables in the job and refer to them?
(I encountered this issue many times - Adding another answer for people that have the same error - from other reasons). A quick checklist. Go to Setting -> CI/CD -> Variables and check: If both AWS_ACCESS_KEY_ID & AWS_SECRET_ACCESS_KEY environment variables exist. If both names are spelled right. If their state is defined as protected - they can only be ran against protected branches (like master). If error still occurs: Make sure the access keys still exist and active on your account. Delete current environment variables and replace them with new generated access keys and make sure AWS_SECRET_ACCESS_KEY doesn't contain any special characters (can lead to strange errors).
GitLab
49,814,003
18
Basically I am looking for the retry button for the pipeline triggered, but all I see is a retry button for the individuals jobs of that pipeline. I don't want to have to push a commit just to retry a pipeline. Reference screenshot
You can retry the latest push on the pipeline by going to: CI/CD -> Pipelines -> Run Pipeline -> Select the branch to run. Otherwise, as you've mentioned, you'd have to manually press the retry button for each individual job for the pipeline (for a pipeline that isn't the latest).
GitLab
49,686,342
18
I have a GitLab CI docker runner to execute my automated tests when I push. One of my tests requires a custom entry in /etc/hosts. I can't figure out how to get the entry into that file. Here's basically what my .gitlab-ci.yml file looks like: before_script: - cat /etc/hosts # for debugging - ... # install app dependencies specs: script: - rspec # <- a test in here fails without the /etc/hosts entry All my tests pass, except for the one that requires that /etc/hosts entry. Let's say I'm trying to have the hostname myhost.local resolve to the IPv4 address XX.XX.XX.XX... I tried using extra_hosts on the runner config, but it didn't seem to have any effect (got idea from here): /etc/gitlab-runner/config.toml: concurrent = 1 check_interval = 0 [[runners]] name = "shell" url = "https://mygitlabinstance.com/" token = "THETOKEN" executor = "shell" [runners.cache] [[runners]] name = "docker-ruby-2.5" url = "https://mygitlabinstance.com/" token = "THETOKEN" executor = "docker" [runners.docker] tls_verify = false image = "ruby:2.5" privileged = false disable_cache = false volumes = ["/cache"] shm_size = 0 extra_hosts = ["myhost.local:XX.XX.XX.XX"] [runners.cache] But the test still failed. The cat /etc/hosts shows that it's unchanged: # Your system has configured 'manage_etc_hosts' as True. # As a result, if you wish for changes to this file to persist # then you will need to either # a.) make changes to the master file in /etc/cloud/templates/hosts.tmpl # b.) change or remove the value of 'manage_etc_hosts' in # /etc/cloud/cloud.cfg or cloud-config from user-data # 127.0.1.1 ip-172-31-2-54.ec2.internal ip-172-31-2-54 127.0.0.1 localhost # The following lines are desirable for IPv6 capable hosts ::1 ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters ff02::3 ip6-allhosts I figured I could just add the entry myself in a before_script line, but I don't seem to be able to execute anything with root privileges in the container: before_script: - echo 'XX.XX.XX.XX myhost.local' >> /etc/hosts ... But that just fails because the gitlab-runner user doesn't have permissions to write to that file. I tried to use sudo, but gitlab-runner can't do that either (echo 'XX.XX.XX.XX myhost.local' | sudo tee --non-interactive --append /etc/hosts --> sudo: a password is required) So in summary, how can I get my container to have the host entry I need (or how can I execute a before_script command as root)?
The following statement is incorrect: "But that just fails because the gitlab-runner user doesn't have permissions to write to that file." The gitlab-runner is not the user executing your before_script, it is the user that runs the container in which your job is executed. You are using the ruby:2.5 Docker image as far as I can tell and that does not contain any USER reference in its or its parents Dockerfile. Try adding a whoami command right before your echo 'XX.XX.XX.XX myhost.local' >> /etc/hosts command to verify you are root. Update If gitlab-runner is shown as the result of whoamithe docker-executor is not used and instead a shell-executor has picked up the job.
GitLab
48,505,986
18
I'm in the middle of some CocoaPods project trying to build my own private Pod, reachable via "pod install" from my main project. It's a Swift project, and everything seemed to be working, reading the appropriate tutorials, etc... I have to say I've been using cocoapods for some time, but I'm kind of new building my own pods and storing them in my private gitlab space. And that seems to be my problem: Apparently I don't know how to properly store my recently created pod on my gitlab space. Additionaly, running "pod install" can't fetch my podspec file. What I have now is a main project, with a Podfile. In this project I have the next simple definition for my pods (2 public (SpkinKit and MBProgressHUD) and 1 private, 'commons'): My Podfile is this one: # Uncomment this line to define a global platform for your project platform :ios, '8.0' target 'MyBaseApp' do # Comment this line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for MyBaseApp pod 'SpinKit' pod 'MBProgressHUD' pod 'commons', :path => 'ssh://git@internal_ip_numeric_address_of_my_gitlab_machine:2222/myusername/ios_commons_pod.git' end If I type "pod install --verbose" I get the following output: Fetching external sources -> Fetching podspec for `commons` from `ssh://git@internal_ip_numeric_address_of_my_gitlab_machine:2222/myusername/ios_commons_pod.git` [!] No podspec found for `commons` in `ssh://git@internal_ip_numeric_address_of_my_gitlab_machine:2222/myusername/ios_commons_pod.git` This crash doesn't allow the pod to get downloaded, and the process stops here. What seems to be wrong? As far as I understand I DO have a podspec file in that gitlab path route. Look at this screenshot: The URL scheme I'm using is the SSH flavoured one, that is the one appearing on the root of my gitlab project homepage (not the HTTP/HTTPS one). This is a limitation of the project, so I can't use the HTTP one. OTOH I think my SSH credentials (and key setup) are stored ok on my machine. Why? because I try using a ssh shell against that URL, from the command line, and I can see "Welcome myusername" on screen without specifying any username and password (Then the gitlab machine logouts that shell for security reasons, but that's another theme. That's expected behaviour). Whatever, I'm still not sure what exact URL format/path should I use in my base app Podfile. Inside gitlab I have my files and podspec file stored with the structure shown in the last screenshot, but I'm still not 100% sure if I've setup everything ok. The contents of my commons.podspec file are these: Pod::Spec.new do |s| # 1 s.platform = :ios s.ios.deployment_target = '8.0' s.name = "commons" s.summary = "commons test fw via pod." s.requires_arc = true # 2 s.version = "0.1.0" # 3 s.license = { :type => "MIT", :file => "LICENSE" } # 4 - Replace with your name and e-mail address s.author = { "Me" => "[email protected]" } # 5 - Replace this URL with your own Github page's URL (from the address bar) s.homepage = "http://internal_ip_numeric_address_of_my_gitlab_machine:8888/myusername" # 6 - Replace this URL with your own Git URL from "Quick Setup" s.source = { :git => "http://internal_ip_numeric_address_of_my_gitlab_machine:8888/myusername/ios_commons_pod.git", :tag => "#{s.version}"} # 7 s.framework = "UIKit" s.dependency 'RNCryptor' # 8 s.source_files = "commons/**/*.{swift}" # 9 s.resources = "commons/**/*.{png,jpeg,jpg,xib,storyboard}" end Any hint? Thanks.
The only thing you need to do is change :path => to :git => and it should download the pod from your repo.
GitLab
39,223,846
18
If there are more than one available runner for a project, how does gitlab ci decide which runner to use? I have an omnibus gitlab 8.6.6-ee installation, with 2 runners configured. The runners are identical (docker images, config, etc) except that they are running on different computers. If they are both idle and a job comes in that either of them could run, which one will run?
To add to Rubinum's answer the 'first' runner would be whichever runner that checks in first that meets all criteria. For example, labels could limit which runners certain jobs run on. Runners query the gitlab server every X seconds to check if there are builds. if there's a build queued and multiple meet criteria, the first to ask will win Update to answer comments: Runners communicate through the CI API http://docs.gitlab.com/ce/ci/api/builds.html to get build status. This will eventually imply that it will become a more or less random choosing of the runner based on when it finished the last job and the xamount of msit is waiting to check. To completely answer the question: Credit goes to BM5k after digging through the code and finding that x = 3 seconds based on this and this. Also found that: which machine a docker+machine runner will use once that runner has been selected) reveals that the machine selection is more or less (effectively) random as well
GitLab
36,700,653
18
As the title states, I can't clone a repository from a Gitlab 6 server even though the ssh seems to work. When trying to clone, it looks like this: git clone ssh://[email protected]:1337/project/repository.git Cloning into 'repository'... Access denied. fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. In the project, I have the role of "developer" which should have the rights to clone a repository? I also checked if my SSH public key is working ssh [email protected] -p 1337 -T Welcome to GitLab, Anonymous! More irritating to me is that for a friend of mine seems everything to work fine. Edit: The main indicator for the problem stated here is the greeting from the SSH Test. In an working enviroment it should be greeting you with your name instead Anonymous!
Try the scp-like syntax: git clone ssh://[email protected]:1337:project/repository.git That forces the use of ~/.ssh/config actually, which means the url can be simplified to gitlab:project/repositoriy.git. But it turned out to be an ssh key issue in the gitlab server ~gitlab/.ssh/authorized_keys (a bit like in issue 4730). The OP Gelix confirms in the comments: I removed my key from Gitlab, manually from authorized_keys, readded it on Gitlab. Everything fine now. Message with SSH Test is now also Welcome to GitLab, Felix *****! (instead of Welcome to GitLab, Anonymous!)
GitLab
33,837,103
18
I am using the Omnibus GitLab CE system with LDAP authentication. Because of LDAP authentication, anyone in my company can sign in to GitLab and a new GitLab user account associated with this user is created (according to my understanding). I want to modify it so that by default this new user (who can automatically sign in based on his LDAP credentials) cannot create new projects. Then, I as the admin, will probably handle most new project creation. I might give the Create Project permission to a few special users.
In newer versions of GitLab >= v7.8 … This is not a setting in config/gitlab.yml but rather in the GUI for admins. Simply navigate to https://___[your GitLab URL]___/admin/application_settings/general#js-account-settings, and set Default projects limit to 0. You can then access individual users's project limit at https://___[your GitLab URL]___/admin/users. See GitLab's update docs for more settings changed between v7.7 and v7.8. git diff origin/7-7-stable:config/gitlab.yml.example origin/7-8-stable:config/gitlab.yml.example
GitLab
27,909,176
18
How do I iterate over the words of a string composed of words separated by whitespace? Note that I'm not interested in C string functions or that kind of character manipulation/access. I prefer elegance over efficiency. My current solution: #include <iostream> #include <sstream> #include <string> using namespace std; int main() { string s = "Somewhere down the road"; istringstream iss(s); do { string subs; iss >> subs; cout << "Substring: " << subs << endl; } while (iss); }
I use this to split string by a delimiter. The first puts the results in a pre-constructed vector, the second returns a new vector. #include <string> #include <sstream> #include <vector> #include <iterator> template <typename Out> void split(const std::string &s, char delim, Out result) { std::istringstream iss(s); std::string item; while (std::getline(iss, item, delim)) { *result++ = item; } } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, std::back_inserter(elems)); return elems; } Note that this solution does not skip empty tokens, so the following will find 4 items, one of which is empty: std::vector<std::string> x = split("one:two::three", ':');
Split
236,129
3,361
How do I split a list of arbitrary length into equal sized chunks? See also: How to iterate over a list in chunks. To chunk strings, see Split string every nth character?.
Here's a generator that yields evenly-sized chunks: def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i:i + n] import pprint pprint.pprint(list(chunks(range(10, 75), 10))) [[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35, 36, 37, 38, 39], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], [50, 51, 52, 53, 54, 55, 56, 57, 58, 59], [60, 61, 62, 63, 64, 65, 66, 67, 68, 69], [70, 71, 72, 73, 74]] For Python 2, using xrange instead of range: def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in xrange(0, len(lst), n): yield lst[i:i + n] Below is a list comprehension one-liner. The method above is preferable, though, since using named functions makes code easier to understand. For Python 3: [lst[i:i + n] for i in range(0, len(lst), n)] For Python 2: [lst[i:i + n] for i in xrange(0, len(lst), n)]
Split
312,443
3,126
I have this string stored in a variable: IN="[email protected];[email protected]" Now I would like to split the strings by ; delimiter so that I have: ADDR1="[email protected]" ADDR2="[email protected]" I don't necessarily need the ADDR1 and ADDR2 variables. If they are elements of an array that's even better. After suggestions from the answers below, I ended up with the following which is what I was after: #!/usr/bin/env bash IN="[email protected];[email protected]" mails=$(echo $IN | tr ";" "\n") for addr in $mails do echo "> [$addr]" done Output: > [[email protected]] > [[email protected]] There was a solution involving setting Internal_field_separator (IFS) to ;. I am not sure what happened with that answer, how do you reset IFS back to default? RE: IFS solution, I tried this and it works, I keep the old IFS and then restore it: IN="[email protected];[email protected]" OIFS=$IFS IFS=';' mails2=$IN for x in $mails2 do echo "> [$x]" done IFS=$OIFS BTW, when I tried mails2=($IN) I only got the first string when printing it in loop, without brackets around $IN it works.
You can set the internal field separator (IFS) variable, and then let it parse into an array. When this happens in a command, then the assignment to IFS only takes place to that single command's environment (to read ). It then parses the input according to the IFS variable value into an array, which we can then iterate over. This example will parse one line of items separated by ;, pushing it into an array: IFS=';' read -ra ADDR <<< "$IN" for i in "${ADDR[@]}"; do # process "$i" done This other example is for processing the whole content of $IN, each time one line of input separated by ;: while IFS=';' read -ra ADDR; do for i in "${ADDR[@]}"; do # process "$i" done done <<< "$IN"
Split
918,886
2,942
I want to split a string using a delimiter, for example split "004-034556" into two separate strings by the delimiter "-": part1 = "004"; part2 = "034556"; That means the first string will contain the characters before '-', and the second string will contain the characters after '-'. I also want to check if the string has the delimiter ('-') in it.
Use the appropriately named method String#split(). String string = "004-034556"; String[] parts = string.split("-"); String part1 = parts[0]; // 004 String part2 = parts[1]; // 034556 Note that split's argument is assumed to be a regular expression, so remember to escape special characters if necessary. there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters". For instance, to split on a period/dot . (which means "any character" in regex), use either backslash \ to escape the individual special character like so split("\\."), or use character class [] to represent literal character(s) like so split("[.]"), or use Pattern#quote() to escape the entire string like so split(Pattern.quote(".")). String[] parts = string.split(Pattern.quote(".")); // Split on the exact string. To test beforehand if the string contains certain character(s), just use String#contains(). if (string.contains("-")) { // Split it. } else { throw new IllegalArgumentException("String " + string + " does not contain -"); } Note, this does not take a regular expression. For that, use String#matches() instead. If you'd like to retain the split character in the resulting parts, then make use of positive lookaround. In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing ?<= group on the pattern. String string = "004-034556"; String[] parts = string.split("(?<=-)"); String part1 = parts[0]; // 004- String part2 = parts[1]; // 034556 In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing ?= group on the pattern. String string = "004-034556"; String[] parts = string.split("(?=-)"); String part1 = parts[0]; // 004 String part2 = parts[1]; // -034556 If you'd like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of split() method. String string = "004-034556-42"; String[] parts = string.split("-", 2); String part1 = parts[0]; // 004 String part2 = parts[1]; // 034556-42
Split
3,481,828
1,934
Let's say that I have an Javascript array looking as following: ["Element 1","Element 2","Element 3",...]; // with close to a hundred elements. What approach would be appropriate to chunk (split) the array into many smaller arrays with, lets say, 10 elements at its most?
The array.slice() method can extract a slice from the beginning, middle, or end of an array for whatever purposes you require, without changing the original array. const chunkSize = 10; for (let i = 0; i < array.length; i += chunkSize) { const chunk = array.slice(i, i + chunkSize); // do whatever } The last chunk may be smaller than chunkSize. For example when given an array of 12 elements the first chunk will have 10 elements, the second chunk only has 2. Note that a chunkSize of 0 will cause an infinite loop.
Split
8,495,687
1,044
I need to split a string into newlines in .NET and the only way I know of to split strings is with the Split method. However that will not allow me to (easily) split on a newline, so what is the best way to do it?
To split on a string you need to use the overload that takes an array of strings: string[] lines = theText.Split( new string[] { Environment.NewLine }, StringSplitOptions.None ); Edit: If you want to handle different types of line breaks in a text, you can use the ability to match more than one string. This will correctly split on either type of line break, and preserve empty lines and spacing in the text: string[] lines = theText.Split( new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.None );
Split
1,547,476
976
In a Bash script, I would like to split a line into pieces and store them in an array. For example, given the line: Paris, France, Europe I would like to have the resulting array to look like so: array[0] = Paris array[1] = France array[2] = Europe A simple implementation is preferable; speed does not matter. How can I do it?
IFS=', ' read -r -a array <<< "$string" Note that the characters in $IFS are treated individually as separators so that in this case fields may be separated by either a comma or a space rather than the sequence of the two characters. Interestingly though, empty fields aren't created when comma-space appears in the input because the space is treated specially. To access an individual element: echo "${array[0]}" To iterate over the elements: for element in "${array[@]}" do echo "$element" done To get both the index and the value: for index in "${!array[@]}" do echo "$index ${array[index]}" done The last example is useful because Bash arrays are sparse. In other words, you can delete an element or add an element and then the indices are not contiguous. unset "array[1]" array[42]=Earth To get the number of elements in an array: echo "${#array[@]}" As mentioned above, arrays can be sparse so you shouldn't use the length to get the last element. Here's how you can in Bash 4.2 and later: echo "${array[-1]}" in any version of Bash (from somewhere after 2.05b): echo "${array[@]: -1:1}" Larger negative offsets select farther from the end of the array. Note the space before the minus sign in the older form. It is required.
Split
10,586,153
952
I have a comma-separated string that I want to convert into an array, so I can loop through it. Is there anything built-in to do this? For example, I have this string var str = "January,February,March,April,May,June,July,August,September,October,November,December"; Now I want to split this by the comma, and then store it in an array.
const array = str.split(','); MDN reference, mostly helpful for the possibly unexpected behavior of the limit parameter. (Hint: "a,b,c".split(",", 2) comes out to ["a", "b"], not ["a", "b,c"].)
Split
2,858,121
904
I've been using the Split() method to split strings, but this only appears to work if you are splitting a string by a character. Is there a way to split a string, with another string being the split by parameter? I've tried converting the splitter into a character array, with no luck. In other words, I'd like to split the string: THExxQUICKxxBROWNxxFOX by xx, and return an array with values: THE, QUICK, BROWN, FOX
In order to split by a string you'll have to use the string array overload. string data = "THExxQUICKxxBROWNxxFOX"; return data.Split(new string[] { "xx" }, StringSplitOptions.None);
Split
2,245,442
854
I think what I want to do is a fairly common task but I've found no reference on the web. I have text with punctuation, and I want a list of the words. "Hey, you - what are you doing here!?" should be ['hey', 'you', 'what', 'are', 'you', 'doing', 'here'] But Python's str.split() only works with one argument, so I have all words with the punctuation after I split with whitespace. Any ideas?
re.split() re.split(pattern, string[, maxsplit=0]) Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. (Incompatibility note: in the original Python 1.5 release, maxsplit was ignored. This has been fixed in later releases.) >>> re.split('\W+', 'Words, words, words.') ['Words', 'words', 'words', ''] >>> re.split('(\W+)', 'Words, words, words.') ['Words', ', ', 'words', ', ', 'words', '.', ''] >>> re.split('\W+', 'Words, words, words.', 1) ['Words', 'words, words.']
Split
1,059,559
842
Say I have a string here: var fullName: String = "First Last" I want to split the string based on whitespace and assign the values to their respective variables var fullNameArr = // something like: fullName.explode(" ") var firstName: String = fullNameArr[0] var lastName: String? = fullnameArr[1] Also, sometimes users might not have a last name.
Just call componentsSeparatedByString method on your fullName import Foundation var fullName: String = "First Last" let fullNameArr = fullName.componentsSeparatedByString(" ") var firstName: String = fullNameArr[0] var lastName: String = fullNameArr[1] Update for Swift 3+ import Foundation let fullName = "First Last" let fullNameArr = fullName.components(separatedBy: " ") let name = fullNameArr[0] let surname = fullNameArr[1]
Split
25,678,373
833
I found some answers online, but I have no experience with regular expressions, which I believe is what is needed here. I have a string that needs to be split by either a ';' or ', ' That is, it has to be either a semicolon or a comma followed by a space. Individual commas without trailing spaces should be left untouched Example string: "b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3], mesitylene [000108-67-8]; polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]" should be split into a list containing the following: ('b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3]' , 'mesitylene [000108-67-8]', 'polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]')
Luckily, Python has this built-in :) import re # Regex pattern splits on substrings "; " and ", " re.split('; |, ', string_to_split) Update: Following your comment: >>> string_to_split = 'Beautiful, is; better*than\nugly' >>> import re >>> re.split('; |, |\*|\n', string_to_split) ['Beautiful', 'is', 'better', 'than', 'ugly']
Split
4,998,629
794
How do I split a string with multiple separators in JavaScript? I'm trying to split on both commas and spaces, but AFAIK JavaScript's split() function only supports one separator.
Pass in a regexp as the parameter: js> "Hello awesome, world!".split(/[\s,]+/) Hello,awesome,world! Edited to add: You can get the last element by selecting the length of the array minus 1: >>> bits = "Hello awesome, world!".split(/[\s,]+/) ["Hello", "awesome", "world!"] >>> bit = bits[bits.length - 1] "world!" ... and if the pattern doesn't match: >>> bits = "Hello awesome, world!".split(/foo/) ["Hello awesome, world!"] >>> bits[bits.length - 1] "Hello awesome, world!"
Split
650,022
767
How can you switch your current windows from horizontal split to vertical split and vice versa in Vim? I did that a moment ago by accident but I cannot find the key again.
Vim mailing list says (re-formatted for better readability): To change two vertically split windows to horizonally split Ctrl-w t Ctrl-w K Horizontally to vertically: Ctrl-w t Ctrl-w H Explanations: Ctrl-w t makes the first (topleft) window current Ctrl-w K moves the current window to full-width at the very top Ctrl-w H moves the current window to full-height at far left Note that the t is lowercase, and the K and H are uppercase. Also, with only two windows, it seems like you can drop the Ctrl-w t part because if you're already in one of only two windows, what's the point of making it current?
Split
1,269,603
710
I am parsing a string in C++ using the following: using namespace std; string parsed,input="text to be parsed"; stringstream input_stringstream(input); if (getline(input_stringstream,parsed,' ')) { // do some processing. } Parsing with a single char delimiter is fine. But what if I want to use a string as delimiter. Example: I want to split: scott>=tiger with >= as delimiter so that I can get scott and tiger.
You can use the std::string::find() function to find the position of your string delimiter, then use std::string::substr() to get a token. Example: std::string s = "scott>=tiger"; std::string delimiter = ">="; std::string token = s.substr(0, s.find(delimiter)); // token is "scott" The find(const string& str, size_t pos = 0) function returns the position of the first occurrence of str in the string, or npos if the string is not found. The substr(size_t pos = 0, size_t n = npos) function returns a substring of the object, starting at position pos and of length npos. If you have multiple delimiters, after you have extracted one token, you can remove it (delimiter included) to proceed with subsequent extractions (if you want to preserve the original string, just use s = s.substr(pos + delimiter.length());): s.erase(0, s.find(delimiter) + delimiter.length()); This way you can easily loop to get each token. Complete Example std::string s = "scott>=tiger>=mushroom"; std::string delimiter = ">="; size_t pos = 0; std::string token; while ((pos = s.find(delimiter)) != std::string::npos) { token = s.substr(0, pos); std::cout << token << std::endl; s.erase(0, pos + delimiter.length()); } std::cout << s << std::endl; Output: scott tiger mushroom
Split
14,265,581
687
Is there any built-in method in Java which allows us to convert comma separated String to some container (e.g array, List or Vector)? Or do I need to write custom code for that? String commaSeparated = "item1 , item2 , item3"; List<String> items = //method that converts above string into list??
Convert comma separated String to List List<String> items = Arrays.asList(str.split("\\s*,\\s*")); The above code splits the string on a delimiter defined as: zero or more whitespace, a literal comma, zero or more whitespace which will place the words into the list and collapse any whitespace between the words and commas. Please note that this returns simply a wrapper on an array: you CANNOT for example .remove() from the resulting List. For an actual ArrayList you must further use new ArrayList<String>.
Split
7,488,643
663
I'm looking for the Python equivalent of String str = "many fancy word \nhello \thi"; String whiteSpaceRegex = "\\s"; String[] words = str.split(whiteSpaceRegex); ["many", "fancy", "word", "hello", "hi"]
The str.split() method without an argument splits on whitespace: >>> "many fancy word \nhello \thi".split() ['many', 'fancy', 'word', 'hello', 'hi']
Split
8,113,782
657
How do I split a sentence and store each word in a list? e.g. "these are words" ⟶ ["these", "are", "words"] To split on other delimiters, see Split a string by a delimiter in python. To split into individual characters, see How do I split a string into a list of characters?.
Given a string sentence, this stores each word in a list called words: words = sentence.split()
Split
743,806
654
I have this string 'john smith~123 Street~Apt 4~New York~NY~12345' Using JavaScript, what is the fastest way to parse this into var name = "john smith"; var street= "123 Street"; //etc...
With JavaScript’s String.prototype.split function: var input = 'john smith~123 Street~Apt 4~New York~NY~12345'; var fields = input.split('~'); var name = fields[0]; var street = fields[1]; // etc.
Split
96,428
635
What regex pattern would need I to pass to java.lang.String.split() to split a String into an Array of substrings using all whitespace characters (' ', '\t', '\n', etc.) as delimiters?
Something in the lines of myString.split("\\s+"); This groups all white spaces as a delimiter. So if I have the string: "Hello[space character][tab character]World" This should yield the strings "Hello" and "World" and omit the empty space between the [space] and the [tab]. As VonC pointed out, the backslash should be escaped, because Java would first try to escape the string to a special character, and send that to be parsed. What you want, is the literal "\s", which means, you need to pass "\\s". It can get a bit confusing. The \\s is equivalent to [ \\t\\n\\x0B\\f\\r].
Split
225,337
594
Using SQL Server, how do I split a string so I can access item x? Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?
I don't believe SQL Server has a built-in split function, so other than a UDF, the only other answer I know is to hijack the PARSENAME function: SELECT PARSENAME(REPLACE('Hello John Smith', ' ', '.'), 2) PARSENAME takes a string and splits it on the period character. It takes a number as its second argument, and that number specifies which segment of the string to return (working from back to front). SELECT PARSENAME(REPLACE('Hello John Smith', ' ', '.'), 3) --return Hello Obvious problem is when the string already contains a period. I still think using a UDF is the best way...any other suggestions?
Split
2,647
533
What would be the best way to split a string on the first occurrence of a delimiter? For example: "123mango abcd mango kiwi peach" splitting on the first mango to get: " abcd mango kiwi peach" To split on the last occurrence instead, see Partition string in Python and get value of last segment after colon.
From the docs: str.split([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 (thus, the list will have at most maxsplit+1 elements). s.split('mango', 1)[1]
Split
6,903,557
502
Why does the second line of this code throw ArrayIndexOutOfBoundsException? String filename = "D:/some folder/001.docx"; String extensionRemoved = filename.split(".")[0]; While this works: String driveLetter = filename.split("/")[0]; I use Java 7.
You need to escape the dot if you want to split on a literal dot: String extensionRemoved = filename.split("\\.")[0]; Otherwise you are splitting on the regex ., which means "any character". Note the double backslash needed to create a single backslash in the regex. You're getting an ArrayIndexOutOfBoundsException because your input string is just a dot, ie ".", which is an edge case that produces an empty array when split on dot; split(regex) removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you're left with an empty array. To avoid getting an ArrayIndexOutOfBoundsException for this edge case, use the overloaded version of split(regex, limit), which has a second parameter that is the size limit for the resulting array. When limit is negative, the behaviour of removing trailing blanks from the resulting array is disabled: ".".split("\\.", -1) // returns an array of two blanks, ie ["", ""] ie, when filename is just a dot ".", calling filename.split("\\.", -1)[0] will return a blank, but calling filename.split("\\.")[0] will throw an ArrayIndexOutOfBoundsException.
Split
14,833,008
483
Java has a convenient split method: String str = "The quick brown fox"; String[] results = str.split(" "); Is there an easy way to do this in C++?
The Boost tokenizer class can make this sort of thing quite simple: #include <iostream> #include <string> #include <boost/foreach.hpp> #include <boost/tokenizer.hpp> using namespace std; using namespace boost; int main(int, char**) { string text = "token, test string"; char_separator<char> sep(", "); tokenizer< char_separator<char> > tokens(text, sep); BOOST_FOREACH (const string& t, tokens) { cout << t << "." << endl; } } Updated for C++11: #include <iostream> #include <string> #include <boost/tokenizer.hpp> using namespace std; using namespace boost; int main(int, char**) { string text = "token, test string"; char_separator<char> sep(", "); tokenizer<char_separator<char>> tokens(text, sep); for (const auto& t : tokens) { cout << t << "." << endl; } }
Split
53,849
478
I'm trying to split text in a JTextArea using a regex to split the String by \n However, this does not work and I also tried by \r\n|\r|n and many other combination of regexes. Code: public void insertUpdate(DocumentEvent e) { String split[], docStr = null; Document textAreaDoc = (Document)e.getDocument(); try { docStr = textAreaDoc.getText(textAreaDoc.getStartPosition().getOffset(), textAreaDoc.getEndPosition().getOffset()); } catch (BadLocationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } split = docStr.split("\\n"); }
This should cover you: String lines[] = string.split("\\r?\\n"); There's only really two newlines (UNIX and Windows) that you need to worry about.
Split
454,908
467
I have some python code that splits on comma, but doesn't strip the whitespace: >>> string = "blah, lots , of , spaces, here " >>> mylist = string.split(',') >>> print mylist ['blah', ' lots ', ' of ', ' spaces', ' here '] I would rather end up with whitespace removed like this: ['blah', 'lots', 'of', 'spaces', 'here'] I am aware that I could loop through the list and strip() each item but, as this is Python, I'm guessing there's a quicker, easier and more elegant way of doing it.
Use list comprehension -- simpler, and just as easy to read as a for loop. my_string = "blah, lots , of , spaces, here " result = [x.strip() for x in my_string.split(',')] # result is ["blah", "lots", "of", "spaces", "here"] See: Python docs on List Comprehension A good 2 second explanation of list comprehension.
Split
4,071,396
463
I need to split my String by spaces. For this I tried: str = "Hello I'm your String"; String[] splited = str.split(" "); But it doesn't seem to work.
What you have should work. If, however, the spaces provided are defaulting to... something else? You can use the whitespace regex: str = "Hello I'm your String"; String[] splited = str.split("\\s+"); This will cause any number of consecutive spaces to split your string into tokens.
Split
7,899,525
451
What's the recommended Python idiom for splitting a string on the last occurrence of the delimiter in the string? example: # instead of regular split >> s = "a,b,c,d" >> s.split(",") >> ['a', 'b', 'c', 'd'] # ..split only on last occurrence of ',' in string: >>> s.mysplit(s, -1) >>> ['a,b,c', 'd'] mysplit takes a second argument that is the occurrence of the delimiter to be split. Like in regular list indexing, -1 means the last from the end. How can this be done?
Use .rsplit() or .rpartition() instead: s.rsplit(',', 1) s.rpartition(',') str.rsplit() lets you specify how many times to split, while str.rpartition() only splits once but always returns a fixed number of elements (prefix, delimiter & postfix) and is faster for the single split case. Demo: >>> s = "a,b,c,d" >>> s.rsplit(',', 1) ['a,b,c', 'd'] >>> s.rsplit(',', 2) ['a,b', 'c', 'd'] >>> s.rpartition(',') ('a,b,c', ',', 'd') Both methods start splitting from the right-hand-side of the string; by giving str.rsplit() a maximum as the second argument, you get to split just the right-hand-most occurrences. If you only need the last element, but there is a chance that the delimiter is not present in the input string or is the very last character in the input, use the following expressions: # last element, or the original if no `,` is present or is the last character s.rsplit(',', 1)[-1] or s s.rpartition(',')[-1] or s If you need the delimiter gone even when it is the last character, I'd use: def last(string, delimiter): """Return the last element from string, after the delimiter If string ends in the delimiter or the delimiter is absent, returns the original string without the delimiter. """ prefix, delim, last = string.rpartition(delimiter) return last if (delim and last) else prefix This uses the fact that string.rpartition() returns the delimiter as the second argument only if it was present, and an empty string otherwise.
Split
15,012,228
413
Suppose I have the string 1:2:3:4:5 and I want to get its last field (5 in this case). How do I do that using Bash? I tried cut, but I don't know how to specify the last field with -f.
You can use string operators: $ foo=1:2:3:4:5 $ echo ${foo##*:} 5 This trims everything from the front until a ':', greedily. ${foo <-- from variable foo ## <-- greedy front trim * <-- matches anything : <-- until the last ':' }
Split
3,162,385
402
I am trying to split the Value using a separator. But I am finding the surprising results String data = "5|6|7||8|9||"; String[] split = data.split("\\|"); System.out.println(split.length); I am expecting to get 8 values. [5,6,7,EMPTY,8,9,EMPTY,EMPTY] But I am getting only 6 values. Any idea and how to fix. No matter EMPTY value comes at anyplace, it should be in array.
split(delimiter) by default removes trailing empty strings from result array. To turn this mechanism off we need to use overloaded version of split(delimiter, limit) with limit set to negative value like String[] split = data.split("\\|", -1); Little more details: split(regex) internally returns result of split(regex, 0) and in documentation of this method you can find (emphasis mine) The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded. Exception: It is worth mentioning that removing trailing empty string makes sense only if such empty strings were created by the split mechanism. So for "".split(anything) since we can't split "" farther we will get as result [""] array. It happens because split didn't happen here, so "" despite being empty and trailing represents original string, not empty string which was created by splitting process.
Split
14,602,062
386
I have a Pandas DataFrame with one column: import pandas as pd df = pd.DataFrame({"teams": [["SF", "NYG"] for _ in range(7)]}) teams 0 [SF, NYG] 1 [SF, NYG] 2 [SF, NYG] 3 [SF, NYG] 4 [SF, NYG] 5 [SF, NYG] 6 [SF, NYG] How can split this column of lists into two columns? Desired result: team1 team2 0 SF NYG 1 SF NYG 2 SF NYG 3 SF NYG 4 SF NYG 5 SF NYG 6 SF NYG
You can use the DataFrame constructor with lists created by to_list: import pandas as pd d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'], ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]} df2 = pd.DataFrame(d1) print (df2) teams 0 [SF, NYG] 1 [SF, NYG] 2 [SF, NYG] 3 [SF, NYG] 4 [SF, NYG] 5 [SF, NYG] 6 [SF, NYG] df2[['team1','team2']] = pd.DataFrame(df2.teams.tolist(), index= df2.index) print (df2) teams team1 team2 0 [SF, NYG] SF NYG 1 [SF, NYG] SF NYG 2 [SF, NYG] SF NYG 3 [SF, NYG] SF NYG 4 [SF, NYG] SF NYG 5 [SF, NYG] SF NYG 6 [SF, NYG] SF NYG And for a new DataFrame: df3 = pd.DataFrame(df2['teams'].to_list(), columns=['team1','team2']) print (df3) team1 team2 0 SF NYG 1 SF NYG 2 SF NYG 3 SF NYG 4 SF NYG 5 SF NYG 6 SF NYG A solution with apply(pd.Series) is very slow: #7k rows df2 = pd.concat([df2]*1000).reset_index(drop=True) In [121]: %timeit df2['teams'].apply(pd.Series) 1.79 s ± 52.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [122]: %timeit pd.DataFrame(df2['teams'].to_list(), columns=['team1','team2']) 1.63 ms ± 54.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Split
35,491,274
383
Assume I've got some arbitrary layout of splits in vim. ____________________ | one | two | | | | | |______| | | three| | | | |___________|______| Is there a way to swap one and two and maintain the same layout? It's simple in this example, but I'm looking for a solution that will help for more complex layouts. UPDATE: I guess I should be more clear. My previous example was a simplification of the actual use-case. With an actual instance: How could I swap any two of those splits, maintaining the same layout? Update! 3+ years later... I put sgriffin's solution in a Vim plugin you can install with ease! Install it with your favorite plugin manager and give it a try: WindowSwap.vim
Starting with this: ____________________ | one | two | | | | | |______| | | three| | | | |___________|______| Make 'three' the active window, then issue the command ctrl+w J. This moves the current window to fill the bottom of the screen, leaving you with: ____________________ | one | two | | | | |___________|______| | three | | | |__________________| Now make either 'one' or 'two' the active window, then issue the command ctrl+w r. This 'rotates' the windows in the current row, leaving you with: ____________________ | two | one | | | | |___________|______| | three | | | |__________________| Now make 'two' the active window, and issue the command ctrl+w H. This moves the current window to fill the left of the screen, leaving you with: ____________________ | two | one | | | | | |______| | | three| | | | |___________|______| As you can see, the manouevre is a bit of a shuffle. With 3 windows, it's a bit like one of those 'tile game' puzzles. I don't recommand trying this if you have 4 or more windows - you'd be better off closing them then opening them again in the desired positions. I made a screencast demonstrating how to work with split windows in Vim.
Split
2,586,984
362
I have a multi-line string that I want to do an operation on each line, like so: inputString = """Line 1 Line 2 Line 3""" I want to iterate on each line: for line in inputString: doStuff()
inputString.splitlines() Will give you a list with each item, the splitlines() method is designed to split each line into a list element.
Split
172,439
357
I have a string containing many words with at least one space between each two. How can I split the string into individual words so I can loop through them? The string is passed as an argument. E.g. ${2} == "cat cat file". How can I loop through it? Also, how can I check if a string contains spaces?
I like the conversion to an array, to be able to access individual elements: sentence="this is a story" stringarray=($sentence) now you can access individual elements directly (it starts with 0): echo ${stringarray[0]} or convert back to string in order to loop: for i in "${stringarray[@]}" do : # do whatever on $i done Of course looping through the string directly was answered before, but that answer had the the disadvantage to not keep track of the individual elements for later use: for i in $sentence do : # do whatever on $i done See also Bash Array Reference.
Split
1,469,849
355
I'd like to take data of the form before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2')) attr type 1 1 foo_and_bar 2 30 foo_and_bar_2 3 4 foo_and_bar 4 6 foo_and_bar_2 and use split() on the column "type" from above to get something like this: attr type_1 type_2 1 1 foo bar 2 30 foo bar_2 3 4 foo bar 4 6 foo bar_2 I came up with something unbelievably complex involving some form of apply that worked, but I've since misplaced that. It seemed far too complicated to be the best way. I can use strsplit as below, but then unclear how to get that back into 2 columns in the data frame. > strsplit(as.character(before$type),'_and_') [[1]] [1] "foo" "bar" [[2]] [1] "foo" "bar_2" [[3]] [1] "foo" "bar" [[4]] [1] "foo" "bar_2" Thanks for any pointers. I've not quite groked R lists just yet.
Use stringr::str_split_fixed library(stringr) str_split_fixed(before$type, "_and_", 2)
Split
4,350,440
343
I have a SQL Table like this: SomeID OtherID Data abcdef-..... cdef123-... 18,20,22 abcdef-..... 4554a24-... 17,19 987654-..... 12324a2-... 13,19,20 Is there a query where I can perform a query like SELECT OtherID, SplitData WHERE SomeID = 'abcdef-.......' that returns individual rows, like this: OtherID SplitData cdef123-... 18 cdef123-... 20 cdef123-... 22 4554a24-... 17 4554a24-... 19 Basically split my data at the comma into individual rows? I am aware that storing a comma-separated string into a relational database sounds dumb, but the normal use case in the consumer application makes that really helpful. I don't want to do the split in the application as I need paging, so I wanted to explore options before refactoring the whole app. It's SQL Server 2008 (non-R2).
You can use the wonderful recursive functions from SQL Server: Sample table: CREATE TABLE Testdata ( SomeID INT, OtherID INT, String VARCHAR(MAX) ); INSERT Testdata SELECT 1, 9, '18,20,22'; INSERT Testdata SELECT 2, 8, '17,19'; INSERT Testdata SELECT 3, 7, '13,19,20'; INSERT Testdata SELECT 4, 6, ''; INSERT Testdata SELECT 9, 11, '1,2,3,4'; The query WITH tmp(SomeID, OtherID, DataItem, String) AS ( SELECT SomeID, OtherID, LEFT(String, CHARINDEX(',', String + ',') - 1), STUFF(String, 1, CHARINDEX(',', String + ','), '') FROM Testdata UNION all SELECT SomeID, OtherID, LEFT(String, CHARINDEX(',', String + ',') - 1), STUFF(String, 1, CHARINDEX(',', String + ','), '') FROM tmp WHERE String > '' ) SELECT SomeID, OtherID, DataItem FROM tmp ORDER BY SomeID; -- OPTION (maxrecursion 0) -- normally recursion is limited to 100. If you know you have very long -- strings, uncomment the option Output SomeID | OtherID | DataItem --------+---------+---------- 1 | 9 | 18 1 | 9 | 20 1 | 9 | 22 2 | 8 | 17 2 | 8 | 19 3 | 7 | 13 3 | 7 | 19 3 | 7 | 20 4 | 6 | 9 | 11 | 1 9 | 11 | 2 9 | 11 | 3 9 | 11 | 4
Split
5,493,510
338
I am attempting to split a list into a series of smaller lists. My Problem: My function to split lists doesn't split them into lists of the correct size. It should split them into lists of size 30 but instead it splits them into lists of size 114? How can I make my function split a list into X number of Lists of size 30 or less? public static List<List<float[]>> splitList(List <float[]> locations, int nSize=30) { List<List<float[]>> list = new List<List<float[]>>(); for (int i=(int)(Math.Ceiling((decimal)(locations.Count/nSize))); i>=0; i--) { List <float[]> subLocat = new List <float[]>(locations); if (subLocat.Count >= ((i*nSize)+nSize)) subLocat.RemoveRange(i*nSize, nSize); else subLocat.RemoveRange(i*nSize, subLocat.Count-(i*nSize)); Debug.Log ("Index: "+i.ToString()+", Size: "+subLocat.Count.ToString()); list.Add (subLocat); } return list; } If I use the function on a list of size 144 then the output is: Index: 4, Size: 120 Index: 3, Size: 114 Index: 2, Size: 114 Index: 1, Size: 114 Index: 0, Size: 114
I would suggest to use this extension method to chunk the source list to the sub-lists by specified chunk size: /// <summary> /// Helper methods for the lists. /// </summary> public static class ListExtensions { public static List<List<T>> ChunkBy<T>(this List<T> source, int chunkSize) { return source .Select((x, i) => new { Index = i, Value = x }) .GroupBy(x => x.Index / chunkSize) .Select(x => x.Select(v => v.Value).ToList()) .ToList(); } } For example, if you chunk the list of 18 items by 5 items per chunk, it gives you the list of 4 sub-lists with the following items inside: 5-5-5-3. NOTE: at the upcoming improvements to LINQ in .NET 6 chunking will come out of the box like this: const int PAGE_SIZE = 5; IEnumerable<Movie[]> chunks = movies.Chunk(PAGE_SIZE);
Split
11,463,734
336
I would like to split a very large string (let's say, 10,000 characters) into N-size chunks. What would be the best way in terms of performance to do this? For instance: "1234567890" split by 2 would become ["12", "34", "56", "78", "90"]. Would something like this be possible using String.prototype.match and if so, would that be the best way to do it in terms of performance?
You can do something like this: "1234567890".match(/.{1,2}/g); // Results in: ["12", "34", "56", "78", "90"] The method will still work with strings whose size is not an exact multiple of the chunk-size: "123456789".match(/.{1,2}/g); // Results in: ["12", "34", "56", "78", "9"] In general, for any string out of which you want to extract at-most n-sized substrings, you would do: str.match(/.{1,n}/g); // Replace n with the size of the substring If your string can contain newlines or carriage returns, you would do: str.match(/(.|[\r\n]){1,n}/g); // Replace n with the size of the substring As far as performance, I tried this out with approximately 10k characters and it took a little over a second on Chrome. YMMV. This can also be used in a reusable function: function chunkString(str, length) { return str.match(new RegExp('.{1,' + length + '}', 'g')); }
Split
7,033,639
319
As the title says, I've got a string and I want to split into segments of n characters. For example: var str = 'abcdefghijkl'; after some magic with n=3, it will become var arr = ['abc','def','ghi','jkl']; Is there a way to do this?
var str = 'abcdefghijkl'; console.log(str.match(/.{1,3}/g)); Note: Use {1,3} instead of just {3} to include the remainder for string lengths that aren't a multiple of 3, e.g: console.log("abcd".match(/.{1,3}/g)); // ["abc", "d"] A couple more subtleties: If your string may contain newlines (which you want to count as a character rather than splitting the string), then the . won't capture those. Use /[\s\S]{1,3}/ instead. (Thanks @Mike). If your string is empty, then match() will return null when you may be expecting an empty array. Protect against this by appending || []. So you may end up with: var str = 'abcdef \t\r\nghijkl'; var parts = str.match(/[\s\S]{1,3}/g) || []; console.log(parts); console.log(''.match(/[\s\S]{1,3}/g) || []);
Split
6,259,515
318
I have this string: "My name is Marco and I'm from Italy" I'd like to split it, with the delimiter being is Marco and, so I should get an array with My name at [0] and I'm from Italy at [1]. How can I do it with C#? I tried with: .Split("is Marco and") But it wants only a single char.
string[] tokens = str.Split(new[] { "is Marco and" }, StringSplitOptions.None); If you have a single character delimiter (like for instance ,), you can reduce that to (note the single quotes): string[] tokens = str.Split(',');
Split
8,928,601
315
I flubbed up my history and want to do some changes to it. Problem is, I have a commit with two unrelated changes, and this commit is surrounded by some other changes in my local (non-pushed) history. I want to split up this commit before I push it out, but most of the guides I'm seeing have to do with splitting up your most recent commit, or uncommitted local changes. Is it feasible to do this to a commit that is buried in history a bit, without having to "re-do" my commits since then?
There is a guide to splitting commits in the rebase manpage. The quick summary is: Perform an interactive rebase including the target commit (e.g. git rebase -i <commit-to-split>^ branch) and mark it to be edited. When the rebase reaches that commit, use git reset HEAD^ to reset to before the commit, but keep your work tree intact. Incrementally add changes and commit them, making as many commits as desired. add -p can be useful to add only some of the changes in a given file. Use commit -c ORIG_HEAD if you want to re-use the original commit message for a certain commit. If you want to test what you're committing (good idea!) use git stash to hide away the part you haven't committed (or stash --keep-index before you even commit it), test, then git stash pop to return the rest to the work tree. Keep making commits until you get all modifications committed, i.e. have a clean work tree. Run git rebase --continue to proceed applying the commits after the now-split commit.
Split
4,307,095
304
I have split my windows horizontally. Now how can I return to normal mode, i.e. no split window just one window without cancelling all of my open windows. I have 5 and do not want to "quit", just want to get out of split window.
Press Control+w, then hit q to close each window at a time. Update: Also consider eckes answer which may be more useful to you, involving :on (read below) if you don't want to do it one window at a time.
Split
4,809,729
302
I have a list that looks like this: my_list = [('1','a'),('2','b'),('3','c'),('4','d')] I want to separate the list in 2 lists. list1 = ['1','2','3','4'] list2 = ['a','b','c','d'] I can do it for example with: list1 = [] list2 = [] for i in list: list1.append(i[0]) list2.append(i[1]) But I want to know if there is a more elegant solution.
>>> source_list = [('1','a'),('2','b'),('3','c'),('4','d')] >>> list1, list2 = zip(*source_list) >>> list1 ('1', '2', '3', '4') >>> list2 ('a', 'b', 'c', 'd') Edit: Note that zip(*iterable) is its own inverse: >>> list(source_list) == zip(*zip(*source_list)) True When unpacking into two lists, this becomes: >>> list1, list2 = zip(*source_list) >>> list(source_list) == zip(list1, list2) True Addition suggested by rocksportrocker.
Split
7,558,908
287
I need to get the last element of a split array with multiple separators. The separators are commas and space. If there are no separators it should return the original string. If the string is "how,are you doing, today?" it should return "today?" If the input were "hello" the output should be "hello". How can I do this in JavaScript?
There's a one-liner for everything. :) var output = input.split(/[, ]+/).pop();
Split
651,563
280
I've recently discovered git's patch option to the add command, and I must say it really is a fantastic feature. I also discovered that a large hunk could be split into smaller hunks by hitting the s key, which adds to the precision of the commit. But what if I want even more precision, if the split hunk is not small enough? For example, consider this already split hunk: @@ -34,12 +34,7 @@ width: 440px; } -/*#field_teacher_id { - display: block; -} */ - -form.table-form #field_teacher + label, -form.table-form #field_producer_distributor + label { +#user-register form.table-form .field-type-checkbox label { width: 300px; } How can I add the CSS comment removal only to the next commit ? The s option is not available anymore!
If you're using git add -p and even after splitting with s, you don't have a small enough change, you can use e to edit the patch directly. This can be a little confusing, but if you carefully follow the instructions in the editor window that will be opened up after pressing e then you'll be fine. In the case you've quoted, you would want to replace the - with a space at the beginning of these lines: - -form.table-form #field_teacher + label, -form.table-form #field_producer_distributor + label { ... and delete the following line, i.e. the one that begins with +. If you then save and exit your editor, just the removal of the CSS comment will be staged.
Split
6,276,752
258
I have a string that has numbers string sNumbers = "1,2,3,4,5"; I can split it then convert it to List<int> sNumbers.Split( new[] { ',' } ).ToList<int>(); How can I convert string array to integer list? So that I'll be able to convert string[] to IEnumerable
var numbers = sNumbers?.Split(',')?.Select(Int32.Parse)?.ToList(); Recent versions of C# (v6+) allow you to do null checks in-line using the null-conditional operator
Split
911,717
258
Consider the following input string: 'MATCHES__STRING' I want to split that string wherever the "delimiter" __ occurs. This should output a list of strings: ['MATCHES', 'STRING'] To split on whitespace, see How do I split a string into a list of words?. To extract everything before the first delimiter, see Splitting on first occurrence. To extract everything before the last delimiter, see Partition string in Python and get value of last segment after colon.
Use the str.split method: >>> "MATCHES__STRING".split("__") ['MATCHES', 'STRING']
Split
3,475,251
257
I have a String with an unknown length that looks something like this "dog, cat, bear, elephant, ..., giraffe" What would be the optimal way to divide this string at the commas so each word could become an element of an ArrayList? For example List<String> strings = new ArrayList<Strings>(); // Add the data here so strings.get(0) would be equal to "dog", // strings.get(1) would be equal to "cat" and so forth.
You could do this: String str = "..."; List<String> elephantList = Arrays.asList(str.split(",")); Basically the .split() method will split the string according to (in this case) delimiter you are passing and will return an array of strings. However, you seem to be after a List of Strings rather than an array, so the array must be turned into a list by using the Arrays.asList() utility. Just as an FYI you could also do something like so: String str = "..."; ArrayList<String> elephantList = new ArrayList<>(Arrays.asList(str.split(",")); But it is usually better practice to program to an interface rather than to an actual concrete implementation, so I would recommend the 1st option.
Split
10,631,715
252
I have a string "1,2,3,4" and I'd like to convert it into an array: [1,2,3,4] How?
>> "1,2,3,4".split(",") => ["1", "2", "3", "4"] Or for integers: >> "1,2,3,4".split(",").map { |s| s.to_i } => [1, 2, 3, 4] Or for later versions of ruby (>= 1.9 - as pointed out by Alex): >> "1,2,3,4".split(",").map(&:to_i) => [1, 2, 3, 4]
Split
975,769
243
I am looking for a way to easily split a python list in half. So that if I have an array: A = [0,1,2,3,4,5] I would be able to get: B = [0,1,2] C = [3,4,5]
A = [1,2,3,4,5,6] B = A[:len(A)//2] C = A[len(A)//2:] If you want a function: def split_list(a_list): half = len(a_list)//2 return a_list[:half], a_list[half:] A = [1,2,3,4,5,6] B, C = split_list(A)
Split
752,308
223
I have prepared a simple code snippet in order to separate the erroneous portion from my web application. public class Main { public static void main(String[] args) throws IOException { System.out.print("\nEnter a string:->"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String temp = br.readLine(); String words[] = temp.split("."); for (int i = 0; i < words.length; i++) { System.out.println(words[i] + "\n"); } } } I have tested it while building a web application JSF. I just want to know why in the above code temp.split(".") does not work. The statement, System.out.println(words[i]+"\n"); displays nothing on the console means that it doesn't go through the loop. When I change the argument of the temp.split() method to other characters, It works just fine as usual. What might be the problem?
java.lang.String.split splits on regular expressions, and . in a regular expression means "any character". Try temp.split("\\.").
Split
7,935,858
216