Package: carefree-toolkit
carefree-toolkitcarefree-toolkitimplemented some commonly used functions and modulesInstallationcarefree-toolkitrequires Python 3.8 or higher.pipinstallcarefree-toolkitorgitclonehttps://github.com/carefree0910/carefree-toolkit.gitcdcarefree-toolkit
pipinstall-e.Usagestimeitclasstimeit(context_error_handler):def__init__(self,msg)Timing context manager.Parametersmsg:str, name of the context which we want to timeit.Exampleimporttimefromcftool.miscimporttimeit# ~~~  [ info ] timing for     sleep 1s     : 1.0002withtimeit("sleep 1s"):time.sleep(1)timestampdeftimestamp(simplify=False,ensure_different=False)->strReturn current timestamp.Parameterssimplify:bool. IfTrue, format will be simplified to 'year-month-day'.ensure_different:bool. IfTrue, format will include millisecond.Examplefromcftool.miscimporttimestamp# 2019-09-30_21-49-56print(timestamp())# 2019-09-30print(timestamp(simplify=True))# 2019-09-30_21-49-56-279768print(timestamp(ensure_different=True))proddefprod(iterable)->floatReturn cumulative production of aniterable.Parametersiterable:iterable.Examplefromcftool.miscimportprod# 120.0print(prod(range(1,6)))hash_codedefhash_code(code)->strReturn hash code for stringcode.Parameterscode:str.Examplefromcftool.miscimporthash_code# Truehash_code("a")!=hash_code("b")prefix_dictdefprefix_dict(d,prefix)->dictPrefix every key in dictdwithprefix, connected with'_'.Parametersd:dict.prefix:str.Examplefromcftool.miscimportprefix_dict# {"foo_a": 1, "foo_b": 2}print(prefix_dict({"a":1,"b":2},"foo"))shallow_copy_dictdefshallow_copy_dict(d)->dictShallow copy dictd, nested dict is also supported.Parametersd:dict.Examplefromcftool.miscimportshallow_copy_dictd={"a":1,"b":{"c":2,"d":3}}sd=shallow_copy_dict(d)d_copy=d.copy()d["b"].pop("c")# {'a': 1, 'b': {'d': 3}}print(d)# {'a': 1, 'b': {'c': 2, 'd': 3}}print(sd)# {'a': 1, 'b': {'d': 3}}print(d_copy)update_dictdefupdate_dict(src_dict,tgt_dict)->dictUpdatetgt_dictwithsrc_dict.Changes will happen only on keys whichsrc_dictholds, and the update procedure will be recursive.Changed will happen inplace.Parameterssrc_dict:dict.tgt_dict:str.Examplefromcftool.miscimportupdate_dictsrc_dict={"a":{"b":1},"c":2}tgt_dict={"a":{"b":0,"b1":1},"c":0,"d":1}# {"a": {"b": 1, "b1": 1}, "c": 2, "d": 1}print(update_dict(src_dict,tgt_dict))fix_float_to_lengthdeffix_float_to_length(num,length)->strChange a float number to string format with fixed length.Parametersnum:float.length:int.Exampleimportmathfromcftool.miscimportfix_float_to_length# 1.000000print(fix_float_to_length(1,8))# 1.000000print(fix_float_to_length(1.,8))# 1.000000print(fix_float_to_length(1.0,8))# -1.00000print(fix_float_to_length(-1,8))# -1.00000print(fix_float_to_length(-1.,8))# -1.00000print(fix_float_to_length(-1.0,8))# 1234567.print(fix_float_to_length(1234567,8))# 12345678print(fix_float_to_length(12345678,8))# 123456789print(fix_float_to_length(123456789,8))# +  nan   +print("+"+fix_float_to_length(math.nan,8)+"+")truncate_string_to_lengthdeftruncate_string_to_length(string,length)->strTruncate a string to make sure its length not exceeding a given length.Parametersstring:str.length:int.Examplefromcftool.miscimporttruncate_string_to_length# 123456print(truncate_string_to_length("123456",6))# 12..67print(truncate_string_to_length("1234567",6))# 12..78print(truncate_string_to_length("12345678",6))# 12...78print(truncate_string_to_length("12345678",7))groupeddefgrouped(iterable,n,*,keep_tail)->listGroup aniterableeverynelements.Parametersiterable:iterable.n:int.keep_tail:bool, whether keep the 'tail' (see example below).Examplefromcftool.miscimportgrouped# [(0, 1), (2, 3), (4, 5)]print(grouped(range(6),2))# [(0, 1, 2), (3, 4, 5)]print(grouped(range(6),3))# [(0, 1, 2, 3)]print(grouped(range(6),4))# [(0, 1, 2, 3), (4, 5)]print(grouped(range(6),4,keep_tail=True))is_numberdefis_numeric(s)->boolCheck whether stringsis numeric.Parameterss:str.Examplefromcftool.miscimportis_numeric# Trueprint(is_numeric(0x1))# Trueprint(is_numeric(1e0))# Trueprint(is_numeric("1"))# Trueprint(is_numeric("1."))# Trueprint(is_numeric("1.0"))# Trueprint(is_numeric("1.00"))# Falseprint(is_numeric("1.0.0"))# Trueprint(is_numeric("nan"))get_one_hotdefget_one_hot(feature,dim)->np.ndarrayGet one-hot representation.Parametersfeature:array-like, source data of one-hot representation.dim:int, dimension of the one-hot representation.Exampleimportnumpyasnpfromcftool.arrayimportget_one_hotfeature=np.array([0,1,0])# [[1 0], [0 1], [1 0]]print(get_one_hot(feature,2))# [[1 0 0] [0 1 0] [1 0 0]]print(get_one_hot(feature,3))# [[1 0 0] [0 1 0] [1 0 0]]print(get_one_hot(feature.tolist(),3))get_indices_from_anotherdefget_indices_from_another(base,segment)->np.ndarrayGetsegmentelements' indices inbase. This function will return positions where elements insegmentappear inbase.All elements in segment should appear in base to ensure validity.Parametersbase:np.ndarray, base array.segment:np.ndarray, segment array.Exampleimportnumpyasnpfromcftool.arrayimportget_indices_from_anotherbase,segment=np.array([1,2,3,5,7,8,9]),np.array([1,3,5,7,9])# [0 2 3 4 6]print(get_indices_from_another(base,segment))# [0 1 2 3 4]print(get_indices_from_another(segment,segment))# [4 3 2 1 0]print(get_indices_from_another(segment[::-1],segment))get_unique_indicesdefget_unique_indices(arr)->UniqueIndicesGet indices for unique values of an array.Parametersarr:np.ndarray, target array which we wish to find indices of each unique value.return_raw:bool, whether returning raw information.Exampleimportnumpyasnpfromcftool.arrayimportget_unique_indicesarr=np.array([1,2,3,2,4,1,0,1],np.int64)unique_indices=get_unique_indices(arr)# UniqueIndices(#   unique          = array([0, 1, 2, 3, 4], dtype=int64),#   unique_cnt      = array([1, 3, 2, 1, 1], dtype=int64),#   sorting_indices = array([6, 0, 5, 7, 1, 3, 2, 4], dtype=int64),#   split_arr       = array([1, 4, 6, 7], dtype=int64))#   split_indices   = [array([6], dtype=int64), array([0, 5, 7], dtype=int64), array([1, 3], dtype=int64),#                      array([2], dtype=int64), array([4], dtype=int64)]print(get_unique_indices(arr))And more...carefree-toolkitis well documented, feel free to dive into the codes and explore something you may need!Licensecarefree-toolkitis MIT licensed, as found in theLICENSEfile.