Completed
Pull Request — master (#148)
by
unknown
56s
created

jobname_generator()   A

Complexity

Conditions 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
c 1
b 0
f 0
dl 0
loc 15
rs 9.4285
1
import re
2
import hashlib
3
import unicodedata
4
import json
5
6
from distutils.util import strtobool
7
from subprocess import Popen, PIPE
8
9
10
def print_boxed(string):
11
    splitted_string = string.split('\n')
12
    max_len = max(map(len, splitted_string))
13
    box_line = u"\u2500" * (max_len + 2)
14
15
    out = u"\u250c" + box_line + u"\u2510\n"
16
    out += '\n'.join([u"\u2502 {} \u2502".format(line.ljust(max_len)) for line in splitted_string])
17
    out += u"\n\u2514" + box_line + u"\u2518"
18
    print out
19
20
def jobname_generator(jobname, job_id):
21
    """check if the length of the jobname is less than 64"""
22
    
23
    """args:
24
	    jobname: initial jobname
25
	    job_id: id of the job in the current batch
26
	    
27
      returns: 
28
	    croped_string: the croped version of the string"""
29
    if len(jobname) + len(job_id) > 64:
30
	extra_length =  len(jobname) + len(job_id) - 64
31
        croped_string = '{}_{}'.format(jobname[0:len(jobname - extra_length)], job_id)
32
    else:
33
	croped_string = '{}_{}'.format(jobname, job_id)
34
    return croped_string
35
36
def yes_no_prompt(query, default=None):
37
    available_prompts = {None: " [y/n] ", 'y': " [Y/n] ", 'n': " [y/N] "}
38
39
    if default not in available_prompts:
40
        raise ValueError("Invalid default: '{}'".format(default))
41
42
    while True:
43
        try:
44
            answer = raw_input("{0}{1}".format(query, available_prompts[default]))
45
            return strtobool(answer)
46
        except ValueError:
47
            if answer == '' and default is not None:
48
                return strtobool(default)
49
50
51
def chunks(sequence, n):
52
    """ Yield successive n-sized chunks from sequence. """
53
    for i in xrange(0, len(sequence), n):
54
        yield sequence[i:i + n]
55
56
57
def generate_uid_from_string(value):
58
    """ Create unique identifier from a string. """
59
    return hashlib.sha256(value).hexdigest()
60
61
62
def slugify(value):
63
    """
64
    Converts to lowercase, removes non-word characters (alphanumerics and
65
    underscores) and converts spaces to underscores. Also strips leading and
66
    trailing whitespace.
67
68
    Reference
69
    ---------
70
    https://github.com/django/django/blob/1.7c3/django/utils/text.py#L436
71
    """
72
    value = unicodedata.normalize('NFKD', unicode(value, "UTF-8")).encode('ascii', 'ignore').decode('ascii')
73
    value = re.sub('[^\w\s-]', '', value).strip().lower()
74
    return str(re.sub('[-\s]+', '_', value))
75
76
77
def encode_escaped_characters(text, escaping_character="\\"):
78
    """ Escape the escaped character using its hex representation """
79
    def hexify(match):
80
        return "\\x{0}".format(match.group()[-1].encode("hex"))
81
82
    return re.sub(r"\\.", hexify, text)
83
84
85
def decode_escaped_characters(text):
86
    """ Convert hex representation to the character it represents """
87
    if len(text) == 0:
88
        return ''
89
90
    def unhexify(match):
91
        return match.group()[2:].decode("hex")
92
93
    return re.sub(r"\\x..", unhexify, text)
94
95
96
def save_dict_to_json_file(path, dictionary):
97
    with open(path, "w") as json_file:
98
        json_file.write(json.dumps(dictionary, indent=4, separators=(',', ': ')))
99
100
101
def load_dict_from_json_file(path):
102
    with open(path, "r") as json_file:
103
        return json.loads(json_file.read())
104
105
106
def detect_cluster():
107
    # Get server status
108
    try:
109
        output = Popen(["qstat", "-B"], stdout=PIPE).communicate()[0]
110
    except OSError:
111
        # If qstat is not available we assume that the cluster is unknown.
112
        return None
113
    # Get server name from status
114
    server_name = output.split('\n')[2].split(' ')[0]
115
    # Cleanup the name and return it
116
    cluster_name = None
117
    if server_name.split('.')[-1] == 'm':
118
        cluster_name = "mammouth"
119
    elif server_name.split('.')[-1] == 'guil':
120
        cluster_name = "guillimin"
121
    elif server_name.split('.')[-1] == 'helios':
122
        cluster_name = "helios"
123
    elif server_name.split('.')[-1] == 'hades':
124
        cluster_name = "hades"
125
    return cluster_name
126
127
128
def get_launcher(cluster_name):
129
    if cluster_name == "helios":
130
        return "msub"
131
    else:
132
        return "qsub"
133