Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
378 lines (299 loc) · 10.2 KB
/
Copy pathutils.py
File metadata and controls
378 lines (299 loc) · 10.2 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
from constants import *
import time
def enumerate_collections(collection: list[object]) -> list[list[int, object]]:
"""Generates a 2-dimensional list, with the index as the first element, and corresponding item as the second.
Args:
collection (list[object]): collection to enumerate
Returns:
list[list[int, object]]: enumerated collection
Examples:
enumerate_collections(['a', 'b', 'c']) = [[0, 'a'], [1, 'b'], [2, 'c']]
"""
result = []
for index in range(len(collection)):
result.append([index, collection[index]])
return result
def lookup(key: str, collection: list[list[object]], index=0) -> str:
"""Returns the value which matches the key at index {index}
Args:
key (str): Key to search by
collection (list[list[object]]): collection to search through
index (int, optional): _description_. Defaults to 0.
Returns:
str: item found with key
"""
for item in collection:
if item[index] == key:
return item
return None
def collection_filter(collection: list[list[object]], index: int, value: object, comparison: bool=True) -> list[list[object]]:
"""Returns only items that match the same value at index
Args:
collection (list[list[object]]): collection to filter through
index (int): index of checked item
value (object): value of check
comparison (bool, optional): value to check with. Defaults to True.
Returns:
list[list[object]]: filtered list
Examples:
collection_filter([
[4, 'a'],
[3, 'b'],
[1, 'c'],
[4, 'd'],
], 0, 4) =
[
[4, 'a'],
[4, 'd']
]
"""
# [i for i in collection if i[index] == value]
result = []
for item in collection:
if comparison == (item[index] == value):
result.append(item)
return result
def collection_select(collection: list[list[object]], index: int) -> list[list[object]]:
# [i[index] for i in collection]
result = []
for item in collection:
result.append(item[index])
return result
def collection_select_multiple(collection: list[list[object]], indices: list[int]) -> list[list[object]]:
# [[i[index1], i[index2], i[index3]] for i in collection]
result = []
for row in collection:
current = []
for index in indices:
current.append(row[index])
result.append(current)
return result
def primitive_encode(word: str):
"""Encodes a string into CSV compatible format
100%200% -> 100%%200%%
lorem,ipsum -> lorem%aipsum
marks:100%,grade:400% -> marks:100%%%agrade:400%%
a\nb -> a%nb
Args:
word (str): String to be encoded
Returns:
str: Primitively encoded string
"""
word = word.replace('%', '%%')
word = word.replace(',', '%a')
word = word.replace('\n', '%n')
return word
def primitive_decode(word: str):
"""Decodes a primitively-encoded string
100%%200%% -> 100%200%
lorem%aipsum -> lorem,ipsum
marks:100%%%agrade:400%% -> marks:100%,grade:400%
a%nb -> a\nb
Args:
word (str): Primitively-encoded value to be decoded
Returns:
str: Decoded string
"""
word = word.replace('%%', '%')
word = word.replace('%a', ',')
word = word.replace('%n', '\n')
return word
def circular_shift(value, offset):
"""Circularly bitshifts left or right
Example:
13 : 0000001101 in binary
circular_shift(13, 1) = 10110
circular_shift(13, 2) = 101100
circular_shift(13, -1) = 1000000110
Args:
b (int): Integer to be shifted
n (int): Shift amount (-ve for bitshift to the right)
Returns:
int: Bitshifted result
"""
result = []
for bit in bin(value)[2:].rjust(10, '0'):
result.append(bit)
forward = offset > 0
offset = abs(offset)
for _ in range(offset):
if forward:
result.append(result.pop(0))
else:
result.insert(0, result.pop())
return int(''.join(result), 2)
def hash(word: str):
"""Hashes the input string by using bit operations
Args:
word (str): String to be hashed
Returns:
str: Hashed string
"""
# return ''.join(
# [
# chr(circular_shift(ord(character), 3) ^ circular_shift(ord(character), -4) ^ circular_shift(ord(character), len(word)))
# for character in word
# ]
# )
result = ''
for character in word:
result += chr(((circular_shift(ord(character), 3) ^ circular_shift(ord(character), -4) ^ circular_shift(ord(character), len(word))) + 32) % 126)
return result
def get_epoch_unix():
return int(time.time()) + (3600 * 8) # +8:00 timezone offset
def epoch_to_human(epoch, with_date=True):
epoch = time.gmtime(epoch)
if with_date:
return f'{epoch.tm_hour}:{str(epoch.tm_min).rjust(2, "0")} ({epoch.tm_mday}/{epoch.tm_mon})'
else:
return f'{epoch.tm_hour}:{str(epoch.tm_min).rjust(2, "0")}'
def get_start_of_week_epoch(epoch):
# 0 -> -4d
# 3d -> 3d
# 4d -> 3d
# 3d + 7d -> 10d
# 3d + 7d + 1d -> 10d
epoch //= 86400
offset = epoch - 3
offset %= 7
epoch += 7
return (epoch - offset) * 86400
def get_day_from_epoch(epoch):
# 0 -> thursday
# 86400 -> thursday
# 86401 -> friday
# mon -> 0
# tue -> 1
# ...
# sat -> 5
# sun -> 6
epoch += 86400 * 3
epoch %= 86400 * 7
return epoch // 86400
def human_duration_to_epoch(raw_string):
# 1h
# 1h 30m
sections = raw_string.split(' ')
hour = None
minute = None
try:
for section in sections:
if section[-1] == 'h':
hour = int(section[:-1])
elif section[-1] == 'm':
minute = int(section[:-1])
except:
return None
if (hour == None) and (minute == None):
return None
hour = hour if hour else 0
minute = minute if minute else 0
if (minute >= 60) or (minute < 0) or (hour < 0):
return None
return (hour * 3600) + (minute * 60)
def human_to_epoch(raw_string):
# day, dd/mm, dd/mm/yy
# +
# hh:mm (24hr)
# hh:mm{am/pm}
try:
first = str(raw_string.split(' ')[0].strip())
second = str(raw_string.split(' ')[1].strip())
period = second[-2:].lower()
hours = int(second.split(":")[0])
if period in ['am', 'pm']:
minutes = int(second.split(":")[1][:2])
# TODO : test
# using 12 hour format
if hours > 12:
return None
if (period == 'pm') and (hours != 12):
hours += 12
else:
minutes = int(second.split(":")[1])
# if hours >= 24:
# return None
# if minutes >= 60:
# return None
if (hours > 24) or (minutes >= 60):
return None
# if period in ['am', 'pm']:
# # using 12 hour format
# if hours > 12:
# return None
# if period == 'pm':
# hours += 12
suffix_time = (hours * 3600) + (minutes * 60)
sections = first.split('/')
if len(sections) == 1:
# day {suffix time}
for index, day in enumerate_collections(['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']):
if sections[0].lower().startswith(day):
return get_start_of_week_epoch(get_epoch_unix() - (8 * 3600)) + (86400 * index) + suffix_time
return None
else:
# TODO : test
# sections = [int(i) for i in sections]
for index in range(len(sections)):
sections[index] = int(sections[index])
date = sections[0]
month = sections[1]
# TODO : test
if (date >= 32) or (date <= 0) or (month >= 13) or (month <= 0):
return None
# if (date >= 32) or (date <= 0):
# return None
# if (month >= 13) or (month <= 0):
# return None
if len(sections) == 2:
# date/month {suffix time}
year = time.gmtime(get_epoch_unix()).tm_year
prefix_time = time.mktime(time.strptime(f'{str(date).rjust(2, "0")}/{str(month).rjust(2, "0")}/{year}', '%d/%m/%Y'))
prefix_time += (3600 * 8)
elif len(sections) == 3:
# date/month/year {suffix time}
year = sections[2]
for date_format in ['%d/%m/%y', '%d/%m/%Y']:
try:
prefix_time = time.mktime(time.strptime(f'{str(date).rjust(2, "0")}/{str(month).rjust(2, "0")}/{str(year).rjust(2, "0")}', date_format))
prefix_time += (3600 * 8) # timezone reasons
except:
pass
else:
return None
return int(prefix_time + suffix_time)
except Exception as e:
print(e)
return None
def time_intersect(start, end, collection):
# collection : list[[start, end], ...]
# returns indexes of elements that intersect with the start and end time
# line-sweeping algorithm can also work here
# but in this case, we just use a normal aabb check
# (x < b) && (a < y)
result = []
for index, (a, b) in enumerate_collections(collection):
if (start <= b) and (a <= end):
result.append(index)
return result
def generate_id(collection, prefix, length):
highest = 0
for item in collection:
highest = max(int(item[0][1:]), highest)
return f'{prefix}{str(highest + 1).rjust(length, "0")}'
def get_subject_titles(collection):
result = []
for subject in collection:
result.append(f'{subject[SUBJECT_NAME]} ({subject[SUBJECT_LEVEL]})')
return result
def ceil(number):
"""
ceil(0) = 0
ceil(0.1) = 1
ceil(0.9) = 1
ceil(2) = 2
ceil(2.1) = 3
"""
if int(number) == number:
return int(number)
return int(number) + 1