index
int64
0
50.7k
project_path
stringclasses
279 values
completion_path
stringlengths
57
199
signature_postion
stringlengths
3
11
class_position
stringlengths
3
11
function_name
stringlengths
1
62
class_name
stringlengths
0
55
body_position
stringlengths
3
11
body_position_with_comments
stringlengths
3
11
masked_class
stringlengths
14
8.32k
masked_class_with_comment
stringlengths
14
8.32k
func_body
stringlengths
9
6.72k
func_body_with_comment
stringlengths
9
6.72k
len_func_body
int64
1
643
len_input
int64
10
2.02k
len_output
int64
4
1.9k
total
int64
20
2.05k
file_code
stringlengths
14
442k
file_code_with_comment
stringlengths
14
442k
43,504
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/utils/optim/ema.py
17,18
9,47
step
Optimizer
18,34
18,34
class Optimizer(optimizer_cls): def __init__(self, *args, polyak=0.0, **kwargs): if not 0.0 <= polyak <= 1.0: raise ValueError("Invalid polyak decay rate: {}".format(polyak)) super().__init__(*args, **kwargs) self.defaults['polyak'] = polyak se...
class Optimizer(optimizer_cls): def __init__(self, *args, polyak=0.0, **kwargs): if not 0.0 <= polyak <= 1.0: raise ValueError("Invalid polyak decay rate: {}".format(polyak)) super().__init__(*args, **kwargs) self.defaults['polyak'] = polyak se...
super().step(closure) self.stepped = True # update exponential moving average after gradient update to parameters for group in self.param_groups: for p in group['params']: state = self.state[p] # state initializati...
super().step(closure) self.stepped = True # update exponential moving average after gradient update to parameters for group in self.param_groups: for p in group['params']: state = self.state[p] # state initializati...
50
269
156
425
"""Wrapper of optimizers in torch.optim for computation of exponential moving average of parameters. Source: https://github.com/kamenbliznashki/pixel_models/blob/master/optim.py """ import torch def build_ema_optimizer(optimizer_cls): class Optimizer(optimizer_cls): def __init__(self, *args, polyak=0.0, ...
"""Wrapper of optimizers in torch.optim for computation of exponential moving average of parameters. Source: https://github.com/kamenbliznashki/pixel_models/blob/master/optim.py """ import torch def build_ema_optimizer(optimizer_cls): class Optimizer(optimizer_cls): def __init__(self, *args, polyak=0.0, ...
43,506
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/utils/optim/lamb.py
205,206
169,251
step
JITLamb
212,251
206,251
class JITLamb(Optimizer): r"""Implements Lamb algorithm. It has been proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional):...
class JITLamb(Optimizer): r"""Implements Lamb algorithm. It has been proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional):...
loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad.data if grad.is_sparse: raise ...
"""Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: ...
110
588
414
1,002
# Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
# Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
43,507
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/utils/optim/lamb.py
78,79
42,148
step
Lamb
85,148
79,148
class Lamb(Optimizer): r"""Implements Lamb algorithm. It has been proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): le...
class Lamb(Optimizer): r"""Implements Lamb algorithm. It has been proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): le...
loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad.data if grad.is_sparse: raise ...
"""Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: ...
201
590
718
1,308
# Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
# Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
43,510
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/classification/data/data_simmim_ft.py
61,62
1,113
build_dataset
62,75
62,75
# -------------------------------------------------------- # SimMIM # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Zhenda Xie # -------------------------------------------------------- import os import torch.distributed as dist from torch.utils.data import DataLo...
# -------------------------------------------------------- # SimMIM # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Zhenda Xie # -------------------------------------------------------- import os import torch.distributed as dist from torch.utils.data import DataLo...
transform = build_transform(is_train, config) if config.DATA.DATASET == 'imagenet': prefix = 'train' if is_train else 'val' root = os.path.join(config.DATA.DATA_PATH, prefix) dataset = datasets.ImageFolder(root, transform=transform) nb_classes = 1000 else: raise ...
transform = build_transform(is_train, config) if config.DATA.DATASET == 'imagenet': prefix = 'train' if is_train else 'val' root = os.path.join(config.DATA.DATA_PATH, prefix) dataset = datasets.ImageFolder(root, transform=transform) nb_classes = 1000 else: raise ...
36
1,311
137
1,448
# -------------------------------------------------------- # SimMIM # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Zhenda Xie # -------------------------------------------------------- import os import torch.distributed as dist from torch.utils.data import DataLo...
# -------------------------------------------------------- # SimMIM # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Zhenda Xie # -------------------------------------------------------- import os import torch.distributed as dist from torch.utils.data import DataLo...
43,511
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/classification/data/data_simmim_pt.py
77,78
1,100
collate_fn
78,92
78,92
# -------------------------------------------------------- # SimMIM # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Zhenda Xie # -------------------------------------------------------- import math import random import numpy as np import torch import torch.distri...
# -------------------------------------------------------- # SimMIM # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Zhenda Xie # -------------------------------------------------------- import math import random import numpy as np import torch import torch.distri...
if not isinstance(batch[0][0], tuple): return default_collate(batch) else: batch_num = len(batch) ret = [] for item_idx in range(len(batch[0][0])): if batch[0][0][item_idx] is None: ret.append(None) else: ret.append(default_...
if not isinstance(batch[0][0], tuple): return default_collate(batch) else: batch_num = len(batch) ret = [] for item_idx in range(len(batch[0][0])): if batch[0][0][item_idx] is None: ret.append(None) else: ret.append(default_...
35
1,037
168
1,205
# -------------------------------------------------------- # SimMIM # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Zhenda Xie # -------------------------------------------------------- import math import random import numpy as np import torch import torch.distri...
# -------------------------------------------------------- # SimMIM # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Zhenda Xie # -------------------------------------------------------- import math import random import numpy as np import torch import torch.distri...
43,512
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/classification/data/imagenet22k_dataset.py
24,25
12,56
_load_image
IN22KDATASET
25,33
25,33
class IN22KDATASET(data.Dataset): def __init__(self, root, ann_file='', transform=None, target_transform=None): super(IN22KDATASET, self).__init__() self.data_path = root self.ann_path = os.path.join(self.data_path, ann_file) self.transform = transform self.target_transform ...
class IN22KDATASET(data.Dataset): def __init__(self, root, ann_file='', transform=None, target_transform=None): super(IN22KDATASET, self).__init__() self.data_path = root self.ann_path = os.path.join(self.data_path, ann_file) self.transform = transform self.target_transform ...
try: im = Image.open(path) except: print("ERROR IMG LOADED: ", path) random_img = np.random.rand(224, 224, 3) * 255 im = Image.fromarray(np.uint8(random_img)) return im
try: im = Image.open(path) except: print("ERROR IMG LOADED: ", path) random_img = np.random.rand(224, 224, 3) * 255 im = Image.fromarray(np.uint8(random_img)) return im
22
409
92
501
import os import json import torch.utils.data as data import numpy as np from PIL import Image import warnings warnings.filterwarnings("ignore", "(Possibly )?corrupt EXIF data", UserWarning) class IN22KDATASET(data.Dataset): def __init__(self, root, ann_file='', transform=None, target_transform=None): s...
import os import json import torch.utils.data as data import numpy as np from PIL import Image import warnings warnings.filterwarnings("ignore", "(Possibly )?corrupt EXIF data", UserWarning) class IN22KDATASET(data.Dataset): def __init__(self, root, ann_file='', transform=None, target_transform=None): s...
43,513
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/classification/data/samplers.py
28,29
11,30
set_epoch
SubsetRandomSampler
29,30
29,30
class SubsetRandomSampler(torch.utils.data.Sampler): r"""Samples elements randomly from a given list of indices, without replacement. Arguments: indices (sequence): a sequence of indices """ def __init__(self, indices): self.epoch = 0 self.indices = indices def __iter__(se...
class SubsetRandomSampler(torch.utils.data.Sampler): r"""Samples elements randomly from a given list of indices, without replacement. Arguments: indices (sequence): a sequence of indices """ def __init__(self, indices): self.epoch = 0 self.indices = indices def __iter__(se...
self.epoch = epoch
self.epoch = epoch
3
161
9
170
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import torch class SubsetRandomSampler(torch.utils.data.Sampler): ...
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import torch class SubsetRandomSampler(torch.utils.data.Sampler): ...
43,514
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/classification/data/zipreader.py
18,19
1,104
is_zip_path
20,23
19,23
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import zipfile import io import numpy as np from PIL import Im...
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import zipfile import io import numpy as np from PIL import Im...
return '.zip@' in img_or_path
"""judge if this is a zip path""" return '.zip@' in img_or_path
4
1,068
18
1,086
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import zipfile import io import numpy as np from PIL import Im...
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import zipfile import io import numpy as np from PIL import Im...
43,515
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/classification/data/zipreader.py
66,68
23,104
list_files
ZipReader
68,85
68,85
class ZipReader(object): """A class to read zipped files""" zip_bank = dict() def __init__(self): super(ZipReader, self).__init__() @staticmethod def get_zipfile(path): zip_bank = ZipReader.zip_bank if path not in zip_bank: zfile = zipfile.ZipFile(path, 'r') ...
class ZipReader(object): """A class to read zipped files""" zip_bank = dict() def __init__(self): super(ZipReader, self).__init__() @staticmethod def get_zipfile(path): zip_bank = ZipReader.zip_bank if path not in zip_bank: zfile = zipfile.ZipFile(path, 'r') ...
if extension is None: extension = ['.*'] zip_path, folder_path = ZipReader.split_zip_style_path(path) zfile = ZipReader.get_zipfile(zip_path) file_lists = [] for file_foler_name in zfile.namelist(): file_foler_name = str.strip(file_foler_name, '/') ...
if extension is None: extension = ['.*'] zip_path, folder_path = ZipReader.split_zip_style_path(path) zfile = ZipReader.get_zipfile(zip_path) file_lists = [] for file_foler_name in zfile.namelist(): file_foler_name = str.strip(file_foler_name, '/') ...
43
726
232
958
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import zipfile import io import numpy as np from PIL import Im...
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import zipfile import io import numpy as np from PIL import Im...
43,516
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/classification/utils/cosine_lr.py
97,98
18,117
get_epoch_values
CosineLRScheduler
98,103
98,103
class CosineLRScheduler(Scheduler): """ Cosine decay with restarts. This is described in the paper https://arxiv.org/abs/1608.03983. Inspiration from https://github.com/allenai/allennlp/blob/master/allennlp/training/learning_rate_schedulers/cosine.py """ def __init__(self, ...
class CosineLRScheduler(Scheduler): """ Cosine decay with restarts. This is described in the paper https://arxiv.org/abs/1608.03983. Inspiration from https://github.com/allenai/allennlp/blob/master/allennlp/training/learning_rate_schedulers/cosine.py """ def __init__(self, ...
if self.t_in_epochs: return self._get_lr(epoch) else: return None
if self.t_in_epochs: return self._get_lr(epoch) else: return None
7
1,243
40
1,283
""" Cosine Scheduler Cosine LR schedule with warmup, cycle/restarts, noise. Hacked together by / Copyright 2020 Ross Wightman """ import logging import math import numpy as np import torch from timm.scheduler.scheduler import Scheduler _logger = logging.getLogger(__name__) class CosineLRScheduler(Scheduler): ...
""" Cosine Scheduler Cosine LR schedule with warmup, cycle/restarts, noise. Hacked together by / Copyright 2020 Ross Wightman """ import logging import math import numpy as np import torch from timm.scheduler.scheduler import Scheduler _logger = logging.getLogger(__name__) class CosineLRScheduler(Scheduler): ...
43,517
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/classification/utils/logger.py
15,17
1,42
create_logger
17,42
17,42
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import sys import logging import functools from termcolor impo...
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import sys import logging import functools from termcolor impo...
# create logger logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) logger.propagate = False # create formatter fmt = '[%(asctime)s %(name)s] (%(filename)s %(lineno)d): %(levelname)s %(message)s' color_fmt = colored('[%(asctime)s %(name)s]', 'green') + \ colored(...
# create logger logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) logger.propagate = False # create formatter fmt = '[%(asctime)s %(name)s] (%(filename)s %(lineno)d): %(levelname)s %(message)s' color_fmt = colored('[%(asctime)s %(name)s]', 'green') + \ colored(...
71
116
401
517
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import sys import logging import functools from termcolor impo...
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import sys import logging import functools from termcolor impo...
43,520
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/classification/utils/utils.py
175,176
153,181
state_dict
NativeScalerWithGradNormCount
176,178
176,178
class NativeScalerWithGradNormCount: state_dict_key = "amp_scaler" def __init__(self): self._scaler = torch.cuda.amp.GradScaler() def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True): self._scaler.scale(loss).backward(create_graph=creat...
class NativeScalerWithGradNormCount: state_dict_key = "amp_scaler" def __init__(self): self._scaler = torch.cuda.amp.GradScaler() def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True): self._scaler.scale(loss).backward(create_graph=creat...
return self._scaler.state_dict()
return self._scaler.state_dict()
2
308
15
323
# -------------------------------------------------------- # Modified By Mzero # -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # ---------------------------------------------------...
# -------------------------------------------------------- # Modified By Mzero # -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # ---------------------------------------------------...
43,522
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/detection/tools/model_converters/selfsup2mmdet.py
8,9
1,43
moco_convert
10,28
9,28
# Copyright (c) OpenMMLab. All rights reserved. import argparse from collections import OrderedDict import torch def moco_convert(src, dst): FILL_FUNC_BODYdef main(): parser = argparse.ArgumentParser(description='Convert model keys') parser.add_argument('src', help='src detectron model path') parser.add_...
# Copyright (c) OpenMMLab. All rights reserved. import argparse from collections import OrderedDict import torch def moco_convert(src, dst): """Convert keys in pycls pretrained moco models to mmdet style.""" FILL_FUNC_BODYdef main(): parser = argparse.ArgumentParser(description='Convert model keys') pars...
# load caffe model moco_model = torch.load(src) blobs = moco_model['state_dict'] # convert to pytorch style state_dict = OrderedDict() for k, v in blobs.items(): if not k.startswith('module.encoder_q.'): continue old_k = k k = k.replace('module.encoder_q.', ''...
"""Convert keys in pycls pretrained moco models to mmdet style.""" # load caffe model moco_model = torch.load(src) blobs = moco_model['state_dict'] # convert to pytorch style state_dict = OrderedDict() for k, v in blobs.items(): if not k.startswith('module.encoder_q.'): c...
51
249
195
444
# Copyright (c) OpenMMLab. All rights reserved. import argparse from collections import OrderedDict import torch def moco_convert(src, dst): FILL_FUNC_BODYdef main(): parser = argparse.ArgumentParser(description='Convert model keys') parser.add_argument('src', help='src detectron model path') parser.add_...
# Copyright (c) OpenMMLab. All rights reserved. import argparse from collections import OrderedDict import torch def moco_convert(src, dst): """Convert keys in pycls pretrained moco models to mmdet style.""" FILL_FUNC_BODYdef main(): parser = argparse.ArgumentParser(description='Convert model keys') pars...
43,523
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/segmentation/tools/analysis_tools/analyze_logs.py
12,13
1,131
plot_curve
13,68
13,68
# Copyright (c) OpenMMLab. All rights reserved. """Modified from https://github.com/open- mmlab/mmdetection/blob/master/tools/analysis_tools/analyze_logs.py.""" import argparse import json from collections import defaultdict import matplotlib.pyplot as plt import seaborn as sns def plot_curve(log_dicts, args): FILL_...
# Copyright (c) OpenMMLab. All rights reserved. """Modified from https://github.com/open- mmlab/mmdetection/blob/master/tools/analysis_tools/analyze_logs.py.""" import argparse import json from collections import defaultdict import matplotlib.pyplot as plt import seaborn as sns def plot_curve(log_dicts, args): FILL_...
if args.backend is not None: plt.switch_backend(args.backend) sns.set_style(args.style) # if legend is None, use {filename}_{key} as legend legend = args.legend if legend is None: legend = [] for json_log in args.json_logs: for metric in args.keys: ...
if args.backend is not None: plt.switch_backend(args.backend) sns.set_style(args.style) # if legend is None, use {filename}_{key} as legend legend = args.legend if legend is None: legend = [] for json_log in args.json_logs: for metric in args.keys: ...
174
760
714
1,474
# Copyright (c) OpenMMLab. All rights reserved. """Modified from https://github.com/open- mmlab/mmdetection/blob/master/tools/analysis_tools/analyze_logs.py.""" import argparse import json from collections import defaultdict import matplotlib.pyplot as plt import seaborn as sns def plot_curve(log_dicts, args): FILL_...
# Copyright (c) OpenMMLab. All rights reserved. """Modified from https://github.com/open- mmlab/mmdetection/blob/master/tools/analysis_tools/analyze_logs.py.""" import argparse import json from collections import defaultdict import matplotlib.pyplot as plt import seaborn as sns def plot_curve(log_dicts, args): FILL_...
43,524
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba
/home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/segmentation/tools/misc/publish_model.py
31,32
1,51
process_checkpoint
32,44
32,44
# Copyright (c) OpenMMLab. All rights reserved. import argparse import subprocess from hashlib import sha256 import torch BLOCK_SIZE = 128 * 1024 def parse_args(): parser = argparse.ArgumentParser( description='Process a checkpoint to be published') parser.add_argument('in_file', help='input checkpo...
# Copyright (c) OpenMMLab. All rights reserved. import argparse import subprocess from hashlib import sha256 import torch BLOCK_SIZE = 128 * 1024 def parse_args(): parser = argparse.ArgumentParser( description='Process a checkpoint to be published') parser.add_argument('in_file', help='input checkpo...
checkpoint = torch.load(in_file, map_location='cpu') # remove optimizer for smaller file size if 'optimizer' in checkpoint: del checkpoint['optimizer'] # if it is necessary to remove some sensitive data in checkpoint['meta'], # add the code here. torch.save(checkpoint, out_file) sha ...
checkpoint = torch.load(in_file, map_location='cpu') # remove optimizer for smaller file size if 'optimizer' in checkpoint: del checkpoint['optimizer'] # if it is necessary to remove some sensitive data in checkpoint['meta'], # add the code here. torch.save(checkpoint, out_file) sha ...
47
349
165
514
# Copyright (c) OpenMMLab. All rights reserved. import argparse import subprocess from hashlib import sha256 import torch BLOCK_SIZE = 128 * 1024 def parse_args(): parser = argparse.ArgumentParser( description='Process a checkpoint to be published') parser.add_argument('in_file', help='input checkpo...
# Copyright (c) OpenMMLab. All rights reserved. import argparse import subprocess from hashlib import sha256 import torch BLOCK_SIZE = 128 * 1024 def parse_args(): parser = argparse.ArgumentParser( description='Process a checkpoint to be published') parser.add_argument('in_file', help='input checkpo...
43,553
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool/COMTool/Main.py
10,11
1,26
restart_program
14,18
11,18
import sys import os try: from main2 import main from parameters import log except Exception: from COMTool.main2 import main from COMTool.parameters import log def restart_program(): FILL_FUNC_BODYif __name__ == '__main__': while 1: ret = main() if not ret is None: break...
import sys import os try: from main2 import main from parameters import log except Exception: from COMTool.main2 import main from COMTool.parameters import log def restart_program(): ''' restart program, not return ''' FILL_FUNC_BODYif __name__ == '__main__': while 1: ret = ...
python = sys.executable log.i("Restarting program, comand: {} {} {}".format(python, python, *sys.argv)) os.execl(python, python, * sys.argv)
''' restart program, not return ''' python = sys.executable log.i("Restarting program, comand: {} {} {}".format(python, python, *sys.argv)) os.execl(python, python, * sys.argv)
15
136
59
195
import sys import os try: from main2 import main from parameters import log except Exception: from COMTool.main2 import main from COMTool.parameters import log def restart_program(): FILL_FUNC_BODYif __name__ == '__main__': while 1: ret = main() if not ret is None: break...
import sys import os try: from main2 import main from parameters import log except Exception: from COMTool.main2 import main from COMTool.parameters import log def restart_program(): ''' restart program, not return ''' FILL_FUNC_BODYif __name__ == '__main__': while 1: ret = ...
43,554
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool/COMTool/autoUpdate.py
50,51
10,87
checkUpdate_neucrack
AutoUpdate
51,72
51,72
class AutoUpdate: updateUrl = "https://github.com/Neutree/COMTool/releases" releaseApiUrl = "https://api.github.com/repos/Neutree/COMTool/releases" releaseApiUrl2 = "https://neucrack.com/comtool_update" def detectNewVersion(self): need, v = self.checkUpdate_neucrack() # github api may change, bu...
class AutoUpdate: updateUrl = "https://github.com/Neutree/COMTool/releases" releaseApiUrl = "https://api.github.com/repos/Neutree/COMTool/releases" releaseApiUrl2 = "https://neucrack.com/comtool_update" def detectNewVersion(self): need, v = self.checkUpdate_neucrack() # github api may change, bu...
import requests, json latest = version.Version() try: headers = { "User-Agent": f"comtool_v{version.major}.{version.minor}.{version.dev}-{platform.platform()}" } page = requests.post(self.releaseApiUrl2, headers=headers) if page.sta...
import requests, json latest = version.Version() try: headers = { "User-Agent": f"comtool_v{version.major}.{version.minor}.{version.dev}-{platform.platform()}" } page = requests.post(self.releaseApiUrl2, headers=headers) if page.sta...
55
651
229
880
try: import version import parameters except ImportError: from COMTool import version, parameters import platform log = parameters.log class AutoUpdate: updateUrl = "https://github.com/Neutree/COMTool/releases" releaseApiUrl = "https://api.github.com/repos/Neutree/COMTool/releases" releaseApiU...
try: import version import parameters except ImportError: from COMTool import version, parameters import platform log = parameters.log class AutoUpdate: updateUrl = "https://github.com/Neutree/COMTool/releases" releaseApiUrl = "https://api.github.com/repos/Neutree/COMTool/releases" releaseApiU...
43,555
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool/COMTool/logger.py
102,103
92,112
i
Fake_Logger
103,105
103,105
class Fake_Logger: ''' use logging module to record log to console or file ''' def __init__(self, level="d", file_path=None, fmt = '%(asctime)s - [%(levelname)s]: %(message)s'): pass def d(self, *args): print(args) def i(self, *args): FILL_FUNC_BODY def w(self, *args): ...
class Fake_Logger: ''' use logging module to record log to console or file ''' def __init__(self, level="d", file_path=None, fmt = '%(asctime)s - [%(levelname)s]: %(message)s'): pass def d(self, *args): print(args) def i(self, *args): FILL_FUNC_BODY def w(self, *args): ...
print(args)
print(args)
1
145
9
154
''' logger wrapper based oh logging @author neucrack @license MIT copyright 2020-2021 neucrack CZD666666@gmail.com ''' import logging import coloredlogs import sys class Logger: ''' use logging module to record log to console or file ''' def __init__(self, level="d", stdout = True, ...
''' logger wrapper based oh logging @author neucrack @license MIT copyright 2020-2021 neucrack CZD666666@gmail.com ''' import logging import coloredlogs import sys class Logger: ''' use logging module to record log to console or file ''' def __init__(self, level="d", stdout = True, ...
43,556
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool/COMTool/logger.py
74,75
14,92
i
Logger
75,80
75,80
class Logger: ''' use logging module to record log to console or file ''' def __init__(self, level="d", stdout = True, file_path=None, fmt = '%(asctime)s - [%(levelname)s] - %(message)s', logger_name = "logger"): self.log = logging.getLogger(logger_name) ...
class Logger: ''' use logging module to record log to console or file ''' def __init__(self, level="d", stdout = True, file_path=None, fmt = '%(asctime)s - [%(levelname)s] - %(message)s', logger_name = "logger"): self.log = logging.getLogger(logger_name) ...
out = "" for arg in args: out += " " + str(arg) self.log.info(out)
out = "" for arg in args: out += " " + str(arg) self.log.info(out)
14
714
39
753
''' logger wrapper based oh logging @author neucrack @license MIT copyright 2020-2021 neucrack CZD666666@gmail.com ''' import logging import coloredlogs import sys class Logger: ''' use logging module to record log to console or file ''' def __init__(self, level="d", stdout = True, ...
''' logger wrapper based oh logging @author neucrack @license MIT copyright 2020-2021 neucrack CZD666666@gmail.com ''' import logging import coloredlogs import sys class Logger: ''' use logging module to record log to console or file ''' def __init__(self, level="d", stdout = True, ...
43,557
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool/COMTool/parameters.py
29,30
1,149
get_config_path
30,39
30,39
import shutil import sys, os from datetime import datetime import json try: from i18n import _, set_locale from logger import Logger except ImportError: from COMTool.i18n import _, set_locale from COMTool.logger import Logger appName = "COMTool" appIcon = "assets/logo.png" appLogo = "assets/logo.png" ...
import shutil import sys, os from datetime import datetime import json try: from i18n import _, set_locale from logger import Logger except ImportError: from COMTool.i18n import _, set_locale from COMTool.logger import Logger appName = "COMTool" appIcon = "assets/logo.png" appLogo = "assets/logo.png" ...
configFilePath = configFileName try: configFilePath = os.path.join(configFileDir, configFileName) if not os.path.exists(configFileDir): os.makedirs(configFileDir) except: pass return configFilePath
configFilePath = configFileName try: configFilePath = os.path.join(configFileDir, configFileName) if not os.path.exists(configFileDir): os.makedirs(configFileDir) except: pass return configFilePath
16
1,471
80
1,551
import shutil import sys, os from datetime import datetime import json try: from i18n import _, set_locale from logger import Logger except ImportError: from COMTool.i18n import _, set_locale from COMTool.logger import Logger appName = "COMTool" appIcon = "assets/logo.png" appLogo = "assets/logo.png" ...
import shutil import sys, os from datetime import datetime import json try: from i18n import _, set_locale from logger import Logger except ImportError: from COMTool.i18n import _, set_locale from COMTool.logger import Logger appName = "COMTool" appIcon = "assets/logo.png" appLogo = "assets/logo.png" ...
43,558
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool/COMTool/parameters.py
91,92
55,122
save
Parameters
92,98
92,98
class Parameters: config = { "version": 3, "skin": "light", "locale": "en", "encoding": "UTF-8", "skipVersion": None, "connId": "serial", "pluginsInfo": { # enabled plugins ID "external": { # "myplugin2": { ...
class Parameters: config = { "version": 3, "skin": "light", "locale": "en", "encoding": "UTF-8", "skipVersion": None, "connId": "serial", "pluginsInfo": { # enabled plugins ID "external": { # "myplugin2": { ...
path = os.path.abspath(path) if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) with open(path, "w", encoding="utf-8") as f: json.dump(self.config, f, indent=4, ensure_ascii=False)
path = os.path.abspath(path) if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) with open(path, "w", encoding="utf-8") as f: json.dump(self.config, f, indent=4, ensure_ascii=False)
17
554
103
657
import shutil import sys, os from datetime import datetime import json try: from i18n import _, set_locale from logger import Logger except ImportError: from COMTool.i18n import _, set_locale from COMTool.logger import Logger appName = "COMTool" appIcon = "assets/logo.png" appLogo = "assets/logo.png" ...
import shutil import sys, os from datetime import datetime import json try: from i18n import _, set_locale from logger import Logger except ImportError: from COMTool.i18n import _, set_locale from COMTool.logger import Logger appName = "COMTool" appIcon = "assets/logo.png" appLogo = "assets/logo.png" ...
43,560
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool/COMTool/test.py
65,66
61,100
_getColorByfmt
A
66,80
66,80
class A: def __init__(self) -> None: self.lastColor = None def _getColorByfmt(self, fmt:bytes): FILL_FUNC_BODY def _texSplitByColor(self, text:bytes): if not self.lastColor: self.lastColor = "#000000" colorFmt = re.findall(rb'\x1b\[.*?m', text) colorStrs = [] ...
class A: def __init__(self) -> None: self.lastColor = None def _getColorByfmt(self, fmt:bytes): FILL_FUNC_BODY def _texSplitByColor(self, text:bytes): if not self.lastColor: self.lastColor = "#000000" colorFmt = re.findall(rb'\x1b\[.*?m', text) colorStrs = [] ...
colors = { b"0": "#000000", b"31": "#ff0000", b"32": "#008000", b"33": "#ffff00" } fmt = fmt[2:-1].split(b";") if len(fmt) == 1: color = colors[b"0"] else: style, color = fmt color = colors[color]...
colors = { b"0": "#000000", b"31": "#ff0000", b"32": "#008000", b"33": "#ffff00" } fmt = fmt[2:-1].split(b";") if len(fmt) == 1: color = colors[b"0"] else: style, color = fmt color = colors[color]...
32
270
137
407
# import unittest,sys # from COMTool import Main,helpAbout # # class COMTest(unittest.TestCase): # # def setUp(self): # print("setup") # # def tearDown(self): # print("teardown") # # def test_1(self): # print("test",sys.prefix) # Main.main() # # if __name__=="__main__": # ...
# import unittest,sys # from COMTool import Main,helpAbout # # class COMTest(unittest.TestCase): # # def setUp(self): # print("setup") # # def tearDown(self): # print("teardown") # # def test_1(self): # print("test",sys.prefix) # Main.main() # # if __name__=="__main__": # ...
43,561
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool/COMTool/utils.py
34,35
1,98
str_to_bytes
35,94
35,94
from datetime import datetime import binascii import re def datetime_format_ms(dt): res = dt.strftime("%Y-%m-%d %H:%M:%S") return '{}.{:03d}'.format(res, int(round(dt.microsecond/1000))) def hexlify(bs, sed=b' '): tmp = b'%02X' + sed.encode() return b''.join([tmp % b for b in bs]) def bytes_to_hex_s...
from datetime import datetime import binascii import re def datetime_format_ms(dt): res = dt.strftime("%Y-%m-%d %H:%M:%S") return '{}.{:03d}'.format(res, int(round(dt.microsecond/1000))) def hexlify(bs, sed=b' '): tmp = b'%02X' + sed.encode() return b''.join([tmp % b for b in bs]) def bytes_to_hex_s...
if not escape: return data.encodeing(encoding) final = b"" p = 0 escapes = { "a": (b'\a', 2), "b": (b'\b', 2), "f": (b'\f', 2), "n": (b'\n', 2), "r": (b'\r', 2), "t": (b'\t', 2), "v": (b'\v', 2), "\\": (b'\\', 2), "\'": (b"'...
if not escape: return data.encodeing(encoding) final = b"" p = 0 escapes = { "a": (b'\a', 2), "b": (b'\b', 2), "f": (b'\f', 2), "n": (b'\n', 2), "r": (b'\r', 2), "t": (b'\t', 2), "v": (b'\v', 2), "\\": (b'\\', 2), "\'": (b"'...
219
414
687
1,101
from datetime import datetime import binascii import re def datetime_format_ms(dt): res = dt.strftime("%Y-%m-%d %H:%M:%S") return '{}.{:03d}'.format(res, int(round(dt.microsecond/1000))) def hexlify(bs, sed=b' '): tmp = b'%02X' + sed.encode() return b''.join([tmp % b for b in bs]) def bytes_to_hex_s...
from datetime import datetime import binascii import re def datetime_format_ms(dt): res = dt.strftime("%Y-%m-%d %H:%M:%S") return '{}.{:03d}'.format(res, int(round(dt.microsecond/1000))) def hexlify(bs, sed=b' '): tmp = b'%02X' + sed.encode() return b''.join([tmp % b for b in bs]) def bytes_to_hex_s...
43,562
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool/COMTool/version.py
26,27
8,38
load_dict
Version
27,33
27,33
class Version: def __init__(self, major=major, minor=minor, dev=dev, name="", desc=""): self.major = major self.minor = minor self.dev = dev self.name = name self.desc = desc def dump_dict(self): ret = { "major": self.major, "minor": sel...
class Version: def __init__(self, major=major, minor=minor, dev=dev, name="", desc=""): self.major = major self.minor = minor self.dev = dev self.name = name self.desc = desc def dump_dict(self): ret = { "major": self.major, "minor": sel...
self.major = obj['major'] self.minor = obj['minor'] self.dev= obj['dev'] self.name = obj['name'] self.desc = obj['desc']
self.major = obj['major'] self.minor = obj['minor'] self.dev= obj['dev'] self.name = obj['name'] self.desc = obj['desc']
14
237
59
296
major = 3 minor = 4 dev = 1 __version__ = "{}.{}.{}".format(major, minor, dev) class Version: def __init__(self, major=major, minor=minor, dev=dev, name="", desc=""): self.major = major self.minor = minor self.dev = dev self.name = name self.desc = desc def dump_d...
major = 3 minor = 4 dev = 1 __version__ = "{}.{}.{}".format(major, minor, dev) class Version: def __init__(self, major=major, minor=minor, dev=dev, name="", desc=""): self.major = major self.minor = minor self.dev = dev self.name = name self.desc = desc def dump_d...
43,563
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool/COMTool/win32_utils.py
86,87
1,111
addShadowEffect
87,111
87,111
from ctypes import WinDLL, c_bool, c_int, c_longlong, POINTER, byref, Structure from ctypes.wintypes import DWORD, HWND, LONG, LPCVOID from enum import Enum class DWMNCRENDERINGPOLICY(Enum): DWMNCRP_USEWINDOWSTYLE = 0 DWMNCRP_DISABLED = 1 DWMNCRP_ENABLED = 2 DWMNCRP_LAS = 3 class DWMWINDOWATTRIBUTE(...
from ctypes import WinDLL, c_bool, c_int, c_longlong, POINTER, byref, Structure from ctypes.wintypes import DWORD, HWND, LONG, LPCVOID from enum import Enum class DWMNCRENDERINGPOLICY(Enum): DWMNCRP_USEWINDOWSTYLE = 0 DWMNCRP_DISABLED = 1 DWMNCRP_ENABLED = 2 DWMNCRP_LAS = 3 class DWMWINDOWATTRIBUTE(...
dwmapi = WinDLL("dwmapi") DwmExtendFrameIntoClientArea = dwmapi.DwmExtendFrameIntoClientArea DwmSetWindowAttribute = dwmapi.DwmSetWindowAttribute DwmExtendFrameIntoClientArea.restype = LONG DwmSetWindowAttribute.restype = LONG DwmSetWindowAttribute.argtypes = [c_int, DWORD, LPCVOID, DWORD] D...
dwmapi = WinDLL("dwmapi") DwmExtendFrameIntoClientArea = dwmapi.DwmExtendFrameIntoClientArea DwmSetWindowAttribute = dwmapi.DwmSetWindowAttribute DwmExtendFrameIntoClientArea.restype = LONG DwmSetWindowAttribute.restype = LONG DwmSetWindowAttribute.argtypes = [c_int, DWORD, LPCVOID, DWORD] D...
89
1,261
483
1,744
from ctypes import WinDLL, c_bool, c_int, c_longlong, POINTER, byref, Structure from ctypes.wintypes import DWORD, HWND, LONG, LPCVOID from enum import Enum class DWMNCRENDERINGPOLICY(Enum): DWMNCRP_USEWINDOWSTYLE = 0 DWMNCRP_DISABLED = 1 DWMNCRP_ENABLED = 2 DWMNCRP_LAS = 3 class DWMWINDOWATTRIBUTE(...
from ctypes import WinDLL, c_bool, c_int, c_longlong, POINTER, byref, Structure from ctypes.wintypes import DWORD, HWND, LONG, LPCVOID from enum import Enum class DWMNCRENDERINGPOLICY(Enum): DWMNCRP_USEWINDOWSTYLE = 0 DWMNCRP_DISABLED = 1 DWMNCRP_ENABLED = 2 DWMNCRP_LAS = 3 class DWMWINDOWATTRIBUTE(...
43,565
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool
/home/hieuvd/dung_repo/raw/stars_03/Neutree_COMTool/COMTool/tool/send_curve_demo.py
20,21
11,23
send
Conn
21,23
21,23
class Conn: def __init__(self, addr, port): self.addr = addr self.port = port self.sock = None # connect tcp server self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.addr, self.port)) def send(self, data): FILL_FUNC_BODY
class Conn: def __init__(self, addr, port): self.addr = addr self.port = port self.sock = None # connect tcp server self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.addr, self.port)) def send(self, data): FILL_FUNC_BODY
self.sock.send(data)
self.sock.send(data)
1
110
14
124
''' execute `pip install comtool --upgrade` first Then run a TCP server on COMTool Finally run this script to connect the server and send data ''' from COMTool.plugins import graph_protocol import math import socket import time class Conn: def __init__(self, addr, port): self.addr = addr ...
''' execute `pip install comtool --upgrade` first Then run a TCP server on COMTool Finally run this script to connect the server and send data ''' from COMTool.plugins import graph_protocol import math import socket import time class Conn: def __init__(self, addr, port): self.addr = addr ...
43,566
/home/hieuvd/dung_repo/raw/stars_03/NotJoeMartinez_yt-fts/yt-fts
/home/hieuvd/dung_repo/raw/stars_03/NotJoeMartinez_yt-fts/yt-fts/yt_fts/config.py
9,10
1,120
get_config_path
10,30
10,30
import sys import os import chromadb from chromadb.config import Settings def get_config_path(): FILL_FUNC_BODYdef make_config_dir(): platform = sys.platform try: if platform == 'win32': config_path = os.path.join(os.getenv('APPDATA'), 'yt-fts') # check if config dir exists...
import sys import os import chromadb from chromadb.config import Settings def get_config_path(): FILL_FUNC_BODYdef make_config_dir(): platform = sys.platform try: if platform == 'win32': config_path = os.path.join(os.getenv('APPDATA'), 'yt-fts') # check if config dir exists...
platform = sys.platform if platform == 'win32': config_path = os.path.join(os.getenv('APPDATA'), 'yt-fts') if not os.path.exists(config_path): return None else: return config_path if platform == 'darwin' or platform == 'linux': config_path = os.pat...
platform = sys.platform if platform == 'win32': config_path = os.path.join(os.getenv('APPDATA'), 'yt-fts') if not os.path.exists(config_path): return None else: return config_path if platform == 'darwin' or platform == 'linux': config_path = os.pat...
42
845
176
1,021
import sys import os import chromadb from chromadb.config import Settings def get_config_path(): FILL_FUNC_BODYdef make_config_dir(): platform = sys.platform try: if platform == 'win32': config_path = os.path.join(os.getenv('APPDATA'), 'yt-fts') # check if config dir exists...
import sys import os import chromadb from chromadb.config import Settings def get_config_path(): FILL_FUNC_BODYdef make_config_dir(): platform = sys.platform try: if platform == 'win32': config_path = os.path.join(os.getenv('APPDATA'), 'yt-fts') # check if config dir exists...
43,568
/home/hieuvd/dung_repo/raw/stars_03/NotJoeMartinez_yt-fts/yt-fts
/home/hieuvd/dung_repo/raw/stars_03/NotJoeMartinez_yt-fts/yt-fts/yt_fts/embeddings.py
7,8
1,44
add_embeddings_to_chroma
8,38
8,38
from openai import OpenAI from rich.progress import track from rich.console import Console from .config import get_chroma_client def add_embeddings_to_chroma(subs, openai_client): FILL_FUNC_BODYdef get_embedding(text, model="text-embedding-ada-002", client=None): if client is None: client = OpenAI() tex...
from openai import OpenAI from rich.progress import track from rich.console import Console from .config import get_chroma_client def add_embeddings_to_chroma(subs, openai_client): FILL_FUNC_BODYdef get_embedding(text, model="text-embedding-ada-002", client=None): if client is None: client = OpenAI() tex...
chroma_client = get_chroma_client() collection = chroma_client.get_or_create_collection(name="subEmbeddings") for sub in track(subs, description="Getting embeddings"): channel_id = sub[0] video_id = sub[1] start_time = sub[2] text = sub[3] if text == '': ...
chroma_client = get_chroma_client() collection = chroma_client.get_or_create_collection(name="subEmbeddings") for sub in track(subs, description="Getting embeddings"): channel_id = sub[0] video_id = sub[1] start_time = sub[2] text = sub[3] if text == '': ...
54
146
275
421
from openai import OpenAI from rich.progress import track from rich.console import Console from .config import get_chroma_client def add_embeddings_to_chroma(subs, openai_client): FILL_FUNC_BODYdef get_embedding(text, model="text-embedding-ada-002", client=None): if client is None: client = OpenAI() tex...
from openai import OpenAI from rich.progress import track from rich.console import Console from .config import get_chroma_client def add_embeddings_to_chroma(subs, openai_client): FILL_FUNC_BODYdef get_embedding(text, model="text-embedding-ada-002", client=None): if client is None: client = OpenAI() tex...
43,569
/home/hieuvd/dung_repo/raw/stars_03/NotJoeMartinez_yt-fts/yt-fts
/home/hieuvd/dung_repo/raw/stars_03/NotJoeMartinez_yt-fts/yt-fts/yt_fts/list.py
12,13
1,138
show_video_transcript
13,41
13,41
import sqlite3 from rich.console import Console from rich.table import Table from .db_utils import get_title_from_db from .utils import time_to_secs, get_time_delta from .config import get_db_path def show_video_transcript(video_id): FILL_FUNC_BODYdef show_video_list(channel_id): con = sqlite3.connect(get_db...
import sqlite3 from rich.console import Console from rich.table import Table from .db_utils import get_title_from_db from .utils import time_to_secs, get_time_delta from .config import get_db_path def show_video_transcript(video_id): FILL_FUNC_BODYdef show_video_list(channel_id): con = sqlite3.connect(get_db...
con = sqlite3.connect(get_db_path()) cur = con.cursor() cur.execute("SELECT * FROM subtitles WHERE video_id=?", (video_id,)) rows = cur.fetchall() console = Console() word_count = 0 for row in rows: timestamp = row[2] time = time_to_secs(timestamp) url = f"https://ww...
con = sqlite3.connect(get_db_path()) cur = con.cursor() cur.execute("SELECT * FROM subtitles WHERE video_id=?", (video_id,)) rows = cur.fetchall() console = Console() word_count = 0 for row in rows: timestamp = row[2] time = time_to_secs(timestamp) url = f"https://ww...
64
1,095
364
1,459
import sqlite3 from rich.console import Console from rich.table import Table from .db_utils import get_title_from_db from .utils import time_to_secs, get_time_delta from .config import get_db_path def show_video_transcript(video_id): FILL_FUNC_BODYdef show_video_list(channel_id): con = sqlite3.connect(get_db...
import sqlite3 from rich.console import Console from rich.table import Table from .db_utils import get_title_from_db from .utils import time_to_secs, get_time_delta from .config import get_db_path def show_video_transcript(video_id): FILL_FUNC_BODYdef show_video_list(channel_id): con = sqlite3.connect(get_db...
43,570
/home/hieuvd/dung_repo/raw/stars_03/NotJoeMartinez_yt-fts/yt-fts
/home/hieuvd/dung_repo/raw/stars_03/NotJoeMartinez_yt-fts/yt-fts/yt_fts/update.py
6,7
1,42
update_channel
10,42
7,42
import tempfile, os from .download import get_videos_list, download_vtts, vtt_to_db from .db_utils import add_channel_info, get_num_vids, get_vid_ids_by_channel_id def update_channel(channel_id, channel_name, language, number_of_jobs, s): FILL_FUNC_BODY
import tempfile, os from .download import get_videos_list, download_vtts, vtt_to_db from .db_utils import add_channel_info, get_num_vids, get_vid_ids_by_channel_id def update_channel(channel_id, channel_name, language, number_of_jobs, s): """ Downloads all the videos from a channel to a tmp directory """ ...
with tempfile.TemporaryDirectory() as tmp_dir: channel_url = f"https://www.youtube.com/channel/{channel_id}/videos" public_video_ids = get_videos_list(channel_url) num_public_vids = len(public_video_ids) num_local_vids = get_num_vids(channel_id) if num_public_vids == num_l...
""" Downloads all the videos from a channel to a tmp directory """ with tempfile.TemporaryDirectory() as tmp_dir: channel_url = f"https://www.youtube.com/channel/{channel_id}/videos" public_video_ids = get_videos_list(channel_url) num_public_vids = len(public_video_ids) ...
97
117
447
564
import tempfile, os from .download import get_videos_list, download_vtts, vtt_to_db from .db_utils import add_channel_info, get_num_vids, get_vid_ids_by_channel_id def update_channel(channel_id, channel_name, language, number_of_jobs, s): FILL_FUNC_BODY
import tempfile, os from .download import get_videos_list, download_vtts, vtt_to_db from .db_utils import add_channel_info, get_num_vids, get_vid_ids_by_channel_id def update_channel(channel_id, channel_name, language, number_of_jobs, s): """ Downloads all the videos from a channel to a tmp directory """ ...
43,571
/home/hieuvd/dung_repo/raw/stars_03/NotJoeMartinez_yt-fts/yt-fts
/home/hieuvd/dung_repo/raw/stars_03/NotJoeMartinez_yt-fts/yt-fts/yt_fts/utils.py
95,96
1,188
check_ss_enabled
96,120
96,120
""" This is where I'm putting all the functions that don't belong anywhere else """ import re import sqlite3 def show_message(code): error_dict = { "search_too_long": "Error: Search text must be less than 40 characters", "no_matches_found": "No matches found.\n- Try shortening the search text or us...
""" This is where I'm putting all the functions that don't belong anywhere else """ import re import sqlite3 def show_message(code): error_dict = { "search_too_long": "Error: Search text must be less than 40 characters", "no_matches_found": "No matches found.\n- Try shortening the search text or us...
from yt_fts.config import get_db_path con = sqlite3.connect(get_db_path()) cur = con.cursor() if channel_id is None: cur.execute(""" SELECT channel_id FROM SemanticSearchEnabled """) else: cur.execute(""" SELECT channel_id FROM SemanticSearch...
from yt_fts.config import get_db_path con = sqlite3.connect(get_db_path()) cur = con.cursor() if channel_id is None: cur.execute(""" SELECT channel_id FROM SemanticSearchEnabled """) else: cur.execute(""" SELECT channel_id FROM SemanticSearch...
50
1,612
181
1,793
""" This is where I'm putting all the functions that don't belong anywhere else """ import re import sqlite3 def show_message(code): error_dict = { "search_too_long": "Error: Search text must be less than 40 characters", "no_matches_found": "No matches found.\n- Try shortening the search text or us...
""" This is where I'm putting all the functions that don't belong anywhere else """ import re import sqlite3 def show_message(code): error_dict = { "search_too_long": "Error: Search text must be less than 40 characters", "no_matches_found": "No matches found.\n- Try shortening the search text or us...
43,572
/home/hieuvd/dung_repo/raw/stars_03/NotJoeMartinez_yt-fts/yt-fts
/home/hieuvd/dung_repo/raw/stars_03/NotJoeMartinez_yt-fts/yt-fts/yt_fts/vector_search.py
72,73
1,130
print_vector_search_results
82,121
73,121
import chromadb from rich.console import Console from sqlite_utils import Database from .utils import time_to_secs, bold_query_matches from .embeddings import get_embedding from .config import get_chroma_client from .db_utils import get_channel_name_from_video_id, get_title_from_db from .download import get_channel...
import chromadb from rich.console import Console from sqlite_utils import Database from .utils import time_to_secs, bold_query_matches from .embeddings import get_embedding from .config import get_chroma_client from .db_utils import get_channel_name_from_video_id, get_title_from_db from .download import get_channel...
console = Console() channel_names = [] for match in reversed(res): distance = match["distance"] link = match["link"] text = bold_query_matches(match["subs"], query) time_stamp = match["start_time"] channel_id = match["channel_id"] video_id = match["...
""" { 'channel_name': 'Peter Whidden', 'video_title': 'Training AI to Play Pokemon with Reinforcement Learning - YouTube', 'subs': 'choosing a Pokemon and winning its first', 'start_time': '00:22:14.909', 'video_id': 'DcYLT37ImBY', 'link': 'https://youtu.be/DcYLT37ImBY?t=1331'} ...
92
906
472
1,378
import chromadb from rich.console import Console from sqlite_utils import Database from .utils import time_to_secs, bold_query_matches from .embeddings import get_embedding from .config import get_chroma_client from .db_utils import get_channel_name_from_video_id, get_title_from_db from .download import get_channel...
import chromadb from rich.console import Console from sqlite_utils import Database from .utils import time_to_secs, bold_query_matches from .embeddings import get_embedding from .config import get_chroma_client from .db_utils import get_channel_name_from_video_id, get_title_from_db from .download import get_channel...
43,651
/home/hieuvd/dung_repo/raw/stars_03/OpenBMB_BMInf/BMInf
/home/hieuvd/dung_repo/raw/stars_03/OpenBMB_BMInf/BMInf/bminf/wrapper.py
39,40
1,59
wrapper
53,59
40,59
from typing import Tuple import torch from .scheduler import TransformerBlockList from .quantization import QuantizedLinear import warnings from cpm_kernels.library import cudart def _wrapper(model : torch.nn.Module, quantization, is_in_blocklist : bool, memory_limit : int) -> Tuple[torch.nn.Module, bool]: if not ...
from typing import Tuple import torch from .scheduler import TransformerBlockList from .quantization import QuantizedLinear import warnings from cpm_kernels.library import cudart def _wrapper(model : torch.nn.Module, quantization, is_in_blocklist : bool, memory_limit : int) -> Tuple[torch.nn.Module, bool]: if not ...
if memory_limit is None: memory_limit = cudart.cudaMemGetInfo()[0] * 0.9 model, found_linear = _wrapper(model, quantization, False, memory_limit) if quantization and not found_linear: warnings.warn("`quantization` is set to true but `torch.nn.Linear` is not found in your model.") return ...
"""Enable the optimization of BMInf on your model. This function automatically looks for the `nn.ModuleList` and `nn.Linear` layers in the model and replaces them. Args: model (torch.nn.Module): your model. quantization (bool): enable model quantization. (default: True) memory_...
36
583
106
689
from typing import Tuple import torch from .scheduler import TransformerBlockList from .quantization import QuantizedLinear import warnings from cpm_kernels.library import cudart def _wrapper(model : torch.nn.Module, quantization, is_in_blocklist : bool, memory_limit : int) -> Tuple[torch.nn.Module, bool]: if not ...
from typing import Tuple import torch from .scheduler import TransformerBlockList from .quantization import QuantizedLinear import warnings from cpm_kernels.library import cudart def _wrapper(model : torch.nn.Module, quantization, is_in_blocklist : bool, memory_limit : int) -> Tuple[torch.nn.Module, bool]: if not ...
43,652
/home/hieuvd/dung_repo/raw/stars_03/OpenBMB_BMInf/BMInf
/home/hieuvd/dung_repo/raw/stars_03/OpenBMB_BMInf/BMInf/example/glm-130B/model_convert/megatron_to_sat.py
5,6
1,71
megatron_to_sat
6,40
6,40
import os import sys import torch def megatron_to_sat(checkpoint_name, target): FILL_FUNC_BODYdef main(): dir_path = str(sys.argv[1]) target_dir = str(sys.argv[2]) iter_path = os.path.join(dir_path, 'latest_checkpointed_iteration.txt') iteration = open(iter_path).read() print(iteration) new...
import os import sys import torch def megatron_to_sat(checkpoint_name, target): FILL_FUNC_BODYdef main(): dir_path = str(sys.argv[1]) target_dir = str(sys.argv[2]) iter_path = os.path.join(dir_path, 'latest_checkpointed_iteration.txt') iteration = open(iter_path).read() print(iteration) new...
num_layer = 70 # checkpoint_name = '/thudm/workspace/hanyu/SwissArmyTransformer-old/data/global_step10400/iter_0010400/10400/mp_rank_00_model_states.pt' sd = torch.load(checkpoint_name, map_location='cpu') new_sd = {} new_sd['transformer.word_embeddings.weight'] = sd['model']['word_embeddings_for_he...
num_layer = 70 # checkpoint_name = '/thudm/workspace/hanyu/SwissArmyTransformer-old/data/global_step10400/iter_0010400/10400/mp_rank_00_model_states.pt' sd = torch.load(checkpoint_name, map_location='cpu') new_sd = {} new_sd['transformer.word_embeddings.weight'] = sd['model']['word_embeddings_for_he...
173
441
1,003
1,444
import os import sys import torch def megatron_to_sat(checkpoint_name, target): FILL_FUNC_BODYdef main(): dir_path = str(sys.argv[1]) target_dir = str(sys.argv[2]) iter_path = os.path.join(dir_path, 'latest_checkpointed_iteration.txt') iteration = open(iter_path).read() print(iteration) new...
import os import sys import torch def megatron_to_sat(checkpoint_name, target): FILL_FUNC_BODYdef main(): dir_path = str(sys.argv[1]) target_dir = str(sys.argv[2]) iter_path = os.path.join(dir_path, 'latest_checkpointed_iteration.txt') iteration = open(iter_path).read() print(iteration) new...
43,653
/home/hieuvd/dung_repo/raw/stars_03/OpenBMB_BMInf/BMInf
/home/hieuvd/dung_repo/raw/stars_03/OpenBMB_BMInf/BMInf/setup.py
44,45
1,77
main
45,75
45,75
import os import setuptools import sys import struct CONFIG = { "package_name": "bminf", "author": "a710128", "author_email": "qbjooo@qq.com", "description": "A toolkit for big model inference", "version": None } def get_readme(path): ret = "" with open(os.path.join(path, "README.md"), enc...
import os import setuptools import sys import struct CONFIG = { "package_name": "bminf", "author": "a710128", "author_email": "qbjooo@qq.com", "description": "A toolkit for big model inference", "version": None } def get_readme(path): ret = "" with open(os.path.join(path, "README.md"), enc...
path = os.path.dirname(os.path.abspath(__file__)) version = get_version(path) open( os.path.join(path, CONFIG["package_name"], "version.py"), "w", encoding="utf-8" ).write('__version__ = "%s"' % version) requires = get_requirements(path) setuptools.setup( name=CONFIG["package_name"], ...
path = os.path.dirname(os.path.abspath(__file__)) version = get_version(path) open( os.path.join(path, CONFIG["package_name"], "version.py"), "w", encoding="utf-8" ).write('__version__ = "%s"' % version) requires = get_requirements(path) setuptools.setup( name=CONFIG["package_name"], ...
58
466
336
802
import os import setuptools import sys import struct CONFIG = { "package_name": "bminf", "author": "a710128", "author_email": "qbjooo@qq.com", "description": "A toolkit for big model inference", "version": None } def get_readme(path): ret = "" with open(os.path.join(path, "README.md"), enc...
import os import setuptools import sys import struct CONFIG = { "package_name": "bminf", "author": "a710128", "author_email": "qbjooo@qq.com", "description": "A toolkit for big model inference", "version": None } def get_readme(path): ret = "" with open(os.path.join(path, "README.md"), enc...
43,661
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/demo/gpnas/CVPR2021_NAS_competition_gpnas_demo.py
27,28
1,66
preprare_trainning_data
28,43
28,43
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
## t_flag ==1 using all trainning data ## t_flag ==2 using half trainning data with open(file_name, 'r') as f: arch_dict = json.load(f) Y_all = [] X_all = [] for sub_dict in arch_dict.items(): Y_all.append(sub_dict[1]['acc'] * 100) X_all.append(np.array(sub_dict[1]['arch'...
## t_flag ==1 using all trainning data ## t_flag ==2 using half trainning data with open(file_name, 'r') as f: arch_dict = json.load(f) Y_all = [] X_all = [] for sub_dict in arch_dict.items(): Y_all.append(sub_dict[1]['acc'] * 100) X_all.append(np.array(sub_dict[1]['arch'...
57
936
261
1,197
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
43,662
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/demo/quant/quant_embedding/reader.py
88,89
33,107
nce_reader
Word2VecReader
89,106
89,106
class Word2VecReader(object): def __init__(self, dict_path, data_path, filelist, trainer_id, trainer_num, window_size=5): self.window_size_ = window_size self.data_path_ = data_path self.fil...
class Word2VecReader(object): def __init__(self, dict_path, data_path, filelist, trainer_id, trainer_num, window_size=5): self.window_size_ = window_size self.data_path_ = data_path self.fil...
for file in self.filelist: with io.open( self.data_path_ + "/" + file, 'r', encoding='utf-8') as f: logger.info("running data in {}".format(self.data_path_ + "/" + ...
for file in self.filelist: with io.open( self.data_path_ + "/" + file, 'r', encoding='utf-8') as f: logger.info("running data in {}".format(self.data_path_ + "/" + ...
63
589
213
802
# -*- coding: utf-8 -* import numpy as np import preprocess import logging import math import random import io logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger("paddle") logger.setLevel(logging.INFO) class NumpyRandomInt(object): def __init__(self, a, b, buf_siz...
# -*- coding: utf-8 -* import numpy as np import preprocess import logging import math import random import io logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger("paddle") logger.setLevel(logging.INFO) class NumpyRandomInt(object): def __init__(self, a, b, buf_siz...
43,663
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/demo/slimfacenet/dataloader/lfw.py
30,31
23,56
reader
LFW
31,52
31,52
class LFW(object): def __init__(self, imgl, imgr): self.imgl_list = imgl self.imgr_list = imgr self.shuffle_idx = [i for i in range(len(self.imgl_list))] def reader(self): FILL_FUNC_BODY def __len__(self): return len(self.imgl_list)
class LFW(object): def __init__(self, imgl, imgr): self.imgl_list = imgl self.imgr_list = imgr self.shuffle_idx = [i for i in range(len(self.imgl_list))] def reader(self): FILL_FUNC_BODY def __len__(self): return len(self.imgl_list)
while True: if len(self.shuffle_idx) == 0: self.shuffle_idx = [i for i in range(len(self.imgl_list))] return index = self.shuffle_idx.pop(0) imgl = imgreader.imread(self.imgl_list[index]) if len(imgl.shape) == 2: im...
while True: if len(self.shuffle_idx) == 0: self.shuffle_idx = [i for i in range(len(self.imgl_list))] return index = self.shuffle_idx.pop(0) imgl = imgreader.imread(self.imgl_list[index]) if len(imgl.shape) == 2: im...
78
110
317
427
# ================================================================ # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # htt...
# ================================================================ # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # htt...
43,664
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/example/auto_compression/detection/post_process.py
50,51
1,156
iou_of
59,68
51,68
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
overlap_left_top = np.maximum(boxes0[..., :2], boxes1[..., :2]) overlap_right_bottom = np.minimum(boxes0[..., 2:], boxes1[..., 2:]) overlap_area = area_of(overlap_left_top, overlap_right_bottom) area0 = area_of(boxes0[..., :2], boxes0[..., 2:]) area1 = area_of(boxes1[..., :2], boxes1[..., 2:]) ...
"""Return intersection-over-union (Jaccard index) of boxes. Args: boxes0 (N, 4): ground truth boxes. boxes1 (N or 1, 4): predicted boxes. eps: a small number to avoid 0 as denominator. Returns: iou (N): IoU values. """ overlap_left_top = np.maximum(boxes0[..., :2], bo...
38
1,755
171
1,926
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
43,665
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/example/auto_compression/detection/post_process.py
97,98
80,156
_non_max_suppression
PPYOLOEPostProcess
98,152
98,152
class PPYOLOEPostProcess(object): """ Args: input_shape (int): network input image size scale_factor (float): scale factor of ori image """ def __init__(self, score_threshold=0.4, nms_threshold=0.5, nms_top_k=10000, kee...
class PPYOLOEPostProcess(object): """ Args: input_shape (int): network input image size scale_factor (float): scale factor of ori image """ def __init__(self, score_threshold=0.4, nms_threshold=0.5, nms_top_k=10000, kee...
batch_size = prediction.shape[0] out_boxes_list = [] box_num_list = [] for batch_id in range(batch_size): bboxes, confidences = prediction[batch_id][..., :4], prediction[ batch_id][..., 4:] # nms picked_box_probs = [] picked...
batch_size = prediction.shape[0] out_boxes_list = [] box_num_list = [] for batch_id in range(batch_size): bboxes, confidences = prediction[batch_id][..., :4], prediction[ batch_id][..., 4:] # nms picked_box_probs = [] picked...
140
270
784
1,054
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
43,666
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/example/auto_compression/semantic_segmentation/data/download_data.py
31,32
1,50
download_data
32,36
32,36
# Copyright (c) 20212 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 20212 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
download_file_and_uncompress( url=url, savepath=savepath, extrapath=extrapath)
download_file_and_uncompress( url=url, savepath=savepath, extrapath=extrapath)
4
557
38
595
# Copyright (c) 20212 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 20212 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
43,668
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/example/full_quantization/picodet/post_process.py
108,109
81,228
warp_boxes
PicoDetPostProcess
111,132
109,132
class PicoDetPostProcess(object): """ Args: input_shape (int): network input image size ori_shape (int): ori image shape of before padding scale_factor (float): scale factor of ori image enable_mkldnn (bool): whether to open MKLDNN """ def __init__(self, ...
class PicoDetPostProcess(object): """ Args: input_shape (int): network input image size ori_shape (int): ori image shape of before padding scale_factor (float): scale factor of ori image enable_mkldnn (bool): whether to open MKLDNN """ def __init__(self, ...
width, height = ori_shape[1], ori_shape[0] n = len(boxes) if n: # warp points xy = np.ones((n * 4, 3)) xy[:, :2] = boxes[:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape( n * 4, 2) # x1y1, x2y2, x1y2, x2y1 # xy = xy @ M.T # transform ...
"""Apply transform to boxes """ width, height = ori_shape[1], ori_shape[0] n = len(boxes) if n: # warp points xy = np.ones((n * 4, 3)) xy[:, :2] = boxes[:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape( n * 4, 2) # x1y1, x2y2, x1y2, x2y1 ...
108
1,608
382
1,990
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
43,669
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/example/full_quantization/ppyoloe/post_process.py
51,52
1,158
iou_of
60,69
52,69
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
overlap_left_top = np.maximum(boxes0[..., :2], boxes1[..., :2]) overlap_right_bottom = np.minimum(boxes0[..., 2:], boxes1[..., 2:]) overlap_area = area_of(overlap_left_top, overlap_right_bottom) area0 = area_of(boxes0[..., :2], boxes0[..., 2:]) area1 = area_of(boxes1[..., :2], boxes1[..., 2:]) ...
"""Return intersection-over-union (Jaccard index) of boxes. Args: boxes0 (N, 4): ground truth boxes. boxes1 (N or 1, 4): predicted boxes. eps: a small number to avoid 0 as denominator. Returns: iou (N): IoU values. """ overlap_left_top = np.maximum(boxes0[..., :2], bo...
38
1,758
171
1,929
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
43,670
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/example/full_quantization/ppyoloe/post_process.py
98,99
81,158
_non_max_suppression
PPYOLOEPostProcess
99,154
99,154
class PPYOLOEPostProcess(object): """ Args: input_shape (int): network input image size scale_factor (float): scale factor of ori image """ def __init__(self, score_threshold=0.4, nms_threshold=0.5, nms_top_k=10000, kee...
class PPYOLOEPostProcess(object): """ Args: input_shape (int): network input image size scale_factor (float): scale factor of ori image """ def __init__(self, score_threshold=0.4, nms_threshold=0.5, nms_top_k=10000, kee...
batch_size = prediction.shape[0] out_boxes_list = [] box_num_list = [] for batch_id in range(batch_size): bboxes, confidences = prediction[batch_id][..., :4], prediction[ batch_id][..., 4:] # nms picked_box_probs = [] picked...
batch_size = prediction.shape[0] out_boxes_list = [] box_num_list = [] for batch_id in range(batch_size): bboxes, confidences = prediction[batch_id][..., :4], prediction[ batch_id][..., 4:] # nms picked_box_probs = [] picked...
142
270
786
1,056
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
43,671
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/example/post_training_quantization/detection/post_process.py
19,20
1,158
hard_nms
29,51
20,51
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
scores = box_scores[:, -1] boxes = box_scores[:, :-1] picked = [] indexes = np.argsort(scores) indexes = indexes[-candidate_size:] while len(indexes) > 0: current = indexes[-1] picked.append(current) if 0 < top_k == len(picked) or len(indexes) == 1: break ...
""" Args: box_scores (N, 5): boxes in corner-form and probabilities. iou_threshold: intersection over union threshold. top_k: keep top_k results. If k <= 0, keep all the results. candidate_size: only consider the candidates with the highest scores. Returns: picked: a...
63
1,708
234
1,942
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
43,672
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/example/post_training_quantization/detection/post_process.py
98,99
81,158
_non_max_suppression
PPYOLOEPostProcess
99,154
99,154
class PPYOLOEPostProcess(object): """ Args: input_shape (int): network input image size scale_factor (float): scale factor of ori image """ def __init__(self, score_threshold=0.4, nms_threshold=0.5, nms_top_k=10000, kee...
class PPYOLOEPostProcess(object): """ Args: input_shape (int): network input image size scale_factor (float): scale factor of ori image """ def __init__(self, score_threshold=0.4, nms_threshold=0.5, nms_top_k=10000, kee...
batch_size = prediction.shape[0] out_boxes_list = [] box_num_list = [] for batch_id in range(batch_size): bboxes, confidences = prediction[batch_id][..., :4], prediction[ batch_id][..., 4:] # nms picked_box_probs = [] picked...
batch_size = prediction.shape[0] out_boxes_list = [] box_num_list = [] for batch_id in range(batch_size): bboxes, confidences = prediction[batch_id][..., :4], prediction[ batch_id][..., 4:] # nms picked_box_probs = [] picked...
142
270
786
1,056
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
43,674
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/analysis/model_size.py
21,22
1,36
model_size
31,36
22,36
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
size = 0 for block in program.blocks: for param in block.all_parameters(): size += np.product(param.shape) return size
""" Get total value numbers of all parameters. Args: program(paddle.static.Program): The program used to calculate model size. Returns: int: The total count of all parameters. """ size = 0 for block in program.blocks: for param in block.all_parameters(): ...
16
270
46
316
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
43,677
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/auto_compression/config_helpers.py
50,51
1,69
extract_train_config
58,69
51,69
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
if config is None: return None if isinstance(config, str): config = load_config(config) if isinstance(config, dict): for key, value in config.items(): if key == TRAIN_CONFIG_NAME: return TrainConfig( **value) if value is not None else T...
"""Extract configuration items of training from file or dict. And fields validation is enable. Args: config(str, dict): The path of configuration file or a dict storing information about training. Returns: An instance of paddleslim.auto_compression.TrainConfig """ if config is None: ...
46
588
114
702
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
43,679
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/common/cached_reader.py
25,26
1,59
cached_reader
35,59
26,59
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
np.random.seed(cached_id) cache_path = os.path.join(cache_path, str(cached_id)) _logger.debug('read data from: {}'.format(cache_path)) def s_reader(): if os.path.isdir(cache_path): for file_name in open(os.path.join(cache_path, "list")): yield np.load( ...
""" Sample partial data from reader and cache them into local file system. Args: reader: Iterative data source. sampled_rate(float): The sampled rate used to sample partial data for evaluation. None means using all data in eval_reader. default: None. cache_path(str): The path to cac...
66
370
302
672
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
43,680
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/common/client.py
98,99
33,149
update
Client
99,139
99,139
class Client(object): def __init__(self, controller, address, client_name): self._controller = controller self._address = address self._ip = self._address[0] self._port = self._address[1] self._client_name = client_name self._params_dict = None self.init_wait ...
class Client(object): def __init__(self, controller, address, client_name): self._controller = controller self._address = address self._ip = self._address[0] self._port = self._address[1] self._client_name = client_name self._params_dict = None self.init_wait ...
assert self._params_dict != None, "Please call next_token to get token first, then call update" current_params_dict = self._controller.update( rewards, self._params_dict, **kwargs) params_grad = compute_grad(current_params_dict, self._params_dict) _logger.debug("Client: updat...
assert self._params_dict != None, "Please call next_token to get token first, then call update" current_params_dict = self._controller.update( rewards, self._params_dict, **kwargs) params_grad = compute_grad(current_params_dict, self._params_dict) _logger.debug("Client: updat...
107
956
560
1,516
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
43,681
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/common/config_helper.py
33,34
1,61
load_config
41,54
34,54
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
if config is None: return None assert isinstance( config, str), f"config should be str but got type(config)={type(config)}" assert os.path.exists(config) and os.path.isfile( config), f"{config} not found or it is not a file." with open(config) as f: cfg = yaml.loa...
"""Load configurations from yaml file into dict. Fields validation is skipped for loading some custom information. Args: config(str): The path of configuration file. Returns: dict: A dict storing configuration information. """ if config is None: return None assert isinsta...
42
452
140
592
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
43,682
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/common/controller_client.py
50,51
26,132
update
ControllerClient
59,79
51,79
class ControllerClient(object): """ Controller client. Args: server_ip(str): The ip that controller server listens on. None means getting the ip automatically. Default: None. server_port(int): The port that controller server listens on. 0 means getting usable port automatically. Default: 0. ...
class ControllerClient(object): """ Controller client. Args: server_ip(str): The ip that controller server listens on. None means getting the ip automatically. Default: None. server_port(int): The port that controller server listens on. 0 means getting usable port automatically. Default: 0. ...
ControllerClient.START = False socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) errno = socket_client.connect_ex((self.server_ip, self.server_port)) if errno != 0: _logger.info("Server is closed!!!") os._exit(0) else: tokens = ...
""" Update the controller according to latest tokens and reward. Args: tokens(list<int>): The tokens generated in last step. reward(float): The reward of tokens. iter(int): The iteration number of current client. """ ControllerClient.START = F...
52
822
252
1,074
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
43,683
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/common/controller_server.py
86,87
28,159
run
ControllerServer
89,159
87,159
class ControllerServer(object): """The controller wrapper with a socket server to handle the request of search agent. Args: controller(slim.searcher.Controller): The controller used to generate tokens. address(tuple): The address of current server binding with format (ip, port). Default: ('', 0)...
class ControllerServer(object): """The controller wrapper with a socket server to handle the request of search agent. Args: controller(slim.searcher.Controller): The controller used to generate tokens. address(tuple): The address of current server binding with format (ip, port). Default: ('', 0)...
_logger.info("Controller Server run...") try: while ((self._search_steps is None) or (self._controller._iter < (self._search_steps))) and not self._closed: conn, addr = self._socket_server.accept() message = conn.recv(102...
"""Start the server. """ _logger.info("Controller Server run...") try: while ((self._search_steps is None) or (self._controller._iter < (self._search_steps))) and not self._closed: conn, addr = self._socket_server.accept(...
211
609
871
1,480
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
43,684
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/common/log_helper.py
22,23
1,54
get_logger
43,54
23,54
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
logger = logging.getLogger(name) logger.setLevel(level) handler = logging.StreamHandler() if fmt: formatter = logging.Formatter(fmt=fmt) handler.setFormatter(formatter) logger.addHandler(handler) logger.propagate = 0 return logger
""" Get logger from logging with given name, level and format without setting logging basicConfig. For setting basicConfig in paddle will disable basicConfig setting after import paddle. Args: name (str): The logger name. level (logging.LEVEL): The base level of the logger f...
19
404
96
500
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
43,685
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/common/meter.py
27,28
18,31
update
AvgrageMeter
28,31
28,31
class AvgrageMeter(object): def __init__(self): self.reset() def reset(self): self.avg = 0 self.sum = 0 self.cnt = 0 def update(self, val, n=1): FILL_FUNC_BODY
class AvgrageMeter(object): def __init__(self): self.reset() def reset(self): self.avg = 0 self.sum = 0 self.cnt = 0 def update(self, val, n=1): FILL_FUNC_BODY
self.sum += val * n self.cnt += n self.avg = self.sum / self.cnt
self.sum += val * n self.cnt += n self.avg = self.sum / self.cnt
13
79
35
114
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
43,686
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/common/patterns_common.py
108,109
1,137
is_shortcut
113,137
109,137
import os import sys sys.setrecursionlimit(10000) ALL_WEIGHT_OP = [ 'conv2d', 'mul', 'matmul', 'embedding', 'conv2d_transpose', 'depthwise_conv2d', 'batch_norm', 'layer_norm', 'instance_norm', 'sync_batch_norm', 'matmul_v2' ] def traversal_ops(op, graph, target_op_idx): """ Get all operators in the m...
import os import sys sys.setrecursionlimit(10000) ALL_WEIGHT_OP = [ 'conv2d', 'mul', 'matmul', 'embedding', 'conv2d_transpose', 'depthwise_conv2d', 'batch_norm', 'layer_norm', 'instance_norm', 'sync_batch_norm', 'matmul_v2' ] def traversal_ops(op, graph, target_op_idx): """ Get all operators in the m...
inps = op.all_inputs() pre_ops = graph.pre_ops(op) for p_op in pre_ops: if _is_identity_op(p_op): p_op = graph.pre_ops(p_op)[0] n_ops = graph.next_ops(p_op) if len(n_ops) == 1: continue ### note: only support one branch donnot have op or has one scale ...
""" op /```````````````````\\ add \\____op1___op2__..._/ """ inps = op.all_inputs() pre_ops = graph.pre_ops(op) for p_op in pre_ops: if _is_identity_op(p_op): p_op = graph.pre_ops(p_op)[0] n_ops = graph.next_ops(p_op) if len(n_ops) == 1: ...
78
1,090
328
1,418
import os import sys sys.setrecursionlimit(10000) ALL_WEIGHT_OP = [ 'conv2d', 'mul', 'matmul', 'embedding', 'conv2d_transpose', 'depthwise_conv2d', 'batch_norm', 'layer_norm', 'instance_norm', 'sync_batch_norm', 'matmul_v2' ] def traversal_ops(op, graph, target_op_idx): """ Get all operators in the m...
import os import sys sys.setrecursionlimit(10000) ALL_WEIGHT_OP = [ 'conv2d', 'mul', 'matmul', 'embedding', 'conv2d_transpose', 'depthwise_conv2d', 'batch_norm', 'layer_norm', 'instance_norm', 'sync_batch_norm', 'matmul_v2' ] def traversal_ops(op, graph, target_op_idx): """ Get all operators in the m...
43,687
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/common/rl_controller/base_env.py
25,26
21,30
step
BaseEnv
26,28
26,28
class BaseEnv: def reset(self): raise NotImplementedError('Abstract method.') def step(self): FILL_FUNC_BODY def _build_state_embedding(self): raise NotImplementedError('Abstract method.')
class BaseEnv: def reset(self): raise NotImplementedError('Abstract method.') def step(self): FILL_FUNC_BODY def _build_state_embedding(self): raise NotImplementedError('Abstract method.')
raise NotImplementedError('Abstract method.')
raise NotImplementedError('Abstract method.')
3
69
16
85
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
43,688
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/common/rl_controller/utils.py
50,51
1,55
compute_grad
51,55
51,55
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
dict3 = dict() for key, value in dict1.items(): dict3[key] = dict1[key] - dict2[key] return dict3
dict3 = dict() for key, value in dict1.items(): dict3[key] = dict1[key] - dict2[key] return dict3
15
473
47
520
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
43,689
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/common/sa_controller.py
150,151
31,201
next_tokens
SAController
160,190
151,190
class SAController(EvolutionaryController): """Simulated annealing controller. Args: range_table(list<int>): Range table. reduce_rate(float): The decay rate of temperature. init_temperature(float): Init temperature. max_try_times(int): max try times before get legal tokens. Defa...
class SAController(EvolutionaryController): """Simulated annealing controller. Args: range_table(list<int>): Range table. reduce_rate(float): The decay rate of temperature. init_temperature(float): Init temperature. max_try_times(int): max try times before get legal tokens. Defa...
if control_token: tokens = control_token[:] else: tokens = self._tokens for it in range(self._max_try_times): new_tokens = tokens[:] index = int(len(self._range_table[0]) * np.random.random()) new_tokens[index] = np.random.randint(self....
""" Get next tokens. Args: control_token: The tokens used to generate next tokens. Returns: list<int>: The next tokens. """ if control_token: tokens = control_token[:] else: tokens = self._tokens for it in ...
80
1,430
326
1,756
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
43,690
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/core/registry.py
27,28
6,37
_register_module
Registry
28,34
28,34
class Registry(object): def __init__(self, name): self._name = name self._module_dict = dict() def __repr__(self): format_str = self.__class__.__name__ + '(name={}, items={})'.format( self._name, list(self._module_dict.keys())) return format_str @property de...
class Registry(object): def __init__(self, name): self._name = name self._module_dict = dict() def __repr__(self): format_str = self.__class__.__name__ + '(name={}, items={})'.format( self._name, list(self._module_dict.keys())) return format_str @property de...
module_name = module_class.__name__ if module_name in self._module_dict: raise KeyError('{} is already registered in {}.'.format( module_name, self.name)) self._module_dict[module_name] = module_class
module_name = module_class.__name__ if module_name in self._module_dict: raise KeyError('{} is already registered in {}.'.format( module_name, self.name)) self._module_dict[module_name] = module_class
19
208
74
282
import inspect __all__ = ["Registry"] class Registry(object): def __init__(self, name): self._name = name self._module_dict = dict() def __repr__(self): format_str = self.__class__.__name__ + '(name={}, items={})'.format( self._name, list(self._module_dict.keys())) ...
import inspect __all__ = ["Registry"] class Registry(object): def __init__(self, name): self._name = name self._module_dict = dict() def __repr__(self): format_str = self.__class__.__name__ + '(name={}, items={})'.format( self._name, list(self._module_dict.keys())) ...
43,691
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/dygraph/dist/distill_helpers.py
33,34
1,42
config2yaml
37,42
34,42
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
final_yaml = dict() final_yaml['DistillConfig'] = configs f = open(yaml_path, "w") yaml.dump([final_yaml], f) f.close()
""" convert dict config to yaml. """ final_yaml = dict() final_yaml['DistillConfig'] = configs f = open(yaml_path, "w") yaml.dump([final_yaml], f) f.close()
13
353
62
415
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
43,692
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/nas/early_stop/early_stop.py
28,29
18,33
client_end
EarlyStopBase
31,33
29,33
class EarlyStopBase(object): """ Abstract early Stop algorithm. """ def get_status(self, iter, result): """Get experiment status. """ raise NotImplementedError( 'get_status in Early Stop algorithm NOT implemented.') def client_end(self): FILL_FUNC_BODY
class EarlyStopBase(object): """ Abstract early Stop algorithm. """ def get_status(self, iter, result): """Get experiment status. """ raise NotImplementedError( 'get_status in Early Stop algorithm NOT implemented.') def client_end(self): """ Stop a client, t...
raise NotImplementedError( 'client_end in Early Stop algorithm NOT implemented.')
""" Stop a client, this function may useful for the client that result is better and better. """ raise NotImplementedError( 'client_end in Early Stop algorithm NOT implemented.')
9
110
25
135
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
43,693
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/nas/gp_nas.py
122,123
21,202
get_predict_jiont
GPNAS
126,137
123,137
class GPNAS(object): """ GPNAS(Gaussian Process based Neural Architecture Search) is a neural architecture search algorithm. We model the correlation between architectue and performance from a Bayesian perspective. Specifically, by introducing a novel Gaussian Process based NAS (GP-NAS) method, the cor...
class GPNAS(object): """ GPNAS(Gaussian Process based Neural Architecture Search) is a neural architecture search algorithm. We model the correlation between architectue and performance from a Bayesian perspective. Specifically, by introducing a novel Gaussian Process based NAS (GP-NAS) method, the cor...
X = np.mat(X) X_train = np.mat(X_train) Y_train = np.mat(Y_train) m_X = self.get_predict(X) m_X_train = self.get_predict(X_train) mat_train = self._get_cor_mat(X_train) mat_joint = self._get_cor_mat_joint(X, X_train) return m_X + mat_joint * np.linalg.inv...
""" get the prediction of network architecture X based on X_train and Y_train """ X = np.mat(X) X_train = np.mat(X_train) Y_train = np.mat(Y_train) m_X = self.get_predict(X) m_X_train = self.get_predict(X_train) mat_train = self._get_cor_mat(X_trai...
37
1,793
181
1,974
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
43,694
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/nas/itpruner/Cifar/utils/utils.py
1,2
1,7
sum_list
2,7
2,7
def sum_list(a, j): FILL_FUNC_BODY
def sum_list(a, j): FILL_FUNC_BODY
b = 0 for i in range(len(a)): if i != j: b += a[i] return b
b = 0 for i in range(len(a)): if i != j: b += a[i] return b
16
20
42
62
def sum_list(a, j): FILL_FUNC_BODY
def sum_list(a, j): FILL_FUNC_BODY
43,695
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/nas/ofa/utils/special_config.py
20,21
1,54
dynabert_config
21,54
21,54
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
new_config = dict() block_num = np.floor((len(model.layers.items()) - 3) / 6) block_name = block_num * 6 + 2 def fix_exp(idx): if (idx - 3) % 6 == 0 or (idx - 5) % 6 == 0: return True return False start_idx = 0 for idx, (block_k, block_v) in enumerate(model.layers.i...
new_config = dict() block_num = np.floor((len(model.layers.items()) - 3) / 6) block_name = block_num * 6 + 2 def fix_exp(idx): if (idx - 3) % 6 == 0 or (idx - 5) % 6 == 0: return True return False start_idx = 0 for idx, (block_k, block_v) in enumerate(model.layers.i...
116
222
423
645
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
43,696
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/nas/search_space/search_space_base.py
52,53
23,64
token2arch
SearchSpaceBase
59,61
53,61
class SearchSpaceBase(object): """Controller for Neural Architecture Search. """ def __init__(self, input_size, output_size, block_num, block_mask, *args): """init model config """ self.input_size = input_size self.output_size = output_size self.block_num = block_num...
class SearchSpaceBase(object): """Controller for Neural Architecture Search. """ def __init__(self, input_size, output_size, block_num, block_mask, *args): """init model config """ self.input_size = input_size self.output_size = output_size self.block_num = block_num...
raise NotImplementedError('Abstract method.')
"""Create networks for training and evaluation according to tokens. Args: tokens(list<int>): The tokens which represent a network. Return: model arch """ raise NotImplementedError('Abstract method.')
3
363
16
379
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
43,697
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/nas/search_space/search_space_factory.py
24,25
20,32
get_search_space
SearchSpaceFactory
29,32
25,32
class SearchSpaceFactory(object): def __init__(self): pass def get_search_space(self, config_lists): FILL_FUNC_BODY
class SearchSpaceFactory(object): def __init__(self): pass def get_search_space(self, config_lists): """ get model spaces based on list(key, config). """ FILL_FUNC_BODY
assert isinstance(config_lists, list), "configs must be a list" return CombineSearchSpace(config_lists)
""" get model spaces based on list(key, config). """ assert isinstance(config_lists, list), "configs must be a list" return CombineSearchSpace(config_lists)
10
66
36
102
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
43,698
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/nas/search_space/utils.py
32,33
1,48
check_points
33,42
33,42
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
if points is None: return False else: if isinstance(points, list): return (True if count in points else False) else: return (True if count == points else False)
if points is None: return False else: if isinstance(points, list): return (True if count in points else False) else: return (True if count == points else False)
27
389
64
453
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
43,699
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/prune/criterion.py
102,104
1,138
bn_scale
106,138
104,138
"""Define some functions to compute the importance of structure to be pruned. """ # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License a...
"""Define some functions to compute the importance of structure to be pruned. """ # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License a...
assert (isinstance(graph, GraphWrapper)) # step1: Get first convolution conv_weight = group.master["name"] axis = group.master["axis"] value = values[conv_weight] param_var = graph.var(conv_weight) conv_op = param_var.outputs()[0] # step2: Get bn layer after first convolution conv_...
"""Compute scores by scales of batch_norm layer. """ assert (isinstance(graph, GraphWrapper)) # step1: Get first convolution conv_weight = group.master["name"] axis = group.master["axis"] value = values[conv_weight] param_var = graph.var(conv_weight) conv_op = param_var.outputs()[0]...
110
1,089
374
1,463
"""Define some functions to compute the importance of structure to be pruned. """ # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License a...
"""Define some functions to compute the importance of structure to be pruned. """ # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License a...
43,700
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/prune/idx_selector.py
28,30
1,123
default_idx_selector
47,82
30,82
"""Define some functions to sort substructures of parameter by importance. """ # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at #...
"""Define some functions to sort substructures of parameter by importance. """ # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at #...
# sort channels by the master convolution's score name = group.master["name"] axis = group.master["axis"] score = scores[name][axis] # get max convolution groups attribution max_groups = 1 for pruning_details in group.all_pruning_details(): groups = pruning_details.op.attr("groups")...
"""Get the pruned indices by scores of master tensor. This function return a list of parameters' pruned indices on given axis. Each element of list is a tuple with format (name, axis, indices) in which 'name' is parameter's name and 'axis' is the axis pruning on and `indices` is indices to be prune...
134
976
441
1,417
"""Define some functions to sort substructures of parameter by importance. """ # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at #...
"""Define some functions to sort substructures of parameter by importance. """ # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at #...
43,701
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/prune/unstructured_pruner_utils.py
9,10
1,19
cal_mxn_avg_matrix
10,19
10,19
import numpy as np import copy __all__ = ["BLOCK_SPARSE_ACCURATE_THRESHOLD", "cal_mxn_avg_matrix"] BLOCK_SPARSE_ACCURATE_THRESHOLD = 0.05 def cal_mxn_avg_matrix(mat, m=1, n=1): FILL_FUNC_BODY
import numpy as np import copy __all__ = ["BLOCK_SPARSE_ACCURATE_THRESHOLD", "cal_mxn_avg_matrix"] BLOCK_SPARSE_ACCURATE_THRESHOLD = 0.05 def cal_mxn_avg_matrix(mat, m=1, n=1): FILL_FUNC_BODY
if m == 1 and n == 1: return copy.deepcopy(mat) avg_mat = np.zeros_like(mat) rows = len(mat) // m + 1 cols = len(mat[0]) // n + 1 for row in range(rows): for col in range(cols): avg_mat[m * row:m * row + m, n * col:n * col + n] = np.mean(mat[ m * row:m * row + m, ...
if m == 1 and n == 1: return copy.deepcopy(mat) avg_mat = np.zeros_like(mat) rows = len(mat) // m + 1 cols = len(mat[0]) // n + 1 for row in range(rows): for col in range(cols): avg_mat[m * row:m * row + m, n * col:n * col + n] = np.mean(mat[ m * row:m * row + m, ...
67
99
153
252
import numpy as np import copy __all__ = ["BLOCK_SPARSE_ACCURATE_THRESHOLD", "cal_mxn_avg_matrix"] BLOCK_SPARSE_ACCURATE_THRESHOLD = 0.05 def cal_mxn_avg_matrix(mat, m=1, n=1): FILL_FUNC_BODY
import numpy as np import copy __all__ = ["BLOCK_SPARSE_ACCURATE_THRESHOLD", "cal_mxn_avg_matrix"] BLOCK_SPARSE_ACCURATE_THRESHOLD = 0.05 def cal_mxn_avg_matrix(mat, m=1, n=1): FILL_FUNC_BODY
43,702
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim
/home/hieuvd/dung_repo/raw/stars_03/PaddlePaddle_PaddleSlim/PaddleSlim/paddleslim/quant/constraints/conv_bn_constraints.py
57,58
22,62
_set_freeze_bn_delay
FreezedConvBNConstraint
58,61
58,61
class FreezedConvBNConstraint(FusionConstraint): """ Simulate the folding of convolution and batch norm with a correction strategy. Reference to: Quantizing deep convolutional networks for efficient inference: A whitepaper Args: - freeze_bn_delay(int): After the 'freeze_bn_delay' steps training, swi...
class FreezedConvBNConstraint(FusionConstraint): """ Simulate the folding of convolution and batch norm with a correction strategy. Reference to: Quantizing deep convolutional networks for efficient inference: A whitepaper Args: - freeze_bn_delay(int): After the 'freeze_bn_delay' steps training, swi...
if isinstance(layer, FUSED_LAYER): setattr(layer, "_freeze_bn_delay", self._freeze_bn_delay)
if isinstance(layer, FUSED_LAYER): setattr(layer, "_freeze_bn_delay", self._freeze_bn_delay)
6
483
43
526
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
43,703
/home/hieuvd/dung_repo/raw/stars_03/PhantomInsights_baby-names-analysis/baby-names-analysis
/home/hieuvd/dung_repo/raw/stars_03/PhantomInsights_baby-names-analysis/baby-names-analysis/scripts/step1.py
23,24
1,62
parse_zip
25,58
24,58
""" Downloads the data in a zip file, reads its contents and generates a new csv file with the fields we need. """ import csv from zipfile import ZipFile import requests def download(): """Downloads the dataset and saves it to disk.""" url = "https://www.ssa.gov/oact/babynames/names.zip" with requests...
""" Downloads the data in a zip file, reads its contents and generates a new csv file with the fields we need. """ import csv from zipfile import ZipFile import requests def download(): """Downloads the dataset and saves it to disk.""" url = "https://www.ssa.gov/oact/babynames/names.zip" with requests...
# This list will hold all our data. We initialize it with the header row. data_list = [["year", "name", "gender", "count"]] # We first read the zip file using a zipfile.ZipFile object. with ZipFile("names.zip") as temp_zip: # Then we read the file list. for file_name in temp_zip.namel...
"""Reads the contents of the zip file and creates a csv file with them.""" # This list will hold all our data. We initialize it with the header row. data_list = [["year", "name", "gender", "count"]] # We first read the zip file using a zipfile.ZipFile object. with ZipFile("names.zip") as temp_zip:...
144
197
389
586
""" Downloads the data in a zip file, reads its contents and generates a new csv file with the fields we need. """ import csv from zipfile import ZipFile import requests def download(): """Downloads the dataset and saves it to disk.""" url = "https://www.ssa.gov/oact/babynames/names.zip" with requests...
""" Downloads the data in a zip file, reads its contents and generates a new csv file with the fields we need. """ import csv from zipfile import ZipFile import requests def download(): """Downloads the dataset and saves it to disk.""" url = "https://www.ssa.gov/oact/babynames/names.zip" with requests...
43,881
/home/hieuvd/dung_repo/raw/stars_03/SkywalkerDarren_chatWeb/chatWeb
/home/hieuvd/dung_repo/raw/stars_03/SkywalkerDarren_chatWeb/chatWeb/config.py
90,91
53,101
get_gpt_model
Config
91,96
91,96
class Config: def __init__(self): config_path = os.path.join(os.path.dirname(__file__), 'config.json') if not os.path.exists(config_path): raise FileNotFoundError(f'config.json not found at {config_path}, ' f'please copy config.example.json to config.j...
class Config: def __init__(self): config_path = os.path.join(os.path.dirname(__file__), 'config.json') if not os.path.exists(config_path): raise FileNotFoundError(f'config.json not found at {config_path}, ' f'please copy config.example.json to config.j...
name_list = [m.name for m in SUPPORTED_GPT_MODELS] if model not in name_list: raise ValueError('open_ai_chat_model must be one of ' + ', '.join(name_list)) return next(m for m in SUPPORTED_GPT_MODELS if m.name == model)
name_list = [m.name for m in SUPPORTED_GPT_MODELS] if model not in name_list: raise ValueError('open_ai_chat_model must be one of ' + ', '.join(name_list)) return next(m for m in SUPPORTED_GPT_MODELS if m.name == model)
32
834
91
925
import dataclasses import json import os @dataclasses.dataclass class GPTModel: name: str context_window: int input_price_per_k: float output_price_per_k: float SUPPORTED_GPT_MODELS = [ GPTModel('gpt-4-turbo-preview', 128_000, 0.01, 0.03), # gpt-4-0125-preview GPTModel('gpt-4-0125-preview',...
import dataclasses import json import os @dataclasses.dataclass class GPTModel: name: str context_window: int input_price_per_k: float output_price_per_k: float SUPPORTED_GPT_MODELS = [ GPTModel('gpt-4-turbo-preview', 128_000, 0.01, 0.03), # gpt-4-0125-preview GPTModel('gpt-4-0125-preview',...
43,882
/home/hieuvd/dung_repo/raw/stars_03/SkywalkerDarren_chatWeb/chatWeb
/home/hieuvd/dung_repo/raw/stars_03/SkywalkerDarren_chatWeb/chatWeb/main.py
10,11
1,27
run
12,25
11,25
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from api import api from config import Config from console import console from webui import webui def run(): FILL_FUNC_BODYif __name__ == '__main__': run()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from api import api from config import Config from console import console from webui import webui def run(): """Run the program.""" FILL_FUNC_BODYif __name__ == '__main__': run()
cfg = Config() mode = cfg.mode if mode == 'console': console(cfg) elif mode == 'api': api(cfg) elif mode == 'webui': webui(cfg) else: raise ValueError('mode must be console or api')
"""Run the program.""" cfg = Config() mode = cfg.mode if mode == 'console': console(cfg) elif mode == 'api': api(cfg) elif mode == 'webui': webui(cfg) else: raise ValueError('mode must be console or api')
29
85
94
179
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from api import api from config import Config from console import console from webui import webui def run(): FILL_FUNC_BODYif __name__ == '__main__': run()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from api import api from config import Config from console import console from webui import webui def run(): """Run the program.""" FILL_FUNC_BODYif __name__ == '__main__': run()
43,897
/home/hieuvd/dung_repo/raw/stars_03/Team-Neptune_DeepSea/DeepSea
/home/hieuvd/dung_repo/raw/stars_03/Team-Neptune_DeepSea/DeepSea/src/fs.py
25,26
4,96
executeStep
FS
26,50
26,50
class FS(): def __init__(self): shutil.rmtree("./base", ignore_errors=True) shutil.rmtree("./menv", ignore_errors=True) shutil.rmtree("./sd", ignore_errors=True) for elements in glob.glob(f"./*.zip"): os.remove(elements) def createSDEnv(self): shutil.rmtree("...
class FS(): def __init__(self): shutil.rmtree("./base", ignore_errors=True) shutil.rmtree("./menv", ignore_errors=True) shutil.rmtree("./sd", ignore_errors=True) for elements in glob.glob(f"./*.zip"): os.remove(elements) def createSDEnv(self): shutil.rmtree("...
if step["name"] == "extract": self.__extract(step["arguments"][0]) if step["name"] == "create_dir": self.__createDir(step["arguments"][0]) if step["name"] == "create_file": self.__createFile(step["arguments"][0], step["arguments"][1]) if ste...
if step["name"] == "extract": self.__extract(step["arguments"][0]) if step["name"] == "create_dir": self.__createDir(step["arguments"][0]) if step["name"] == "create_file": self.__createFile(step["arguments"][0], step["arguments"][1]) if ste...
41
806
263
1,069
import shutil, os, logging, re, zipfile, glob from pathlib import Path class FS(): def __init__(self): shutil.rmtree("./base", ignore_errors=True) shutil.rmtree("./menv", ignore_errors=True) shutil.rmtree("./sd", ignore_errors=True) for elements in glob.glob(f"./*.zip"): ...
import shutil, os, logging, re, zipfile, glob from pathlib import Path class FS(): def __init__(self): shutil.rmtree("./base", ignore_errors=True) shutil.rmtree("./menv", ignore_errors=True) shutil.rmtree("./sd", ignore_errors=True) for elements in glob.glob(f"./*.zip"): ...
43,898
/home/hieuvd/dung_repo/raw/stars_03/Team-Neptune_DeepSea/DeepSea
/home/hieuvd/dung_repo/raw/stars_03/Team-Neptune_DeepSea/DeepSea/src/gh.py
13,14
8,34
downloadReleaseAssets
GH
14,34
14,34
class GH(): def __init__(self, ghToken): self.token = ghToken self.github = Github(self.token) def downloadReleaseAssets(self, module): FILL_FUNC_BODY
class GH(): def __init__(self, ghToken): self.token = ghToken self.github = Github(self.token) def downloadReleaseAssets(self, module): FILL_FUNC_BODY
try: ghRepo = self.github.get_repo(module["repo"]) except: logging.exception(f"Unable to get: {module['repo']}") return releases = ghRepo.get_releases() if releases.totalCount == 0: logging.warning(f"No available release for: {modu...
try: ghRepo = self.github.get_repo(module["repo"]) except: logging.exception(f"Unable to get: {module['repo']}") return releases = ghRepo.get_releases() if releases.totalCount == 0: logging.warning(f"No available release for: {modu...
49
62
271
333
import pathlib from github import Github import urllib.request import re import logging class GH(): def __init__(self, ghToken): self.token = ghToken self.github = Github(self.token) def downloadReleaseAssets(self, module): FILL_FUNC_BODY
import pathlib from github import Github import urllib.request import re import logging class GH(): def __init__(self, ghToken): self.token = ghToken self.github = Github(self.token) def downloadReleaseAssets(self, module): FILL_FUNC_BODY
44,053
/home/hieuvd/dung_repo/raw/stars_03/Thmen_EGVSR/EGVSR
/home/hieuvd/dung_repo/raw/stars_03/Thmen_EGVSR/EGVSR/codes/models/espcn_model.py
31,32
6,53
infer
ESPCNModel
37,53
32,53
class ESPCNModel(BaseModel): def __init__(self, opt): super(ESPCNModel, self).__init__(opt) if self.verbose: self.logger.info('{} Model Info {}'.format('=' * 20, '=' * 20)) self.logger.info('Model: {}'.format(opt['model']['name'])) # set network self.set_net...
class ESPCNModel(BaseModel): def __init__(self, opt): super(ESPCNModel, self).__init__(opt) if self.verbose: self.logger.info('{} Model Info {}'.format('=' * 20, '=' * 20)) self.logger.info('Model: {}'.format(opt['model']['name'])) # set network self.set_net...
# canonicalize lr_data = data_utils.canonicalize(lr_data) # to torch.FloatTensor lr_data = lr_data.permute(0, 3, 1, 2) # tchw lr_data = lr_data[:,0:1,:,:] # temporal padding lr_data, n_pad_front = self.pad_sequence(lr_data) # infer hr_seq = self.net_...
""" Function of inference Parameters: :param lr_data: a rgb video sequence with shape thwc :return: a rgb video sequence with type np.uint8 and shape thwc """ # canonicalize lr_data = data_utils.canonicalize(lr_data) # to torch.FloatTensor ...
38
359
196
555
from .base_model import BaseModel from .networks.espcn_nets import ESPNet from utils import data_utils class ESPCNModel(BaseModel): def __init__(self, opt): super(ESPCNModel, self).__init__(opt) if self.verbose: self.logger.info('{} Model Info {}'.format('=' * 20, '=' * 20)) ...
from .base_model import BaseModel from .networks.espcn_nets import ESPNet from utils import data_utils class ESPCNModel(BaseModel): def __init__(self, opt): super(ESPCNModel, self).__init__(opt) if self.verbose: self.logger.info('{} Model Info {}'.format('=' * 20, '=' * 20)) ...
44,054
/home/hieuvd/dung_repo/raw/stars_03/Thmen_EGVSR/EGVSR
/home/hieuvd/dung_repo/raw/stars_03/Thmen_EGVSR/EGVSR/codes/models/vespcn_model.py
17,18
6,67
set_network
VESPCNModel
18,55
18,55
class VESPCNModel(BaseModel): def __init__(self, opt): super(VESPCNModel, self).__init__(opt) if self.verbose: self.logger.info('{} Model Info {}'.format('=' * 20, '=' * 20)) self.logger.info('Model: {}'.format(opt['model']['name'])) # set network self.set_n...
class VESPCNModel(BaseModel): def __init__(self, opt): super(VESPCNModel, self).__init__(opt) if self.verbose: self.logger.info('{} Model Info {}'.format('=' * 20, '=' * 20)) self.logger.info('Model: {}'.format(opt['model']['name'])) # set network self.set_n...
# define net G self.net_G = define_generator(self.opt).to(self.device) if self.verbose: self.logger.info('Generator: {}\n'.format( self.opt['model']['generator']['name']) + self.net_G.__str__()) # load network load_path_G = self.opt['model']['generato...
# define net G self.net_G = define_generator(self.opt).to(self.device) if self.verbose: self.logger.info('Generator: {}\n'.format( self.opt['model']['generator']['name']) + self.net_G.__str__()) # load network load_path_G = self.opt['model']['generato...
184
278
673
951
from .base_model import BaseModel from .networks import define_generator from utils import data_utils class VESPCNModel(BaseModel): def __init__(self, opt): super(VESPCNModel, self).__init__(opt) if self.verbose: self.logger.info('{} Model Info {}'.format('=' * 20, '=' * 20)) ...
from .base_model import BaseModel from .networks import define_generator from utils import data_utils class VESPCNModel(BaseModel): def __init__(self, opt): super(VESPCNModel, self).__init__(opt) if self.verbose: self.logger.info('{} Model Info {}'.format('=' * 20, '=' * 20)) ...
44,055
/home/hieuvd/dung_repo/raw/stars_03/Thmen_EGVSR/EGVSR
/home/hieuvd/dung_repo/raw/stars_03/Thmen_EGVSR/EGVSR/scripts/create_gif.py
18,19
1,33
create_gif
19,30
19,30
# !/bin/python3 import os, glob, sys import imageio import cv2 print(os.getcwd()) TIME_GAP = 0.075 # 两帧之间的时间间隔,秒为单位 FILE_PATH = "../results/Vid4/TecoGAN_BD_iter500000/calendar/*" BEGIN_INDEX = 1 END_INDEX = 7 FORMAT = ".jpg" imgs = glob.glob(FILE_PATH) imgs.sort() # 返回gif def create_gif(image_list, gif_name): FILL...
# !/bin/python3 import os, glob, sys import imageio import cv2 print(os.getcwd()) TIME_GAP = 0.075 # 两帧之间的时间间隔,秒为单位 FILE_PATH = "../results/Vid4/TecoGAN_BD_iter500000/calendar/*" BEGIN_INDEX = 1 END_INDEX = 7 FORMAT = ".jpg" imgs = glob.glob(FILE_PATH) imgs.sort() # 返回gif def create_gif(image_list, gif_name): FILL...
print(image_list) frames = [] for image_name in image_list: frames.append(imageio.imread(image_name)) # Save them as frames into a gif imageio.mimsave(gif_name, frames, 'GIF', duration=TIME_GAP) return
print(image_list) frames = [] for image_name in image_list: frames.append(imageio.imread(image_name)) # Save them as frames into a gif imageio.mimsave(gif_name, frames, 'GIF', duration=TIME_GAP) return
22
188
95
283
# !/bin/python3 import os, glob, sys import imageio import cv2 print(os.getcwd()) TIME_GAP = 0.075 # 两帧之间的时间间隔,秒为单位 FILE_PATH = "../results/Vid4/TecoGAN_BD_iter500000/calendar/*" BEGIN_INDEX = 1 END_INDEX = 7 FORMAT = ".jpg" imgs = glob.glob(FILE_PATH) imgs.sort() # 返回gif def create_gif(image_list, gif_name): FILL...
# !/bin/python3 import os, glob, sys import imageio import cv2 print(os.getcwd()) TIME_GAP = 0.075 # 两帧之间的时间间隔,秒为单位 FILE_PATH = "../results/Vid4/TecoGAN_BD_iter500000/calendar/*" BEGIN_INDEX = 1 END_INDEX = 7 FORMAT = ".jpg" imgs = glob.glob(FILE_PATH) imgs.sort() # 返回gif def create_gif(image_list, gif_name): FILL...
44,056
/home/hieuvd/dung_repo/raw/stars_03/Thmen_EGVSR/EGVSR
/home/hieuvd/dung_repo/raw/stars_03/Thmen_EGVSR/EGVSR/scripts/create_gif_contrast.py
13,14
1,98
generate_mask
22,33
14,33
import os, glob import imageio import cv2 import numpy as np from tqdm import trange dataset = 'city' LR_DIR = '../data/Vid4/Gaussian4xLR/' HR_DIR = '../results/Vid4/G_iter420000/' MIX_DIR = '../results' def generate_mask(h, w, split_rate: float): FILL_FUNC_BODYdef generate_image(lr, sr, mix_path): lr_imgs = so...
import os, glob import imageio import cv2 import numpy as np from tqdm import trange dataset = 'city' LR_DIR = '../data/Vid4/Gaussian4xLR/' HR_DIR = '../results/Vid4/G_iter420000/' MIX_DIR = '../results' def generate_mask(h, w, split_rate: float): """ :param h: mask height :param w: mask width :param...
shape = (h, w) mask = np.zeros(shape, dtype=np.uint8) start = round(split_rate * (w + h) - h) for i in range(start, w): tmp = np.eye(*shape, k=i, dtype=np.uint8) * 255 mask = np.bitwise_or(mask, tmp) return mask
""" :param h: mask height :param w: mask width :param split_rate: 0.0 - 1.0 :return: mask zero_one matirx bottom-left corner is zero (split_rate*100% percent) top-right corner is one ((1-split_rate)*100% percent) """ shape = (h, w) mask = np.zeros(shape...
35
1,128
119
1,247
import os, glob import imageio import cv2 import numpy as np from tqdm import trange dataset = 'city' LR_DIR = '../data/Vid4/Gaussian4xLR/' HR_DIR = '../results/Vid4/G_iter420000/' MIX_DIR = '../results' def generate_mask(h, w, split_rate: float): FILL_FUNC_BODYdef generate_image(lr, sr, mix_path): lr_imgs = so...
import os, glob import imageio import cv2 import numpy as np from tqdm import trange dataset = 'city' LR_DIR = '../data/Vid4/Gaussian4xLR/' HR_DIR = '../results/Vid4/G_iter420000/' MIX_DIR = '../results' def generate_mask(h, w, split_rate: float): """ :param h: mask height :param w: mask width :param...
44,058
/home/hieuvd/dung_repo/raw/stars_03/Thmen_EGVSR/EGVSR
/home/hieuvd/dung_repo/raw/stars_03/Thmen_EGVSR/EGVSR/scripts/selectROI.py
25,26
1,47
on_mouse
26,42
26,42
import os import cv2 ##################################################### # parameter setting # ##################################################### group = 2 scale = 9/16 / group Dataset = ['Vid4', 'Gvt72', 'ToS3'] GT_root_path = '../data/' Rst_root_path = '../res...
import os import cv2 ##################################################### # parameter setting # ##################################################### group = 2 scale = 9/16 / group Dataset = ['Vid4', 'Gvt72', 'ToS3'] GT_root_path = '../data/' Rst_root_path = '../res...
global point1, point2 img2 = img.copy() if event == cv2.EVENT_LBUTTONDOWN: # 左键点击 point1 = (x, y) cv2.circle(img2, point1, 10, (0, 255, 0), 5) cv2.imshow('setect ROI', img2) elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON): # 按住左键拖曳 tmp = (x, round...
global point1, point2 img2 = img.copy() if event == cv2.EVENT_LBUTTONDOWN: # 左键点击 point1 = (x, y) cv2.circle(img2, point1, 10, (0, 255, 0), 5) cv2.imshow('setect ROI', img2) elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON): # 按住左键拖曳 tmp = (x, round...
80
268
338
606
import os import cv2 ##################################################### # parameter setting # ##################################################### group = 2 scale = 9/16 / group Dataset = ['Vid4', 'Gvt72', 'ToS3'] GT_root_path = '../data/' Rst_root_path = '../res...
import os import cv2 ##################################################### # parameter setting # ##################################################### group = 2 scale = 9/16 / group Dataset = ['Vid4', 'Gvt72', 'ToS3'] GT_root_path = '../data/' Rst_root_path = '../res...
44,059
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/examples/orient-ccw.py
12,13
1,66
signed_area
17,23
13,23
# An example of flipping feature polygons right side up. import datetime import logging import sys import fiona logging.basicConfig(stream=sys.stderr, level=logging.INFO) def signed_area(coords): FILL_FUNC_BODYwith fiona.open('docs/data/test_uk.shp', 'r') as source: # Copy the source schema and add two ne...
# An example of flipping feature polygons right side up. import datetime import logging import sys import fiona logging.basicConfig(stream=sys.stderr, level=logging.INFO) def signed_area(coords): """Return the signed area enclosed by a ring using the linear time algorithm at http://www.cgafaq.info/wiki/Pol...
xs, ys = map(list, zip(*coords)) xs.append(xs[1]) ys.append(ys[1]) return sum(xs[i]*(ys[i+1]-ys[i-1]) for i in range(1, len(coords)))/2.0
"""Return the signed area enclosed by a ring using the linear time algorithm at http://www.cgafaq.info/wiki/Polygon_Area. A value >= 0 indicates a counter-clockwise oriented ring. """ xs, ys = map(list, zip(*coords)) xs.append(xs[1]) ys.append(ys[1]) return sum(xs[i]*(ys[i+1]-ys[i-1]) f...
14
512
86
598
# An example of flipping feature polygons right side up. import datetime import logging import sys import fiona logging.basicConfig(stream=sys.stderr, level=logging.INFO) def signed_area(coords): FILL_FUNC_BODYwith fiona.open('docs/data/test_uk.shp', 'r') as source: # Copy the source schema and add two ne...
# An example of flipping feature polygons right side up. import datetime import logging import sys import fiona logging.basicConfig(stream=sys.stderr, level=logging.INFO) def signed_area(coords): """Return the signed area enclosed by a ring using the linear time algorithm at http://www.cgafaq.info/wiki/Pol...
44,060
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/_path.py
176,177
1,216
_vsi_path
189,216
177,216
"""Dataset paths, identifiers, and filenames Note: this module is not part of Rasterio's API. It is for internal use only. """ import os import pathlib import re import sys from urllib.parse import urlparse import attr from fiona.errors import PathError # Supported URI schemes and their mapping to GDAL's VSI suff...
"""Dataset paths, identifiers, and filenames Note: this module is not part of Rasterio's API. It is for internal use only. """ import os import pathlib import re import sys from urllib.parse import urlparse import attr from fiona.errors import PathError # Supported URI schemes and their mapping to GDAL's VSI suff...
if isinstance(path, _UnparsedPath): return path.path elif isinstance(path, _ParsedPath): if not path.scheme: return path.path else: if path.scheme.split('+')[-1] in CURLSCHEMES: suffix = '{}://'.format(path.scheme.split('+')[-1]) els...
"""Convert a parsed path to a GDAL VSI path Parameters ---------- path : Path A ParsedPath or UnparsedPath object. Returns ------- str """ if isinstance(path, _UnparsedPath): return path.path elif isinstance(path, _ParsedPath): if not path.scheme: ...
68
1,513
282
1,795
"""Dataset paths, identifiers, and filenames Note: this module is not part of Rasterio's API. It is for internal use only. """ import os import pathlib import re import sys from urllib.parse import urlparse import attr from fiona.errors import PathError # Supported URI schemes and their mapping to GDAL's VSI suff...
"""Dataset paths, identifiers, and filenames Note: this module is not part of Rasterio's API. It is for internal use only. """ import os import pathlib import re import sys from urllib.parse import urlparse import attr from fiona.errors import PathError # Supported URI schemes and their mapping to GDAL's VSI suff...
44,061
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/_path.py
66,68
48,118
from_uri
_ParsedPath
68,97
68,97
@attr.s(slots=True) class _ParsedPath(_Path): """Result of parsing a dataset URI/Path Attributes ---------- path : str Parsed path. Includes the hostname and query string in the case of a URI. archive : str Parsed archive path. scheme : str URI scheme such as "ht...
@attr.s(slots=True) class _ParsedPath(_Path): """Result of parsing a dataset URI/Path Attributes ---------- path : str Parsed path. Includes the hostname and query string in the case of a URI. archive : str Parsed archive path. scheme : str URI scheme such as "ht...
parts = urlparse(uri) if sys.platform == "win32" and re.match(r"^[a-zA-Z]\:", parts.netloc): parsed_path = f"{parts.netloc}{parts.path}" parsed_netloc = None else: parsed_path = parts.path parsed_netloc = parts.netloc path = parsed_path ...
parts = urlparse(uri) if sys.platform == "win32" and re.match(r"^[a-zA-Z]\:", parts.netloc): parsed_path = f"{parts.netloc}{parts.path}" parsed_netloc = None else: parsed_path = parts.path parsed_netloc = parts.netloc path = parsed_path ...
86
369
291
660
"""Dataset paths, identifiers, and filenames Note: this module is not part of Rasterio's API. It is for internal use only. """ import os import pathlib import re import sys from urllib.parse import urlparse import attr from fiona.errors import PathError # Supported URI schemes and their mapping to GDAL's VSI suff...
"""Dataset paths, identifiers, and filenames Note: this module is not part of Rasterio's API. It is for internal use only. """ import os import pathlib import re import sys from urllib.parse import urlparse import attr from fiona.errors import PathError # Supported URI schemes and their mapping to GDAL's VSI suff...
44,062
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/_path.py
44,45
41,48
as_vsi
_Path
45,48
45,48
class _Path: """Base class for dataset paths""" def as_vsi(self): FILL_FUNC_BODY
class _Path: """Base class for dataset paths""" def as_vsi(self): FILL_FUNC_BODY
return _vsi_path(self)
return _vsi_path(self)
2
35
16
51
"""Dataset paths, identifiers, and filenames Note: this module is not part of Rasterio's API. It is for internal use only. """ import os import pathlib import re import sys from urllib.parse import urlparse import attr from fiona.errors import PathError # Supported URI schemes and their mapping to GDAL's VSI suff...
"""Dataset paths, identifiers, and filenames Note: this module is not part of Rasterio's API. It is for internal use only. """ import os import pathlib import re import sys from urllib.parse import urlparse import attr from fiona.errors import PathError # Supported URI schemes and their mapping to GDAL's VSI suff...
44,063
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/_path.py
129,131
118,135
name
_UnparsedPath
132,135
131,135
@attr.s(slots=True) class _UnparsedPath(_Path): """Encapsulates legacy GDAL filenames Attributes ---------- path : str The legacy GDAL filename. """ path = attr.ib() @property def name(self): FILL_FUNC_BODY
@attr.s(slots=True) class _UnparsedPath(_Path): """Encapsulates legacy GDAL filenames Attributes ---------- path : str The legacy GDAL filename. """ path = attr.ib() @property def name(self): """The unparsed path's original path""" FILL_FUNC_BODY
return self.path
"""The unparsed path's original path""" return self.path
2
103
11
114
"""Dataset paths, identifiers, and filenames Note: this module is not part of Rasterio's API. It is for internal use only. """ import os import pathlib import re import sys from urllib.parse import urlparse import attr from fiona.errors import PathError # Supported URI schemes and their mapping to GDAL's VSI suff...
"""Dataset paths, identifiers, and filenames Note: this module is not part of Rasterio's API. It is for internal use only. """ import os import pathlib import re import sys from urllib.parse import urlparse import attr from fiona.errors import PathError # Supported URI schemes and their mapping to GDAL's VSI suff...
44,064
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/compat.py
7,8
1,13
strencode
8,13
8,13
from collections import UserDict from collections.abc import Mapping DICT_TYPES = (dict, Mapping, UserDict) def strencode(instr, encoding="utf-8"): FILL_FUNC_BODY
from collections import UserDict from collections.abc import Mapping DICT_TYPES = (dict, Mapping, UserDict) def strencode(instr, encoding="utf-8"): FILL_FUNC_BODY
try: instr = instr.encode(encoding) except (UnicodeDecodeError, AttributeError): pass return instr
try: instr = instr.encode(encoding) except (UnicodeDecodeError, AttributeError): pass return instr
10
63
40
103
from collections import UserDict from collections.abc import Mapping DICT_TYPES = (dict, Mapping, UserDict) def strencode(instr, encoding="utf-8"): FILL_FUNC_BODY
from collections import UserDict from collections.abc import Mapping DICT_TYPES = (dict, Mapping, UserDict) def strencode(instr, encoding="utf-8"): FILL_FUNC_BODY
44,065
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/enums.py
26,28
6,32
_missing_
WktVersion
28,32
28,32
class WktVersion(Enum): """ .. versionadded:: 1.9.0 Supported CRS WKT string versions. """ #: WKT Version 2 from 2015 WKT2_2015 = "WKT2_2015" #: Alias for latest WKT Version 2 WKT2 = "WKT2" #: WKT Version 2 from 2019 WKT2_2019 = "WKT2_2018" #: WKT Version 1 GDAL Style ...
class WktVersion(Enum): """ .. versionadded:: 1.9.0 Supported CRS WKT string versions. """ #: WKT Version 2 from 2015 WKT2_2015 = "WKT2_2015" #: Alias for latest WKT Version 2 WKT2 = "WKT2" #: WKT Version 2 from 2019 WKT2_2019 = "WKT2_2018" #: WKT Version 1 GDAL Style ...
if value == "WKT2_2019": # WKT2_2019 alias added in GDAL 3.2, use WKT2_2018 for compatibility return WktVersion.WKT2_2019 raise ValueError(f"Invalid value for WktVersion: {value}")
if value == "WKT2_2019": # WKT2_2019 alias added in GDAL 3.2, use WKT2_2018 for compatibility return WktVersion.WKT2_2019 raise ValueError(f"Invalid value for WktVersion: {value}")
23
267
90
357
"""Enumerations.""" from enum import Enum class WktVersion(Enum): """ .. versionadded:: 1.9.0 Supported CRS WKT string versions. """ #: WKT Version 2 from 2015 WKT2_2015 = "WKT2_2015" #: Alias for latest WKT Version 2 WKT2 = "WKT2" #: WKT Version 2 from 2019 WKT2_2019 = "WK...
"""Enumerations.""" from enum import Enum class WktVersion(Enum): """ .. versionadded:: 1.9.0 Supported CRS WKT string versions. """ #: WKT Version 2 from 2015 WKT2_2015 = "WKT2_2015" #: Alias for latest WKT Version 2 WKT2 = "WKT2" #: WKT Version 2 from 2019 WKT2_2019 = "WK...
44,066
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/fio/bounds.py
14,28
1,90
bounds
41,90
28,90
"""$ fio bounds""" import json import click from cligj import precision_opt, use_rs_opt import fiona from fiona.fio.helpers import obj_gen from fiona.fio import with_context_env from fiona.model import ObjectEncoder @click.command(short_help="Print the extent of GeoJSON objects") @precision_opt @click.option('--ex...
"""$ fio bounds""" import json import click from cligj import precision_opt, use_rs_opt import fiona from fiona.fio.helpers import obj_gen from fiona.fio import with_context_env from fiona.model import ObjectEncoder @click.command(short_help="Print the extent of GeoJSON objects") @precision_opt @click.option('--ex...
stdin = click.get_text_stream('stdin') source = obj_gen(stdin) for i, obj in enumerate(source): obj_id = obj.get("id", "collection:" + str(i)) xs = [] ys = [] features = obj.get("features") or [obj] for j, feat in enumerate(features): feat_id = feat.get(...
"""Print the bounding boxes of GeoJSON objects read from stdin. Optionally explode collections and print the bounds of their features. To print identifiers for input objects along with their bounds as a {id: identifier, bbox: bounds} JSON object, use --with-id. To print the input objects them...
152
401
558
959
"""$ fio bounds""" import json import click from cligj import precision_opt, use_rs_opt import fiona from fiona.fio.helpers import obj_gen from fiona.fio import with_context_env from fiona.model import ObjectEncoder @click.command(short_help="Print the extent of GeoJSON objects") @precision_opt @click.option('--ex...
"""$ fio bounds""" import json import click from cligj import precision_opt, use_rs_opt import fiona from fiona.fio.helpers import obj_gen from fiona.fio import with_context_env from fiona.model import ObjectEncoder @click.command(short_help="Print the extent of GeoJSON objects") @precision_opt @click.option('--ex...
44,067
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/fio/calc.py
11,20
1,64
calc
42,64
20,64
import json import click from cligj import use_rs_opt from .helpers import obj_gen, eval_feature_expression from fiona.fio import with_context_env from fiona.model import ObjectEncoder @click.command(short_help="Calculate GeoJSON property by Python expression") @click.argument('property_name') @click.argument('expr...
import json import click from cligj import use_rs_opt from .helpers import obj_gen, eval_feature_expression from fiona.fio import with_context_env from fiona.model import ObjectEncoder @click.command(short_help="Calculate GeoJSON property by Python expression") @click.argument('property_name') @click.argument('expr...
stdin = click.get_text_stream('stdin') source = obj_gen(stdin) for i, obj in enumerate(source): features = obj.get("features") or [obj] for j, feat in enumerate(features): if not overwrite and property_name in feat["properties"]: raise click.UsageError( ...
""" Create a new property on GeoJSON features using the specified expression. \b The expression is evaluated in a restricted namespace containing: - sum, pow, min, max and the imported math module - shape (optional, imported from shapely.geometry if available) - bool, int, str, ...
53
381
216
597
import json import click from cligj import use_rs_opt from .helpers import obj_gen, eval_feature_expression from fiona.fio import with_context_env from fiona.model import ObjectEncoder @click.command(short_help="Calculate GeoJSON property by Python expression") @click.argument('property_name') @click.argument('expr...
import json import click from cligj import use_rs_opt from .helpers import obj_gen, eval_feature_expression from fiona.fio import with_context_env from fiona.model import ObjectEncoder @click.command(short_help="Calculate GeoJSON property by Python expression") @click.argument('property_name') @click.argument('expr...
44,068
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/fio/cat.py
20,78
1,140
cat
86,140
78,140
"""fio-cat""" import json import warnings import click import cligj import fiona from fiona.transform import transform_geom from fiona.model import Feature, ObjectEncoder from fiona.fio import options, with_context_env from fiona.fio.helpers import recursive_round from fiona.errors import AttributeFilterError warni...
"""fio-cat""" import json import warnings import click import cligj import fiona from fiona.transform import transform_geom from fiona.model import Feature, ObjectEncoder from fiona.fio import options, with_context_env from fiona.fio.helpers import recursive_round from fiona.errors import AttributeFilterError warni...
dump_kwds = {"sort_keys": True} if indent: dump_kwds["indent"] = indent if compact: dump_kwds["separators"] = (",", ":") # Validate file idexes provided in --layer option # (can't pass the files to option callback) if layer: options.validate_multilayer_file_index(files, ...
""" Concatenate and print the features of input datasets as a sequence of GeoJSON features. When working with a multi-layer dataset the first layer is used by default. Use the '--layer' option to select a different layer. """ dump_kwds = {"sort_keys": True} if indent: dump_kwds...
139
688
555
1,243
"""fio-cat""" import json import warnings import click import cligj import fiona from fiona.transform import transform_geom from fiona.model import Feature, ObjectEncoder from fiona.fio import options, with_context_env from fiona.fio.helpers import recursive_round from fiona.errors import AttributeFilterError warni...
"""fio-cat""" import json import warnings import click import cligj import fiona from fiona.transform import transform_geom from fiona.model import Feature, ObjectEncoder from fiona.fio import options, with_context_env from fiona.fio.helpers import recursive_round from fiona.errors import AttributeFilterError warni...
44,069
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/fio/distrib.py
12,17
1,36
distrib
22,36
17,36
"""$ fio distrib""" import json import click import cligj from fiona.fio import helpers, with_context_env from fiona.model import ObjectEncoder @click.command() @cligj.use_rs_opt @click.pass_context @with_context_env def distrib(ctx, use_rs): FILL_FUNC_BODY
"""$ fio distrib""" import json import click import cligj from fiona.fio import helpers, with_context_env from fiona.model import ObjectEncoder @click.command() @cligj.use_rs_opt @click.pass_context @with_context_env def distrib(ctx, use_rs): """Distribute features from a collection. Print the features of...
stdin = click.get_text_stream('stdin') source = helpers.obj_gen(stdin) for i, obj in enumerate(source): obj_id = obj.get("id", "collection:" + str(i)) features = obj.get("features") or [obj] for j, feat in enumerate(features): if obj.get("type") == "FeatureCollection": ...
"""Distribute features from a collection. Print the features of GeoJSON objects read from stdin. """ stdin = click.get_text_stream('stdin') source = helpers.obj_gen(stdin) for i, obj in enumerate(source): obj_id = obj.get("id", "collection:" + str(i)) features = obj.get("featu...
49
129
200
329
"""$ fio distrib""" import json import click import cligj from fiona.fio import helpers, with_context_env from fiona.model import ObjectEncoder @click.command() @cligj.use_rs_opt @click.pass_context @with_context_env def distrib(ctx, use_rs): FILL_FUNC_BODY
"""$ fio distrib""" import json import click import cligj from fiona.fio import helpers, with_context_env from fiona.model import ObjectEncoder @click.command() @cligj.use_rs_opt @click.pass_context @with_context_env def distrib(ctx, use_rs): """Distribute features from a collection. Print the features of...
44,070
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/fio/helpers.py
76,77
1,135
make_ld_context
80,113
77,113
"""Helper objects needed by multiple CLI commands. """ from functools import partial import json import math import warnings from fiona.model import Geometry, to_dict from fiona._vendor.munch import munchify warnings.simplefilter("default") def obj_gen(lines, object_hook=None): """Return a generator of JSON ...
"""Helper objects needed by multiple CLI commands. """ from functools import partial import json import math import warnings from fiona.model import Geometry, to_dict from fiona._vendor.munch import munchify warnings.simplefilter("default") def obj_gen(lines, object_hook=None): """Return a generator of JSON ...
ctx = { "@context": { "geojson": "http://ld.geojson.org/vocab#", "Feature": "geojson:Feature", "FeatureCollection": "geojson:FeatureCollection", "GeometryCollection": "geojson:GeometryCollection", "LineString": "geojson:LineString", "Mu...
"""Returns a JSON-LD Context object. See https://json-ld.org/spec/latest/json-ld/.""" ctx = { "@context": { "geojson": "http://ld.geojson.org/vocab#", "Feature": "geojson:Feature", "FeatureCollection": "geojson:FeatureCollection", "GeometryCollection"...
74
804
461
1,265
"""Helper objects needed by multiple CLI commands. """ from functools import partial import json import math import warnings from fiona.model import Geometry, to_dict from fiona._vendor.munch import munchify warnings.simplefilter("default") def obj_gen(lines, object_hook=None): """Return a generator of JSON ...
"""Helper objects needed by multiple CLI commands. """ from functools import partial import json import math import warnings from fiona.model import Geometry, to_dict from fiona._vendor.munch import munchify warnings.simplefilter("default") def obj_gen(lines, object_hook=None): """Return a generator of JSON ...
44,071
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/fio/load.py
14,48
1,115
load
54,115
48,115
"""$ fio load""" from functools import partial import click import cligj import fiona from fiona.fio import options, with_context_env from fiona.model import Feature, Geometry from fiona.transform import transform_geom @click.command(short_help="Load GeoJSON to a dataset in another format.") @click.argument("outpu...
"""$ fio load""" from functools import partial import click import cligj import fiona from fiona.fio import options, with_context_env from fiona.model import Feature, Geometry from fiona.transform import transform_geom @click.command(short_help="Load GeoJSON to a dataset in another format.") @click.argument("outpu...
dst_crs = dst_crs or src_crs if src_crs and dst_crs and src_crs != dst_crs: transformer = partial( transform_geom, src_crs, dst_crs, antimeridian_cutting=True ) else: def transformer(x): return Geometry.from_dict(**x) def feature_gen(): """Conve...
"""Load features from JSON to a file in another format. The input is a GeoJSON feature collection or optionally a sequence of GeoJSON feature objects. """ dst_crs = dst_crs or src_crs if src_crs and dst_crs and src_crs != dst_crs: transformer = partial( transform_geom, src...
168
427
564
991
"""$ fio load""" from functools import partial import click import cligj import fiona from fiona.fio import options, with_context_env from fiona.model import Feature, Geometry from fiona.transform import transform_geom @click.command(short_help="Load GeoJSON to a dataset in another format.") @click.argument("outpu...
"""$ fio load""" from functools import partial import click import cligj import fiona from fiona.fio import options, with_context_env from fiona.model import Feature, Geometry from fiona.transform import transform_geom @click.command(short_help="Load GeoJSON to a dataset in another format.") @click.argument("outpu...
44,072
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/fio/ls.py
13,20
1,25
ls
23,25
20,25
"""$ fiona ls""" import json import click from cligj import indent_opt import fiona from fiona.fio import options, with_context_env @click.command() @click.argument('input', required=True) @indent_opt @options.open_opt @click.pass_context @with_context_env def ls(ctx, input, indent, open_options): FILL_FUNC_BODY
"""$ fiona ls""" import json import click from cligj import indent_opt import fiona from fiona.fio import options, with_context_env @click.command() @click.argument('input', required=True) @indent_opt @options.open_opt @click.pass_context @with_context_env def ls(ctx, input, indent, open_options): """ Lis...
result = fiona.listlayers(input, **open_options) click.echo(json.dumps(result, indent=indent))
""" List layers in a datasource. """ result = fiona.listlayers(input, **open_options) click.echo(json.dumps(result, indent=indent))
6
132
37
169
"""$ fiona ls""" import json import click from cligj import indent_opt import fiona from fiona.fio import options, with_context_env @click.command() @click.argument('input', required=True) @indent_opt @options.open_opt @click.pass_context @with_context_env def ls(ctx, input, indent, open_options): FILL_FUNC_BODY
"""$ fiona ls""" import json import click from cligj import indent_opt import fiona from fiona.fio import options, with_context_env @click.command() @click.argument('input', required=True) @indent_opt @options.open_opt @click.pass_context @with_context_env def ls(ctx, input, indent, open_options): """ Lis...
44,073
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/fio/main.py
51,78
1,114
main_group
80,97
78,97
""" Main click group for the CLI. Needs to be isolated for entry-point loading. """ import itertools import logging import sys import click from click_plugins import with_plugins from cligj import verbose_opt, quiet_opt if sys.version_info < (3, 10): from importlib_metadata import entry_points else: from i...
""" Main click group for the CLI. Needs to be isolated for entry-point loading. """ import itertools import logging import sys import click from click_plugins import with_plugins from cligj import verbose_opt, quiet_opt if sys.version_info < (3, 10): from importlib_metadata import entry_points else: from i...
verbosity = verbose - quiet configure_logging(verbosity) ctx.obj = {} ctx.obj["verbosity"] = verbosity ctx.obj["aws_profile"] = aws_profile envopts = {"CPL_DEBUG": (verbosity > 2)} if aws_profile or aws_no_sign_requests: session = AWSSession( profile_name=aws_profile, ...
"""Fiona command line interface. """ verbosity = verbose - quiet configure_logging(verbosity) ctx.obj = {} ctx.obj["verbosity"] = verbosity ctx.obj["aws_profile"] = aws_profile envopts = {"CPL_DEBUG": (verbosity > 2)} if aws_profile or aws_no_sign_requests: session = AWSSessi...
40
894
194
1,088
""" Main click group for the CLI. Needs to be isolated for entry-point loading. """ import itertools import logging import sys import click from click_plugins import with_plugins from cligj import verbose_opt, quiet_opt if sys.version_info < (3, 10): from importlib_metadata import entry_points else: from i...
""" Main click group for the CLI. Needs to be isolated for entry-point loading. """ import itertools import logging import sys import click from click_plugins import with_plugins from cligj import verbose_opt, quiet_opt if sys.version_info < (3, 10): from importlib_metadata import entry_points else: from i...
44,074
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/fio/options.py
13,14
1,97
cb_layer
15,21
14,21
"""Common commandline options for `fio`""" from collections import defaultdict import click src_crs_opt = click.option('--src-crs', '--src_crs', help="Source CRS.") dst_crs_opt = click.option('--dst-crs', '--dst_crs', help="Destination CRS.") def cb_layer(ctx, param, value): FILL_FUNC_BODYdef cb_multilayer(ctx, ...
"""Common commandline options for `fio`""" from collections import defaultdict import click src_crs_opt = click.option('--src-crs', '--src_crs', help="Source CRS.") dst_crs_opt = click.option('--dst-crs', '--dst_crs', help="Destination CRS.") def cb_layer(ctx, param, value): """Let --layer be a name or index...
if value is None or not value.isdigit(): return value else: return int(value)
"""Let --layer be a name or index.""" if value is None or not value.isdigit(): return value else: return int(value)
12
799
37
836
"""Common commandline options for `fio`""" from collections import defaultdict import click src_crs_opt = click.option('--src-crs', '--src_crs', help="Source CRS.") dst_crs_opt = click.option('--dst-crs', '--dst_crs', help="Destination CRS.") def cb_layer(ctx, param, value): FILL_FUNC_BODYdef cb_multilayer(ctx, ...
"""Common commandline options for `fio`""" from collections import defaultdict import click src_crs_opt = click.option('--src-crs', '--src_crs', help="Source CRS.") dst_crs_opt = click.option('--dst-crs', '--dst_crs', help="Destination CRS.") def cb_layer(ctx, param, value): """Let --layer be a name or index...
44,075
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/fio/rm.py
11,18
1,31
rm
18,31
18,31
import click import logging import fiona from fiona.fio import with_context_env logger = logging.getLogger(__name__) @click.command(help="Remove a datasource or an individual layer.") @click.argument("input", required=True) @click.option("--layer", type=str, default=None, required=False, help="Name of layer to rem...
import click import logging import fiona from fiona.fio import with_context_env logger = logging.getLogger(__name__) @click.command(help="Remove a datasource or an individual layer.") @click.argument("input", required=True) @click.option("--layer", type=str, default=None, required=False, help="Name of layer to rem...
if layer is None: kind = "datasource" else: kind = "layer" if not yes: click.confirm(f"The {kind} will be removed. Are you sure?", abort=True) try: fiona.remove(input, layer=layer) except Exception: logger.exception(f"Failed to remove {kind}.") raise...
if layer is None: kind = "datasource" else: kind = "layer" if not yes: click.confirm(f"The {kind} will be removed. Are you sure?", abort=True) try: fiona.remove(input, layer=layer) except Exception: logger.exception(f"Failed to remove {kind}.") raise...
34
149
120
269
import click import logging import fiona from fiona.fio import with_context_env logger = logging.getLogger(__name__) @click.command(help="Remove a datasource or an individual layer.") @click.argument("input", required=True) @click.option("--layer", type=str, default=None, required=False, help="Name of layer to rem...
import click import logging import fiona from fiona.fio import with_context_env logger = logging.getLogger(__name__) @click.command(help="Remove a datasource or an individual layer.") @click.argument("input", required=True) @click.option("--layer", type=str, default=None, required=False, help="Name of layer to rem...
44,076
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona
/home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/inspector.py
12,13
1,37
main
14,27
13,27
import code import logging import sys import fiona logging.basicConfig(stream=sys.stderr, level=logging.INFO) logger = logging.getLogger('fiona.inspector') def main(srcfile): FILL_FUNC_BODYif __name__ == '__main__': import argparse parser = argparse.ArgumentParser( prog="python -m fiona.inspector"...
import code import logging import sys import fiona logging.basicConfig(stream=sys.stderr, level=logging.INFO) logger = logging.getLogger('fiona.inspector') def main(srcfile): """Open a dataset in an iteractive session.""" FILL_FUNC_BODYif __name__ == '__main__': import argparse parser = argparse.Argum...
with fiona.drivers(): with fiona.open(srcfile) as src: code.interact( 'Fiona %s Interactive Inspector (Python %s)\n' 'Type "src.schema", "next(src)", or "help(src)" ' "for more information." % (fiona.__version__, ".".join(map(str, s...
"""Open a dataset in an iteractive session.""" with fiona.drivers(): with fiona.open(srcfile) as src: code.interact( 'Fiona %s Interactive Inspector (Python %s)\n' 'Type "src.schema", "next(src)", or "help(src)" ' "for more information." ...
30
185
134
319
import code import logging import sys import fiona logging.basicConfig(stream=sys.stderr, level=logging.INFO) logger = logging.getLogger('fiona.inspector') def main(srcfile): FILL_FUNC_BODYif __name__ == '__main__': import argparse parser = argparse.ArgumentParser( prog="python -m fiona.inspector"...
import code import logging import sys import fiona logging.basicConfig(stream=sys.stderr, level=logging.INFO) logger = logging.getLogger('fiona.inspector') def main(srcfile): """Open a dataset in an iteractive session.""" FILL_FUNC_BODYif __name__ == '__main__': import argparse parser = argparse.Argum...