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 |
|---|---|---|---|---|
Google Labs Browser Size
I've always preferred fixed-width layouts over fluid-width layouts, one of the main reasons is that I'm able to better understand how the whole picture will be without having to worry about the screen resolution.
But now the "picture" has changed, there is a high discrepancy between the lowest... |
leaving 980 pixels unused in a 24" monitor just seems plain odd not to say wrong
I’d disagree here. If you’ve got a monitor with that high a resolution, you’re probably not running with a maximised browser window. And even if you are, are you really fussed that the content’s all in a fixed area in the middle? Really?... | Fluid | 1,963,041 | 10 |
I have a fluid template, from where I call an often used snippet (called "partial"):
Template:
<f:render partial="fbLikeBox" arguments="{settings}"/>
Partial fbLikeBox.html:
<div id="fb-root"></div><script src="http://connect.facebook.net/xxxxxxxx"></script>
<fb:like href="{settings.baseURL}/details/?guide_uid={audiog... | Starting with TYPO3 4.6, you could just use
<f:render partial="fbLikeBox" arguments="{_all}" />
The {_all} will simple make sure all variables currently available in your template, are available in the partial.
| Fluid | 7,668,620 | 10 |
I want to compare two dates. I want to make a condition which checks if the date in my database is older than the date in two days.
Here are my two variables:
{<f:format.date format="d.m.Y">+2 days</f:format.date>}
{<f:format.date format="d.m.Y">{day.valid}</f:format.date>}
I want to solve this in the template, not i... | Assign your date to variable »yourdate«.
<f:if condition="{f:format.date(date: '+2 days', format: 'Y-m-d')} < {f:format.date(date: yourdate, format: 'Y-m-d')}">
<f:then>
yourdate is smaller than now + 2 days.
</f:then>
<f:else>
yourdate is greater than or equal to now + 2 days.
</f:else>
... | Fluid | 15,929,181 | 10 |
I opted to use the Raphaël javascript library for its extensive browser support, but I'm having trouble getting the SVG to display properly in any browser, except for Chrome and Firefox. I've been scratching my head over this for a while now and would love to hear how I could make SVG work in a responsive layout.
Chrom... | You can add these properties to your SVG tag - <svg viewBox="0 0 300 329" preserveAspectRatio="xMidYMid meet"> to preserve aspect ratio.
Taken from the article I read that in...
To preserve the aspect ratio of the containing element and ensure that
is scales uniformly, we include the viewbox and preserveAspectRatio... | Fluid | 16,983,749 | 10 |
plugin.tx_xxx {
setting {
storagePid = 23
}
}
I want this TYPO3 settings in utility file.
Please help me.
| The above method works only in controller or services class try below it will work in any PHP files in Extension.
$objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\Extbase\\Object\\ObjectManager');
$configurationManager = $objectManager->get('TYPO3\\CMS\\Extbase\\Configuration\\Configur... | Fluid | 30,839,907 | 10 |
I am trying to find the best way to convert map[string]string to type string.
I tried converting to JSON with marshalling to keep the format and then converting back to a string, but this was not successful.
More specifically, I am trying to convert a map containing keys and values to a string to accommodate Environmen... | You need some key=value pair on each line representing one map entry, and you need quotes around the values:
package main
import (
"bytes"
"fmt"
)
func createKeyValuePairs(m map[string]string) string {
b := new(bytes.Buffer)
for key, value := range m {
fmt.Fprintf(b, "%s=\"%s\"\n", key, value)... | Nomad | 48,149,969 | 24 |
nomad docker image will be fetched from Docker Hub. But I have want use some local images. How can I use theme. (I dont want to use private repo)
Example I want to use local image test
> docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
test ... | I'm not sure if this can be treated as an answer or a "hack".
But if you want Nomad to use docker image that is already present on a node the image MUST NOT be tagged latest.
For testing I tag my images as IMAGE:local. This way Nomad uses it if present, pulls it from remote if not.
| Nomad | 56,342,572 | 10 |
Nomad has three different ways to map ports:
Network stanza under group level
Network stanza under config -> resources level
port_map stanza under config level
What is the difference and when I should use which?
|
First of all port_map is
deprecated,
so you shouldn't be using that as part of task driver configuration.
Up until Nomad 0.12, ports could be specified in a task's resource stanza and set
using the docker port_map field. As more features have been added to the group
network resource allocation, task based network res... | Nomad | 63,601,913 | 10 |
According to Prefect's Hybrid Execution model, Agents "watch for any scheduled flow runs and execute them accordingly on your infrastructure," while Executors "are responsible for actually running tasks [...] users can submit functions and wait for their results."
While this makes some sense from a high-level design pe... | Agents represent the local infrastructure that a Flow can and should execute on, as specified by that Flow's RunConfig. If a Flow should only run on Docker (or Kubernetes, or ECS, or whatever else) then the Flow Run is served by that Agent only. Agents can serve multiple Flows, so long as those Flows are all supported ... | Prefect | 66,959,695 | 13 |
I'm following the Prefect tutorial available at: https://docs.prefect.io/core/tutorial/01-etl-before-prefect.html.
The code can be downloaded from the git: https://github.com/PrefectHQ/prefect/tree/master/examples/tutorial
The tutorials have a dependency to aircraftlib which is a directory under tutorials. I can execut... | This depends partially on the type of Flow Storage and Agent you are using. Since you are running with Prefect Server, I assume you are using Local Storage + a Local Agent; in this case, you need to make sure the aircraftlib directory is on your local importable Python PATH. There are a few ways of doing this:
run y... | Prefect | 63,881,231 | 10 |
I'm running Kubernetes 1.11, and trying to configure the Kubernetes cluster to check a local name server first. I read the instructions on the Kubernetes site for customizing CoreDNS, and used the Dashboard to edit the system ConfigMap for CoreDNS. The resulting corefile value is:
.:53 {
errors
health
kuber... | One way to apply Configmap changes would be to redeploy CoreDNS pods:
kubectl rollout restart -n kube-system deployment/coredns
| CoreDNS | 53,498,438 | 15 |
What happened
Resolving an external domain from within a pod fails with SERVFAIL message. In the logs, i/o timeout error is mentioned.
What I expected to happen
External domains should be successfully resolved from the pods.
How to reproduce it
apiVersion: v1
kind: Pod
metadata:
name: dnsutils
namespace: default
sp... | Finally found the solution which was the combination of two changes. After applying both changes, my pods could finally resolve addresses properly.
Kubelet configuration
Based on known issues, change resolv-conf path for Kubelet to use.
# Add resolv-conf flag to Kubelet configuration
echo "--resolv-conf=/run/systemd/re... | CoreDNS | 62,664,701 | 13 |
I have a self made Kubernetes cluster consisting of VMs. My problem is, that the coredns pods are always go in CrashLoopBackOff state, and after a while they go back to Running as nothing happened.. One solution that I found and could not try yet, is changing the default memory limit from 170Mi to something higher. As ... | You must edit coredns pod's template in coredns deployment definition:
kubectl edit deployment -n kube-system coredns
Once your default editor is opened with coredns deployment, in the templateSpec you will find part which is responsible for setting memory and cpu limits.
| CoreDNS | 53,448,665 | 13 |
i have been trying to setup k8s in a single node,everything was installed fine. but when i check the status of my kube-system pods,
CNI -> flannel pod has crashed, reason -> Nameserver limits were exceeded, some nameservers have been omitted, the applied nameserver line is: x.x.x.x x.x.x.x x.x.x.x
CoreDNS pods status... | In short, you have too many entries in /etc/resolv.conf.
This is a known issue:
Some Linux distributions (e.g. Ubuntu), use a local DNS resolver by default (systemd-resolved). Systemd-resolved moves and replaces /etc/resolv.conf with a stub file that can cause a fatal forwarding loop when resolving names in upstream s... | CoreDNS | 59,890,834 | 11 |
I have a running k8s cluster with two replicas of CoreDNS. But when i try enter the bash prompt of the POD it's throwing me below error
# kubectl exec -it coredns-5644d7b6d9-285bj -n kube-system sh
error: Internal error occurred: error executing command in container: failed to exec in container: failed to start exec "9... | You can use the sidecar pattern following the instructions here: https://support.rancher.com/hc/en-us/articles/360041568712-How-to-troubleshoot-using-the-namespace-of-a-container#sidecar-container-0-2
In short, do this to find a node where a coredns pod is running:
kubectl -n kube-system get po -o wide | grep coredns
... | CoreDNS | 60,666,170 | 11 |
Question
How to get the Kubernetes related keys from etcd? Tried to list keys in etcd but could not see related keys. Also where is etcdctl installed?
$ etcdctl
bash: etcdctl: command not found..
$ sudo netstat -tnlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address... | Usually you need to get etcdctl by yourself. Just download the latest etcdctl archive from etcd releases page.
Also, starting from Kubernetes version 1.6 it uses etcd version 3, so to get a list of all keys is:
ETCDCTL_API=3 etcdctl --endpoints=<etcd_ip>:2379 get / --prefix --keys-only
You can find all etcdctl v3 acti... | etcd | 47,807,892 | 20 |
Now we building a realtime analytics system and it should be highly distributed. We plan to use distributed locks and counters to ensure data consistency, and we need a some kind of distributed map to know which client is connected to which server.
I have no prior experience in distributed systems before, but I think w... | Hazelcast and etcd are two very different systems. The reason is the CAP theorem.
The CAP theorem states that no distributed system can have Consistency, Availability, and Partition-tolerance. Distributed systems normally fall closer to CA or CP. Hazelcast is an AP system, and etcd (being a Raft implementation) is CP. ... | etcd | 31,011,105 | 17 |
Is it safe to use etcd across multiple data centers? As it expose etcd port to public internet.
Do I have to use client certificates in this case or etcd has some sort of authification?
| Yes, but there are two big issues you need to tackle:
Security. This all depends on what type of info you are storing in etcd. Using a point to point VPN is probably preferred over exposing the entire cluster to the internet. Client certificates can also be used.
Tuning. etcd relies on replication between machines for... | etcd | 26,075,680 | 15 |
I have been playing with docker-compose and have cobbled together a project from the docker hub website.
One thing that eludes me is how I can scale individual services up (by adding more instances) AND have existing instances somehow made aware of those new instances.
For example, the canonical docker-compose example... | Docker just released a new Version with built in orchestration:
https://blog.docker.com/2016/06/docker-1-12-built-in-orchestration/
You can start a new Swarm Cluster with:
docker swarm init
And create Services:
docker service create –name frontend –replicas 5 -p 80:80/tcp nginx:latest
The created Services will be loa... | etcd | 35,002,493 | 15 |
We are choosing the best option for implementing a leader election for our service (written in Java) comprised of multiple (e.g., 3) instances for high availability. Our goal is to have only a single instance active at any given time.
Would be great to hear your opinion about the following options:
1) Hazelcast. Using ... | 1) Hazelcast, by version 3.12, provides a CPSubsystem which is a CP system in terms of CAP and built using Raft consensus algorithm inside the Hazelcast cluster. CPSubsytem has a distributed lock implementation called FencedLock which can be used to implement a leader election.
For more information about CPSubsystem a... | etcd | 53,605,172 | 13 |
I created ConfigMap using kubectl and I can also see it using:
kubectl get cm
I am just curious where kubernetes stores this data/information within the cluster? Does it store in etc? How do I view it, if it stored in etcd?
Does it store in any file/folder location or anywhere else?
I mean where kubernetes stores it i... | Yes etcd is used for storing ConfigMaps and other resources you deploy to the cluster. See https://matthewpalmer.net/kubernetes-app-developer/articles/how-does-kubernetes-use-etcd.html and note https://github.com/kubernetes/kubernetes/issues/19781#issuecomment-172553264
You view the content of the configmap with 'kube... | etcd | 53,935,597 | 13 |
I am dealing with CRDs and creating Custom resources. I need to keep lots of information about my application in the Custom resource. As per the official doc, etcd works with request up to 1.5MB. I am hitting errors something like
"error": "Request entity too large: limit is 3145728"
I believe the specified limit in ... |
The "error": "Request entity too large: limit is 3145728" is probably the default response from kubernetes handler for objects larger than 3MB, as you can see here at L305 of the source code:
expectedMsgFor1MB := `etcdserver: request is too large`
expectedMsgFor2MB := `rpc error: code = ResourceExhausted desc = tryin... | etcd | 60,468,110 | 10 |
I am trying to understand what the difference is between SLURM's srun and sbatch commands. I will be happy with a general explanation, rather than specific answers to the following questions, but here are some specific points of confusion that can be a starting point and give an idea of what I'm looking for.
According... | The documentation says
srun is used to submit a job for execution in real time
while
sbatch is used to submit a job script for later execution.
They both accept practically the same set of parameters. The main difference is that srun is interactive and blocking (you get the result in your terminal and you cannot writ... | Slurm | 43,767,866 | 178 |
I have a job running a linux machine managed by slurm.
Now that the job is running for a few hours I realize that I underestimated the time required for it to finish and thus the value of the --time argument I specified is not enough. Is there a way to add time to an existing running job through slurm?
| Use the scontrol command to modify a job
scontrol update jobid=<job_id> TimeLimit=<new_timelimit>
Use the SLURM time format, eg. for 8 days 15 hours: TimeLimit=8-15:00:00
Requires admin privileges, on some machines.
Will be allowed to users only if the job is not running yet, on most machines.
| Slurm | 28,413,418 | 115 |
I suppose it's a pretty trivial question but nevertheless, I'm looking for the (sacct I guess) command that will display the CPU time and memory used by a slurm job ID.
| If your job is finished, then the sacct command is what you're looking for. Otherwise, look into sstat. For sacct the --format switch is the other key element. If you run this command:
sacct -e
you'll get a printout of the different fields that can be used for the --format switch. The details of each field are descr... | Slurm | 24,020,420 | 100 |
Suppose that I have the following simple bash script which I want to submit to a batch server through SLURM:
#!/bin/bash
#SBATCH -o "outFile"$1".txt"
#SBATCH -e "errFile"$1".txt"
hostname
exit 0
In this script, I simply want to write the output of hostname on a textfile whose full name I control via the command-lin... | I thought I'd offer some insight because I was also looking for the replacement to the -v option in qsub, which for sbatch can be accomplished using the --export option. I found a nice site here that shows a list of conversions from Torque to Slurm, and it made the transition much smoother.
You can specify the environm... | Slurm | 27,708,656 | 77 |
Is it possible to expand the number of characters used in the JobName column of the command sacct in SLURM?
For example, I currently have:
JobID JobName Elapsed NCPUS NTasks State
------------ ---------- ---------- ---------- -------- ----------
12345 lengthy_na+ 00:00:01 4 ... | You should use the format option, with:
sacct --helpformat
you'll see the parameters to show, for instance:
sacct --format="JobID,JobName%30"
will print the job id and the name up to 30 characters:
JobID JobName
------------ ------------------------------
19009 ... | Slurm | 42,217,102 | 69 |
When I use sinfo I see the following:
$ sinfo
PARTITION AVAIL TIMELIMIT NODES STATE NODELIST
[...]
RG3 up 28-00:00:0 1 drain rg3hpc4
[...]
What does the state 'drain' mean?
| It means no further job will be scheduled on that node, but the currently running jobs will keep running (by contrast with setting the node down which kills all jobs running on the node).
Nodes are often set to that state so that some maintenance operation can take place once all running jobs are finished.
From the ma... | Slurm | 22,480,627 | 54 |
I have searched google and read the documentation.
My local cluster is using SLURM. I want to check the following things:
How many cores does each node have?
How many cores has each job in the queue reserved?
Any advice would be much appreciated!
| in order to see the details of all the nodes you can use:
scontrol show node
For an specific node:
scontrol show node "nodename"
And for the cores of job you can use the format mark %C, for instance:
squeue -o"%.7i %.9P %.8j %.8u %.2t %.10M %.6D %C"
More info about format.
| Slurm | 41,299,911 | 51 |
How do the terms "job", "task", and "step" as used in the SLURM docs relate to each other?
AFAICT, a job may consist of multiple tasks, and also it make consist of multiple steps, but, assuming this is true, it's still not clear to me how tasks and steps relate.
It would be helpful to see an example showing the full co... | A job consists of one or more steps, each consisting of one or more tasks each using one or more CPU.
Jobs are typically created with the sbatch command, steps are created with the srun command, tasks are requested, at the job level with --ntasks or --ntasks-per-node, or at the step level with --ntasks. CPUs are requ... | Slurm | 46,506,784 | 50 |
The terminology used in the sbatch man page might be a bit confusing. Thus, I want to be sure I am getting the options set right. Suppose I have a task to run on a single node with N threads. Am I correct to assume that I would use --nodes=1 and --ntasks=N?
I am used to thinking about using, for example, pthreads to c... | Depending on the parallelism you are using: distributed or shared memory
--ntasks=# : Number of "tasks" (use with distributed parallelism).
--ntasks-per-node=# : Number of "tasks" per node (use with distributed parallelism).
--cpus-per-task=# : Number of CPUs allocated to each task (use with shared m... | Slurm | 51,139,711 | 49 |
Using sinfo it shows 3 nodes are in drain state,
PARTITION AVAIL TIMELIMIT NODES STATE NODELIST
all* up infinite 3 drain node[10,11,12]
Which command line should I use to undrain such nodes?
| Found an approach, enter scontrol interpreter (in command line type scontrol) and then
scontrol: update NodeName=node10 State=DOWN Reason="undraining"
scontrol: update NodeName=node10 State=RESUME
Then
scontrol: show node node10
displays amongst other info
State=IDLE
Update: some of these nodes got DRAIN state back... | Slurm | 29,535,118 | 42 |
On a SLURM cluster one can use squeue to get information about jobs on the system.
I know that "R" means running; and "PD" meaning pending, but what is "CG"?
I understand it to be "canceling" or "failing" from experience, but does "CG" apply when a job successfully closes? What is the G?
| "CG" stands for "completing" and it happens to a job that cannot be terminated, probably because of an I/O operation.
More detailed info in the Slurm Troubleshooting Guide
| Slurm | 42,032,634 | 41 |
When I launch a computation on the cluster, I usually have a separate program doing the post-processing at the end :
sbatch simulation
sbatch --dependency=afterok:JOBIDHERE postprocessing
I want to avoid mistyping and automatically have the good job id inserted. Any idea? Thanks
| You can do something like this:
RES=$(sbatch simulation) && sbatch --dependency=afterok:${RES##* } postprocessing
The RES variable will hold the result of the sbatch command, something like Submitted batch job 102045. The construct ${RES##* } isolates the last word (see more info here), in the current case the job id.... | Slurm | 19,960,332 | 40 |
I have a couple of thousand jobs to run on a SLURM cluster with 16 nodes. These jobs should run only on a subset of the available nodes of size 7. Some of the tasks are parallelized, hence use all the CPU power of a single node while others are single threaded. Therefore, multiple jobs should run at the same time on a ... | You can work the other way around; rather than specifying which nodes to use, with the effect that each job is allocated all the 7 nodes, specify which nodes not to use:
sbatch --exclude=myCluster[01-09] myScript.sh
and Slurm will never allocate more than 7 nodes to your jobs. Make sure though that the cluster configu... | Slurm | 26,216,727 | 40 |
In a sbatch script, you can directly launch programs or scripts (for example an executable file myapp) but in many tutorials people use srun myapp instead.
Despite reading some documentation on the topic, I do not understand the difference and when to use each of those syntaxes.
I hope this question is precise enough (... | The srun command is used to create job 'steps'.
First, it will bring better reporting of the resource usage ; the sstat command will provide real-time resource usage for processes that are started with srun, and each step (each call to srun) will be reported individually in the accounting.
Second, it can be used to se... | Slurm | 53,636,752 | 40 |
I am running a Python code that contains print statements via SLURM. Normally when I run the Python code directly via "python program.py" the print statements appear in the terminal. When I run my program via SLURM, as expected the print statements do not appear in the terminal. How can I save the print statements t... | By default, print in Python is buffered, meaning that it does not write to files or stdout immediately, and needs to be 'flushed' to force the writing to stdout immediately.
See this question for available options.
The simplest option is to start the Python interpreter with the -u option.
From the python man page:
-u ... | Slurm | 33,178,514 | 38 |
I'm working in a SLURM cluster and I was running several processes at the same time (on several input files), and using the same bash script.
At the end of the job, the process was killed and this is the error I obtained.
slurmstepd: error: Detected 1 oom-kill event(s) in step 1090990.batch cgroup.
My guess is that th... | The approved answer is correct but, to be more precise, error
slurmstepd: error: Detected 1 oom-kill event(s) in step 1090990.batch cgroup.
indicates that you are low on Linux's CPU RAM memory.
If you were, for instance, running some computation on GPU, requesting more GPU memory than what is available will result in ... | Slurm | 52,421,068 | 36 |
I am using slurm on a cluster to run jobs and submit a script that looks like below with sbatch:
#!/usr/bin/env bash
#SBATCH -o slurm.sh.out
#SBATCH -p defq
#SBATCH --mail-type=ALL
#SBATCH --mail-user=my.email@something.com
echo "hello"
Can I somehow comment out a #SBATCH line, e.g. the #SBATCH --mail-user=my.email@... | just add another # at the beginning.
##SBATCH --mail-user...
This will not be processed by Slurm
| Slurm | 40,346,871 | 34 |
I wanted to run a python script main.py multiple times with different arguments through a sbatch_run.sh script as in:
#!/bin/bash
#SBATCH --job-name=sbatch_run
#SBATCH --array=1-1000
#SBATCH --exclude=node047
arg1=10 #arg to be change during runs
arg2=12 #arg to be change during runs
python main.py $arg1 $arg2
The ar... | When sbatch is run, Slurm copies the submission script to its internal database ; you can convince yourself with the following experiment:
$ cat submit.sh
#!/bin/bash
#SBATCH --hold
echo helloworld
The --hold is there to make sure the job does not start. Submit it :
$ sbatch submit.sh
Then modify the submission scri... | Slurm | 38,778,844 | 24 |
Would someone be able to clarify what each of these things actually are? From what I gathered, nodes are computing points within the cluster, essentially a single computer. Tasks are processes that can be executed either on a single node or on multiple nodes. And cores are basically how much of a CPU on a single node d... | The terms can have different meanings in different context, but if we stick to a Slurm context:
A (compute) node is a computer part of a larger set of nodes (a cluster). Besides compute nodes, a cluster comprises one or more login nodes, file server nodes, management nodes, etc. A compute node offers resources such as... | Slurm | 65,603,381 | 24 |
I submitted several jobs via SLURM to our school's HPC cluster. Because the shell scripts all have the same name, so the job names appear exactly the same. It looks like
[myUserName@rclogin06 ~]$ sacct -u myUserName
JobID JobName Partition Account AllocCPUS State ExitCode
------------ ---------- --... | You can use the scontrol command to see the job details. $ scontrol show job <jobid>
For example, for a running job on our SLURM cluster:
$ scontrol show job 1665191
JobId=1665191 Name=tasktest
...
Shared=OK Contiguous=0 Licenses=(null) Network=(null)
Command=/lustre/work/.../slurm_test/task.submit
... | Slurm | 24,586,699 | 22 |
I have submitted a job to a SLURM queue, the job has run and completed. I then check the completed jobs using the sacct command. But looking at the results of the sacct command I notice additional results that I did not expect:
JobID JobName State NCPUS Timelimit
5297048 ... | A Slurm job contains multiple jobsteps, which are all accounted for (in terms of resource usage) separately by Slurm. Usually, these steps are created using srun/mpirun and enumerated starting from 0. But in addition to that, there are sometimes two special steps. For example, take the following job:
sbatch -n 4 --wrap... | Slurm | 52,447,602 | 22 |
I'm trying to obtain a value from another file and use this within a SLURM submission script. However, I get an error that the value is non-numerical, in other words, it is not being dereferenced.
Here is the script:
#!/bin/bash
# This reads out the number of procs based on the decomposeParDict ... | This won't work. What happens when you run
sbatch myscript.sh
is that slurm parses the script for those special #SBATCH lines, generates a job record, stores the batch script somewhere. The batch script is executed only later when the job runs.
So you need to structure you workflow in a slightly different way, and fir... | Slurm | 24,508,040 | 21 |
I could get access to a computing cluster, specifically one node with two 12-Core CPUs, which is running with Slurm Workload Manager.
I would like to run TensorFlow on that system but unfortunately I were not able to find any information about how to do this or if this is even possible. I am new to this but as far as I... | It's relatively simple.
Under the simplifying assumptions that you request one process per host, slurm will provide you with all the information you need in environment variables, specifically SLURM_PROCID, SLURM_NPROCS and SLURM_NODELIST.
For example, you can initialize your task index, the number of tasks and the nod... | Slurm | 34,826,736 | 21 |
I have the following script to submit job with slurm:
#!/bin/sh
#!/bin/bash
#SBATCH -J $3 #job_name
#SBATCH -n 1 #Number of processors
#SBATCH -p CA
nwchem $1 > $2
The first argument ($1) is my input, the second ($2) is my output and I would like the third ($3) to be my jobname. If I do like this, the job name is '... | The SBATCH directives are seen as comments by the shell and it does not perform variable substitution on $3. There are several courses of action:
Option 1: pass the -J argument on the command line:
sbatch -J thejobname submission_script.sh input.data output.res
Option 2: pass the script through stdin replacing the po... | Slurm | 36,279,200 | 21 |
You need to run, say, 30 srun jobs, but ensure each of the jobs is run on a node from the particular list of nodes (that have the same performance, to fairly compare timings).
How would you do it?
What I tried:
srun --nodelist=machineN[0-3] <some_cmd> : runs <some_cmd> on all the nodes simultaneously (what i need: to ... | Update: Version 23.02 has fixed this, as can be read in the Release notes: Allow for --nodelist to contain more nodes than required by --nodes.
You can go the opposite direction and use the --exclude option of sbatch:
srun --exclude=machineN[4-XX] <some_cmd>
Then slurm will only consider nodes that are not listed in ... | Slurm | 37,480,603 | 20 |
Is there a way in python 3 to log the memory (ram) usage, while some program is running?
Some background info. I run simulations on a hpc cluster using slurm, where I have to reserve some memory before submitting a job. I know that my job require a lot of memory, but I am not sure how much. So I was wondering if there ... | You can do that with the memory_profiler package. Just with adding a decorator @profile to a function, you will get an output like this:
Line # Mem usage Increment Line Contents
==============================================
3 @profile
4 5.97 MB 0.00 MB def my_func():
5 ... | Slurm | 47,410,932 | 20 |
as administrator I need to give the maximum priority to a given job.
I have found that submission options like: --priority=<value> or --nice[=adjustment] could be useful, but I do not know which values I should assign them in order to provide the job with the highest priority.
Another approach could be to set a low pri... | I found a solution that works without the need of using PriorityType=priority/multifactor (as suggested by Bub Espinja):
$ scontrol update job=<job-id> Priority=<any-integer>
The above command will update the priority of the job and update the queue accordingly.
The minimum priority needed to become the next one in li... | Slurm | 39,787,477 | 19 |
I'm starting the SLURM job with script and script must work depending on it's location which is obtained inside of script itself with SCRIPT_LOCATION=$(realpath $0). But SLURM copies script to slurmd folder and starts job from there and it screws up further actions.
Are there any option to get location of script used f... | You can get the initial (i.e. at submit time) location of the submission script from scontrol like this:
scontrol show job "$SLURM_JOB_ID" | awk -F= '/Command=/{print $2}'
So you can replace the realpath $0 part with the above. This will only work within a Slurm allocation of course. So if you want the script to work ... | Slurm | 56,962,129 | 19 |
I am queuing multiple jobs in SLURM. Can I limit the number of parallel running jobs in slurm?
Thanks in advance!
| If you are not the administrator, your can hold some jobs if you do not want them all to start at the same time, with scontrol hold <JOBID>, and you can delay the submission of some jobs with sbatch --begin=YYYY-MM-DD.
Also, if it is a job array, you can limit the number of jobs in the array that are concurrently runni... | Slurm | 42,812,425 | 18 |
I want to run a script on cluster (SBATCH file).
How can activate my virtual environment (path/to/env_name/bin/activate).
Does I need only to add the following code to my_script.sh file?
module load python/2.7.14
source "/pathto/Python_directory/ENV2.7_new/bin/activate"
| You mean to activate a specific Python environment as part of your submission to Slurm? This is what I add to my job script and it works well. Note that I use Anaconda, which by default adds the required paths to my .bashrc script after installation. Hope this helps.
....
# define and create a unique scratch directory... | Slurm | 53,545,690 | 18 |
I am using SLURM to dispatch jobs on a supercomputer. I have set the --output=log.out option to place the content from a job's stdout into a file (log.out). I'm finding that the file is updated every 30-60 minutes, making it difficult for me to check on the status of my jobs.
Any idea why it takes so long to update thi... | This may be related to buffering.
Have you tried disabling output buffering as suggested in here? I would recommend the stdbuf option:
stdbuf -o0 -e0 command
But can't be sure without more information, as I've never experienced a behavior like that. Which filesystem are you using?
Also if you are using srun to run you... | Slurm | 25,170,763 | 16 |
When using bsub with LSF, the -o option gave a lot of details such as when the job started and ended and how much memory and CPU time the job took. With SLURM, all I get is the same standard output that I'd get from running a script without LSF.
For example, given this Perl 6 script:
warn "standard error stream";
say ... | UPDATED ANSWER:
Years after my original answer, a friend pointed out seff to me, which is by far the best way to get this info:
seff JOBID
Just be aware that memory consumption is not constantly monitored, so if your job gets killed due to using too much memory, then know that it really did go over what you requested ... | Slurm | 29,928,925 | 16 |
In slurm, calling the command squeue -u <username> will list all the jobs that are pending or active for a given user. I am wondering if there was a quick way to tally them all so that I know how many outstanding jobs there are, including pending and actively running jobs. Thanks!
| I would interprete "quick command" differently. Additionally I would add -r for cases when you are using job arrays:
squeue -u <username> -h -t pending,running -r | wc -l
option -h removes the header "wc -l" (word count) counts the line of the output.
Eventually I am using it with watch
watch 'squeue -u <username> -h ... | Slurm | 53,037,185 | 16 |
I am trying to launch a large number of job steps using a batch script. The different steps can be completely different programs and do need exactly one CPU each. First I tried doing this using the --multi-prog argument to srun. Unfortunately, when using all CPUs assigned to my job in this manner, performance degrades ... | Found it! The nomenclature and the many command line options to slurm confused me. The solution is given by
#!/bin/bash
#SBATCH -o $HOME/slurm/slurm_out/%j.%N.out
#SBATCH --error=$HOME/slurm/slurm_out/%j.%N.err_out
#SBATCH --get-user-env
#SBATCH -J test
#SBATCH -D $HOME/slurm
#SBATCH --export=NONE
#SBATCH --ntasks=48
... | Slurm | 24,056,961 | 15 |
I am trying to run some parallel code on slurm, where the different processes do not need to communicate. Naively I used python's slurm package. However, it seems that I am only using the cpu's on one node.
For example, if I have 4 nodes with 5 cpu's each, I will only run 5 processes at the same time. How can I tell mu... | Your current code will run 10 times on 5 processor, on a SINGLE node where you start it. It has nothing to do with SLURM now.
You will have to SBATCH the script to SLURM.
If you want to run this script on 5 cores with SLURM modify the script like this:
#!/usr/bin/python3
#SBATCH --output=wherever_you_want_to_store_th... | Slurm | 39,974,874 | 15 |
I have a problem where I need to launch the same script but with different input arguments.
Say I have a script myscript.py -p <par_Val> -i <num_trial>, where I need to consider N different par_values (between x0 and x1) and M trials for each value of par_values.
Each trial of M is such that almost reaches the time l... | The best approach is to use job arrays.
One option is to pass the parameter p1 when submitting the job script, so you will only have one script, but will have to submit it multiple times, once for each p1 value.
The code will be like this (untested):
#!/bin/bash
#SBATCH --job-name=cv_01
#SBATCH --output=cv_analysis_eis... | Slurm | 41,900,600 | 15 |
I used to use a server with LSF but now I just transitioned to one with SLURM.
What is the equivalent command of bpeek (for LSF) in SLURM?
bpeek
bpeek Displays the stdout and stderr output of an unfinished job
I couldn't find the documentation anywhere. If you have some good references for SLURM, please let me know a... | I just learned that in SLURM there is no need to do bpeek to check the current standard output and standard error since they are printed in running time to the files specified for the stdout and stderr.
| Slurm | 19,062,153 | 14 |
We have a 4 GPU nodes with 2 36-core CPUs and 200 GB of RAM available at our local cluster. When I'm trying to submit a job with the follwoing configuration:
#SBATCH --nodes=1
#SBATCH --ntasks=40
#SBATCH --cpus-per-task=1
#SBATCH --mem-per-cpu=1500MB
#SBATCH --gres=gpu:4
#SBATCH --time=0-10:00:00
I'm getting the follo... | The CPUs are most likely 36-threads not 36-cores and Slurm is probably configured to allocate cores and not threads.
Check the output of scontrol show nodes to see what the nodes really offer.
| Slurm | 55,290,596 | 14 |
I have set of an array job as follows:
sbatch --array=1:100%5 ...
which will limit the number of simultaneously running tasks to 5. The job is now running, and I would like to change this number to 10 (i.e. I wish I'd run sbatch --array=1:100%10 ...).
The documentation on array jobs mentions that you can use scontrol ... | You can change the array throttling limit with the following command:
scontrol update ArrayTaskThrottle=<count> JobId=<jobID>
| Slurm | 55,430,330 | 14 |
I'm using Slurm. When I run
sinfo -Nel
it is common to see a server designated as idle, but sometimes there is also a little asterisk near it (Like this: idle*).
What does that mean? I couldn't find any info about that. (The server is up and running).
| When an * appears after the state of a node it means that the node is unreachable
Quoting the sinfo manpage under the NODE STATE CODES section:
* The node is presently not responding and will not be allocated any new work. If the node remains non-responsive, it will be placed in the DOWN state (except in the case ... | Slurm | 31,903,407 | 13 |
In SGE/PBS, I can submit binary executables to the cluster just like I would locally. For example:
qsub -b y -cwd echo hello
would submit a job named echo, which writes the word "hello" to its output file.
How can I submit a similar job to SLURM. It expects the file to have a hash-bang interpreter on the first line. O... | you can use the --wrap parameter to automatically wrap the command in a script.
something like:
sbatch --wrap="echo hello"
| Slurm | 33,400,769 | 13 |
When I submit a SLURM job with the option --gres=gpu:1 to a node with two GPUs, how can I get the ID of the GPU which is allocated for the job? Is there an environment variable for this purpose? The GPUs I'm using are all nvidia GPUs.
Thanks.
| You can get the GPU id with the environment variable CUDA_VISIBLE_DEVICES. This variable is a comma separated list of the GPU ids assigned to the job.
| Slurm | 43,967,405 | 12 |
I am running a job array with SLURM, with the following job array script (that I run with sbatch job_array_script.sh [args]:
#!/bin/bash
#SBATCH ... other options ...
#SBATCH --array=0-1000%200
srun ./job_slurm_script.py $1 $2 $3 $4
echo 'open' > status_file.txt
To explain, I want job_slurm_script.py to be run as ... | You can add the flag --wait to sbatch.
Check the manual page of sbatch for information about --wait.
| Slurm | 46,427,148 | 12 |
Edit
What I am really looking for is a way to emulate SLURM, something interactive and reasonably user-friendly that I can install.
Original post
I want to test drive some minimal examples with SLURM, and I am trying to install it all on a local machine with Ubuntu 16.04. I am following the most recent slurm install g... | The value in front of ControlMachine has to match the output of hostname -s on the machine on which slurmctld starts. The same holds for NodeName ; it has to match the output of hostname -s on the machine on which slurmd starts. As you only have one machine and it appears to be called Haggunenon, the relevant lines in ... | Slurm | 46,966,876 | 11 |
I have noticed a strange seq behavior on one of my computers (Ubuntu LTS 14.04): instead of using points as decimal separator it is using commas:
seq 0. 0.1 0.2
0,0
0,1
0,2
The same version of seq (8.21) on my other PC gives the normal points (also same Ubuntu version). The strangest thing is that I am observing the s... | It's likely the LANG variable or some other locale-specific variable. On a computer where seq behaves "normally" try:
$ LANG=fr_FR seq 0. 0.1 0.2
0,0
0,1
0,2
$ LANG=en_US seq 0. 0.1 0.2
0.0
0.1
0.2
| Slurm | 23,884,934 | 10 |
I want to see the status of one of my older jobs submitted using slurm. I have used sacct -j , but it does not give me information on exactly the date when the job was submitted/terminated etc. I want to check the date, time of the job submissio. I tried to use scontrol, but I suppose that only works for current runnin... | As you mentioned that sacct -j is working but not providing the proper information, I'll assume that accounting is properly set and working.
You can select the output of the sacct command with the -o flag, so to get exactly what you want you can use:
sacct -j JOBID -o jobid,submit,start,end,state
You can use sacct --he... | Slurm | 46,973,921 | 10 |
I have a bunch of jobs running as an array job in slurm:
123_[1-500] PD my_job 0:00 me
123_2 R my_job 9:99 me
123_3 R my_job 9:99 me
123_4 R my_job 9:99 me
123_5 R my_job 9:99 me
...
As I read the man page on scancel, it seems to indicate that if I execute scancel 123 it will stop everythin... | You can issue scancel with the additional --state tag:
scancel --state=PENDING 123
or, in short:
scancel -t PD 123
That will only cancel jobs of the 123 array that are pending and will leave the running the already started ones.
| Slurm | 47,318,252 | 10 |
I have a python script that should generate a bunch of inputs for an external program to be called. The calls to the external program will be through slurm.
What I want is for my script to wait until all the generated calls to the external programs are finished (not the slurm command, the actual execution of the extern... | You can run your sbatch commands asynchronously in subprocesses as you tried before, but use the -W or --wait command line options for sbatch. This will cause the subprocess to not return until the job has terminated. You can then block the execution of your main program until all of the subprocesses complete. As a b... | Slurm | 51,838,249 | 10 |
I have script for running my parallel program on cluster. I run it with usual command:
sbatch -p PARTITION -t TIME -N NODES /full/path/to/my/script.sh PARAMETERS-LIST
Inside that script.sh I need to source another bash script (which is located in the same directory where script.sh resides) to load some routines/variabl... | The problem is that the location of the sbatch shell script, and only this script, is different in the case you just run it from your desktop's command prompt form the case of slurmstepd running it on a node. This happens because sbatch physically copies your script to every head node of the allocation, and runs it fro... | Slurm | 57,696,302 | 10 |
I'm new to iOS and Objective-C and the whole MVC paradigm and I'm stuck with the following:
I have a view that acts as a data entry form and I want to give the user the option to select multiple products. The products are listed on another view with a UITableViewController and I have enabled multiple selections.
How do... | This question seems to be very popular here on Stack Overflow so I thought I would try and give a better answer to help out people starting in the world of iOS like me.
Passing Data Forward
Passing data forward to a view controller from another view controller. You would use this method if you wanted to pass an object/... | Swift | 5,210,535 | 1,499 |
In Swift, how does one call Objective-C code?
Apple mentioned that they could co-exist in one application, but does this mean that one could technically re-use old classes made in Objective-C whilst building new classes in Swift?
| Using Objective-C Classes in Swift
If you have an existing class that you'd like to use, perform Step 2 and then skip to Step 5. (For some cases, I had to add an explicit #import <Foundation/Foundation.h to an older Objective-C File.)
Step 1: Add Objective-C Implementation -- .m
Add a .m file to your class, and name ... | Swift | 24,002,369 | 1,137 |
My application has a dark background, but in iOS 7 the status bar became transparent. So I can't see anything there, only the green battery indicator in the corner. How can I change the status bar text color to white like it is on the home screen?
|
Set the UIViewControllerBasedStatusBarAppearance to YES in the .plist file.
In the viewDidLoad do a [self setNeedsStatusBarAppearanceUpdate];
Add the following method:
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
Note: This does not work for controllers inside UINaviga... | Swift | 17,678,881 | 1,088 |
In Objective C, I can use #pragma mark to mark sections of my code in the symbol navigator. Since this is a C preprocessor command, it's not available in Swift. Is there a stand-in for this in Swift, or do I have to use ugly comments?
| You can use // MARK:
There has also been discussion that liberal use of class extensions might be a better practice anyway. Since extensions can implement protocols, you can e.g. put all of your table view delegate methods in an extension and group your code at a more semantic level than #pragma mark is capable of.
| Swift | 24,017,316 | 1,019 |
I was implementing an algorithm in Swift Beta and noticed that the performance was very poor. After digging deeper I realized that one of the bottlenecks was something as simple as sorting arrays. The relevant part is here:
let n = 1000000
var x = [Int](repeating: 0, count: n)
for i in 0..<n {
x[i] = random()
}
//... | tl;dr Swift 1.0 is now as fast as C by this benchmark using the default release optimisation level [-O].
Here is an in-place quicksort in Swift Beta:
func quicksort_swift(inout a:CInt[], start:Int, end:Int) {
if (end - start < 2){
return
}
var p = a[start + (end - start)/2]
var l = start
va... | Swift | 24,101,718 | 986 |
Is there a function that I can use to iterate over an array and have both index and element, like Python's enumerate?
for index, element in enumerate(list):
...
| Yes. As of Swift 3.0, if you need the index for each element along with its value, you can use the enumerated() method to iterate over the array. It returns a sequence of pairs composed of the index and the value for each item in the array. For example:
for (index, element) in list.enumerated() {
print("Item \(index)... | Swift | 24,028,421 | 964 |
How do you get the length of a String? For example, I have a variable defined like:
var test1: String = "Scott"
However, I can't seem to find a length method on the string.
| As of Swift 4+
It's just:
test1.count
for reasons.
(Thanks to Martin R)
As of Swift 2:
With Swift 2, Apple has changed global functions to protocol extensions, extensions that match any type conforming to a protocol. Thus the new syntax is:
test1.characters.count
(Thanks to JohnDifool for the heads up)
As of Swift 1
... | Swift | 24,037,711 | 841 |
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 us... | 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 ... | Swift | 25,678,373 | 833 |
I just created a new Swift project within Xcode. I am wondering which version of Swift it's using.
How can I see, in Xcode or the terminal, what version of Swift I am using inside my project?
| What I do is say in the Terminal:
$ xcrun swift -version
Output for Xcode 6.3.2 is:
Apple Swift version 1.2 (swiftlang-602.0.53.1 clang-602.0.53)
Of course that assumes that your xcrun is pointing at your copy of Xcode correctly. If, like me, you're juggling several versions of Xcode, that can be a worry! To make sur... | Swift | 30,790,188 | 747 |
I'm trying to create an NSTimer in Swift but I'm having some trouble.
NSTimer(timeInterval: 1, target: self, selector: test(), userInfo: nil, repeats: true)
test() is a function in the same class.
I get an error in the editor:
Could not find an overload for 'init' that accepts the supplied
arguments
When I chang... | Swift itself doesn't use selectors — several design patterns that in Objective-C make use of selectors work differently in Swift. (For example, use optional chaining on protocol types or is/as tests instead of respondsToSelector:, and use closures wherever you can instead of performSelector: for better type/memory safe... | Swift | 24,007,650 | 698 |
I have an app where the UITableView's separator inset is set to custom values - Right 0, Left 0. This works perfectly in iOS 7.x, however in iOS 8.0 I see that the separator inset is set to the default of 15 on the right. Even though in the xib files it set to 0, it still shows up incorrectly.
How do I remove the UITab... | iOS 8.0 introduces the layoutMargins property on cells AND table views.
This property isn't available on iOS 7.0 so you need to make sure you check before assigning it!
The easy fix is to subclass your cell and override the layout margins property as suggested by @user3570727. However you will lose any system behavior ... | Swift | 25,770,119 | 686 |
I'm trying to work out how to cast an Int into a String in Swift.
I figure out a workaround, using NSNumber but I'd love to figure out how to do it all in Swift.
let x : Int = 45
let xNSNumber = x as NSNumber
let xString : String = xNSNumber.stringValue
| Converting Int to String:
let x : Int = 42
var myString = String(x)
And the other way around - converting String to Int:
let myString : String = "42"
let x: Int? = myString.toInt()
if (x != nil) {
// Successfully converted String to Int
}
Or if you're using Swift 2 or 3:
let x: Int? = Int(myString)
| Swift | 24,161,336 | 672 |
This crash has been a blocking issue I used the following steps to reproduce the issue:
Create a Cocoa Touch Framework project
Add a swift file and a class Dog
Build a framework for device
Create a Single View application in Swift
Import framework into app project
Instantiate swift class from the framework in ViewCont... | In the target's General tab, there is an Embedded Binaries field. When you add the framework there the crash is resolved.
Reference is here on Apple Developer Forums.
| Swift | 24,333,981 | 670 |
In Objective-C the code to check for a substring in an NSString is:
NSString *string = @"hello Swift";
NSRange textRange =[string rangeOfString:@"Swift"];
if(textRange.location != NSNotFound)
{
NSLog(@"exists");
}
But how do I do this in Swift?
| You can do exactly the same call with Swift:
Swift 4 & Swift 5
In Swift 4 String is a collection of Character values, it wasn't like this in Swift 2 and 3, so you can use this more concise code1:
let string = "hello Swift"
if string.contains("Swift") {
print("exists")
}
Swift 3.0+
var string = "hello Swift"
if st... | Swift | 24,034,043 | 659 |
Let's say we have a custom class named ImageFile and this class contains two properties:
class ImageFile {
var fileName = String()
var fileID = Int()
}
Lots of them are stored in an Array:
var images : Array = []
var aImage = ImageFile()
aImage.fileName = "image1.png"
aImage.fileID = 101
images.append(aImage)... | First, declare your Array as a typed array so that you can call methods when you iterate:
var images : [imageFile] = []
Then you can simply do:
Swift 2
images.sorted({ $0.fileID > $1.fileID })
Swift 3
images.sorted(by: { $0.fileID > $1.fileID })
Swift 5
images.sorted { $0.fileId > $1.fileID }
The example above give... | Swift | 24,130,026 | 655 |
How can I detect any text changes in a textField? The delegate method shouldChangeCharactersInRange works for something, but it did not fulfill my need exactly. Since until it returns YES, the textField texts are not available to other observer methods.
e.g. in my code calculateAndUpdateTextFields did not get the upda... | From proper way to do uitextfield text change call back:
I catch the characters sent to a UITextField control something like this:
// Add a "textFieldDidChange" notification method to the text field control.
In Objective-C:
[textField addTarget:self
action:@selector(textFieldDidChange:)
forContro... | Swift | 7,010,547 | 642 |
Will Swift-based applications work on OS X 10.9 (Mavericks)/iOS 7 and lower?
For example, I have a machine running OS X 10.8 (Mountain Lion), and I am wondering if an application I write in Swift will run on it.
Or what should I have to create a Swift application using Mac OS?
| I tested it for you. Swift applications compile into standard binaries and can be run on OS X 10.9 and iOS 7.
Simple Swift application used for testing:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScre... | Swift | 24,001,778 | 629 |
Fellow devs,
I am having trouble with AutoLayout in Interface Builder (Xcode 5 / iOS 7).
It's very basic and important so I think everyone should know how this properly works. If this is a bug in Xcode, it is a critical one!
So, whenever I have a view hierarchy such as this I run into trouble:
>UIViewController
>> UIVi... | Updated
Nowadays, Apple realized the problem we solved many years ago (lol_face) and provides Content Layout Guide and Frame Layout Guide as part of the UIScrollView. Therefore you need to go through the following steps:
Same as original response below;
For this contentView, set top, bottom, left, and right margins t... | Swift | 19,036,228 | 625 |
enum Suit: String {
case spades = "♠"
case hearts = "♥"
case diamonds = "♦"
case clubs = "♣"
}
For example, how can I do something like:
for suit in Suit {
// do something with suit
print(suit.rawValue)
}
Resulting example:
♠
♥
♦
♣
| This post is relevant here https://www.swift-studies.com/blog/2014/6/10/enumerating-enums-in-swift
Essentially the proposed solution is
enum ProductCategory : String {
case Washers = "washers", Dryers = "dryers", Toasters = "toasters"
static let allValues = [Washers, Dryers, Toasters]
}
for category in Prod... | Swift | 24,007,461 | 610 |
weak references don't seem to work in Swift unless a protocol is declared as @objc, which I don't want in a pure Swift app.
This code gives a compile error (weak cannot be applied to non-class type MyClassDelegate):
class MyClass {
weak var delegate: MyClassDelegate?
}
protocol MyClassDelegate {
}
I need to prefix ... | You need to declare the type of the protocol as AnyObject.
protocol ProtocolNameDelegate: AnyObject {
// Protocol stuff goes here
}
class SomeClass {
weak var delegate: ProtocolNameDelegate?
}
Using AnyObject you say that only classes can conform to this protocol, whereas structs or enums can't.
| Swift | 24,066,304 | 602 |
I'm trying to work out an appropriate singleton model for usage in Swift. So far, I've been able to get a non-thread safe model working as:
class var sharedInstance: TPScopeManager {
get {
struct Static {
static var instance: TPScopeManager? = nil
}
if !Static.instance {
... | tl;dr: Use the class constant approach if you are using Swift 1.2 or above and the nested struct approach if you need to support earlier versions.
From my experience with Swift there are three approaches to implement the Singleton pattern that support lazy initialization and thread safety.
Class constant
class Singleto... | Swift | 24,024,549 | 596 |
I am looking for a way to replace characters in a Swift String.
Example: "This is my string"
I would like to replace " " with "+" to get "This+is+my+string".
How can I achieve this?
| This answer has been updated for Swift 4 & 5. If you're still using Swift 1, 2 or 3 see the revision history.
You have a couple of options. You can do as @jaumard suggested and use replacingOccurrences()
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal... | Swift | 24,200,888 | 595 |
I've gone through the iBook from Apple, and couldn't find any definition of it:
Can someone explain the structure of dispatch_after?
dispatch_after(<#when: dispatch_time_t#>, <#queue: dispatch_queue_t?#>, <#block: dispatch_block_t?#>)
| I use dispatch_after so often that I wrote a top-level utility function to make the syntax simpler:
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
... | Swift | 24,034,544 | 584 |
The character 👩👩👧👦 (family with two women, one girl, and one boy) is encoded as such:
U+1F469 WOMAN,
U+200D ZWJ,
U+1F469 WOMAN,
U+200D ZWJ,
U+1F467 GIRL,
U+200D ZWJ,
U+1F466 BOY
So it's very interestingly-encoded; the perfect target for a unit test. However, Swift doesn't seem to know how to treat it. Here's wh... | This has to do with how the String type works in Swift, and how the contains(_:) method works.
The '👩👩👧👦 ' is what's known as an emoji sequence, which is rendered as one visible character in a string. The sequence is made up of Character objects, and at the same time it is made up of UnicodeScalar objects.
If ... | Swift | 43,618,487 | 584 |
In Swift, how can I check if an element exists in an array? Xcode does not have any suggestions for contain, include, or has, and a quick search through the book turned up nothing. Any idea how to check for this? I know that there is a method find that returns the index number, but is there a method that returns a bool... | Swift 2, 3, 4, 5:
let elements = [1, 2, 3, 4, 5]
if elements.contains(5) {
print("yes")
}
contains() is a protocol extension method of SequenceType (for sequences of Equatable elements) and not a global method as in
earlier releases.
Remarks:
This contains() method requires that the sequence elements
adopt the E... | Swift | 24,102,024 | 575 |
I have an IOS app with an Azure back-end, and would like to log certain events, like logins and which versions of the app users are running.
How can I return the version and build number using Swift?
| EDIT
Updated for Swift 4.2
let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
EDIT
As pointed out by @azdev on the new version of Xcode you will get a compile error for trying my previous solution, to solve this just edit it as suggested to unwrap the bundle dictionary using a !
let ... | Swift | 25,965,239 | 568 |
What's the difference between print, NSLog and println and when should I use each?
For example, in Python if I wanted to print a dictionary, I'd just print myDict, but now I have 2 other options. How and when should I use each?
| A few differences:
print vs println:
The print function prints messages in the Xcode console when debugging apps.
The println is a variation of this that was removed in Swift 2 and is not used any more. If you see old code that is using println, you can now safely replace it with print.
Back in Swift 1.x, print did no... | Swift | 25,951,195 | 567 |
Playing around with Swift, coming from a Java background, why would you want to choose a Struct instead of a Class? Seems like they are the same thing, with a Struct offering less functionality. Why choose it then?
| According to the very popular WWDC 2015 talk Protocol Oriented Programming in Swift (video, transcript), Swift provides a number of features that make structs better than classes in many circumstances.
Structs are preferable if they are relatively small and copiable because copying is way safer than having multiple ref... | Swift | 24,232,799 | 566 |
I have been working to create a UIAlertView in Swift, but for some reason I can't get the statement right because I'm getting this error:
Could not find an overload for 'init' that accepts the supplied
arguments
Here is how I have it written:
let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "me... | From the UIAlertView class:
// UIAlertView is deprecated. Use UIAlertController with a
preferredStyle of UIAlertControllerStyleAlert instead
On iOS 8, you can do this:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "... | Swift | 24,022,479 | 564 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.