-
Notifications
You must be signed in to change notification settings - Fork 38
/
utils.py
78 lines (66 loc) · 1.76 KB
/
utils.py
1
2
3
4
5
6
7
8
9
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
75
76
77
78
import math
import os
import errno
import shutil
def get_grid_dim(x):
"""
Transforms x into product of two integers
:param x: int
:return: two ints
"""
factors = prime_powers(x)
if len(factors) % 2 == 0:
i = int(len(factors) / 2)
return factors[i], factors[i - 1]
i = len(factors) // 2
return factors[i], factors[i]
def prime_powers(n):
"""
Compute the factors of a positive integer
Algorithm from https://rosettacode.org/wiki/Factors_of_an_integer#Python
:param n: int
:return: set
"""
factors = set()
for x in xrange(1, int(math.sqrt(n)) + 1):
if n % x == 0:
factors.add(int(x))
factors.add(int(n // x))
return sorted(factors)
def empty_dir(path):
"""
Delete all files and folders in a directory
:param path: string, path to directory
:return: nothing
"""
for the_file in os.listdir(path):
file_path = os.path.join(path, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print 'Warning: {}'.format(e)
def create_dir(path):
"""
Creates a directory
:param path: string
:return: nothing
"""
try:
os.makedirs(path)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
def prepare_dir(path, empty=False):
"""
Creates a directory if it soes not exist
:param path: string, path to desired directory
:param empty: boolean, delete all directory content if it exists
:return: nothing
"""
if not os.path.exists(path):
create_dir(path)
if empty:
empty_dir(path)