hexsha
stringlengths
40
40
size
int64
7
1.04M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
247
max_stars_repo_name
stringlengths
4
125
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
247
max_issues_repo_name
stringlengths
4
125
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
247
max_forks_repo_name
stringlengths
4
125
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.04M
avg_line_length
float64
1.77
618k
max_line_length
int64
1
1.02M
alphanum_fraction
float64
0
1
original_content
stringlengths
7
1.04M
filtered:remove_function_no_docstring
int64
-102
942k
filtered:remove_class_no_docstring
int64
-354
977k
filtered:remove_delete_markers
int64
0
60.1k
580f6b656f18ebb519adcc1d9ef6790858d2d266
34,832
py
Python
paddleslim/nas/ofa/convert_super.py
1375207619/PaddleSlim
1a9376a8b68e2219db3e95dea900ef4003e72c36
[ "Apache-2.0" ]
1
2021-12-30T08:23:21.000Z
2021-12-30T08:23:21.000Z
paddleslim/nas/ofa/convert_super.py
maxpark/PaddleSlim
f6b827fca5f3d9cc467426b8ef30e3a6d2b012b9
[ "Apache-2.0" ]
null
null
null
paddleslim/nas/ofa/convert_super.py
maxpark/PaddleSlim
f6b827fca5f3d9cc467426b8ef30e3a6d2b012b9
[ "Apache-2.0" ]
null
null
null
# 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect import decorator import logging import numbers import paddle from ...common import get_logger from .utils.utils import get_paddle_version pd_ver = get_paddle_version() if pd_ver == 185: import paddle.fluid.dygraph.nn as nn from paddle.fluid.dygraph.nn import Conv2D, Conv2DTranspose, Linear, LayerNorm, Embedding from paddle.fluid import ParamAttr from .layers_old import * from . import layers_old as layers Layer = paddle.fluid.dygraph.Layer else: import paddle.nn as nn from paddle.nn import Conv2D, Conv2DTranspose, Linear, LayerNorm, Embedding, SyncBatchNorm from paddle import ParamAttr from .layers import * from . import layers Layer = paddle.nn.Layer from .layers_base import Block from . import layers_old _logger = get_logger(__name__, level=logging.INFO) __all__ = ['supernet', 'Convert'] WEIGHT_LAYER = ['conv', 'linear', 'embedding'] class Convert: """ Convert network to the supernet according to the search space. Parameters: context(paddleslim.nas.ofa.supernet): search space defined by the user. Examples: .. code-block:: python from paddleslim.nas.ofa import supernet, Convert sp_net_config = supernet(kernel_size=(3, 5, 7), expand_ratio=[1, 2, 4]) convert = Convert(sp_net_config) """ def convert(self, network): """ The function to convert the network to a supernet. Parameters: network(paddle.nn.Layer|list(paddle.nn.Layer)): instance of the model or list of instance of layers. Examples: .. code-block:: python from paddle.vision.models import mobilenet_v1 from paddleslim.nas.ofa import supernet, Convert sp_net_config = supernet(kernel_size=(3, 5, 7), expand_ratio=[1, 2, 4]) convert = Convert(sp_net_config).convert(mobilenet_v1()) """ # search the first and last weight layer, don't change out channel of the last weight layer # don't change in channel of the first weight layer model = [] if isinstance(network, Layer): for name, sublayer in network.named_sublayers(): model.append(sublayer) else: model = network first_weight_layer_idx = -1 last_weight_layer_idx = -1 weight_layer_count = 0 # NOTE: pre_channel store for shortcut module pre_channel = None cur_channel = None for idx, layer in enumerate(model): cls_name = layer.__class__.__name__.lower() ### basic api in paddle if len(layer.sublayers()) == 0: if 'conv' in cls_name or 'linear' in cls_name or 'embedding' in cls_name: weight_layer_count += 1 last_weight_layer_idx = idx if first_weight_layer_idx == -1: first_weight_layer_idx = idx if getattr(self.context, 'channel', None) != None: assert len( self.context.channel ) == weight_layer_count, "length of channel must same as weight layer." for idx, layer in enumerate(model): if isinstance(layer, Conv2D): attr_dict = layer.__dict__ key = attr_dict['_full_name'] new_attr_name = [ 'stride', 'padding', 'dilation', 'groups', 'bias_attr' ] if pd_ver == 185: new_attr_name += ['param_attr', 'use_cudnn', 'act', 'dtype'] else: new_attr_name += [ 'weight_attr', 'data_format', 'padding_mode' ] self._change_name(layer, pd_ver, conv=True) new_attr_dict = dict.fromkeys(new_attr_name, None) new_attr_dict['candidate_config'] = dict() if pd_ver == 185: new_attr_dict['num_channels'] = None new_attr_dict['num_filters'] = None new_attr_dict['filter_size'] = None else: new_attr_dict['in_channels'] = None new_attr_dict['out_channels'] = None new_attr_dict['kernel_size'] = None self.kernel_size = getattr(self.context, 'kernel_size', None) # if the kernel_size of conv is 1, don't change it. fks = '_filter_size' if '_filter_size' in attr_dict.keys( ) else '_kernel_size' ks = [attr_dict[fks]] if isinstance( attr_dict[fks], numbers.Integral) else attr_dict[fks] if self.kernel_size and int(ks[0]) != 1: new_attr_dict['transform_kernel'] = True new_attr_dict[fks[1:]] = max(self.kernel_size) new_attr_dict['candidate_config'].update({ 'kernel_size': self.kernel_size }) else: new_attr_dict[fks[1:]] = attr_dict[fks] in_key = '_num_channels' if '_num_channels' in attr_dict.keys( ) else '_in_channels' out_key = '_num_filters' if '_num_filters' in attr_dict.keys( ) else '_out_channels' if self.context.expand: ### first super convolution if idx == first_weight_layer_idx: new_attr_dict[in_key[1:]] = attr_dict[in_key] else: new_attr_dict[in_key[1:]] = int(self.context.expand * attr_dict[in_key]) ### last super convolution if idx == last_weight_layer_idx: new_attr_dict[out_key[1:]] = attr_dict[out_key] else: new_attr_dict[out_key[1:]] = int(self.context.expand * attr_dict[out_key]) new_attr_dict['candidate_config'].update({ 'expand_ratio': self.context.expand_ratio }) elif self.context.channel: if attr_dict['_groups'] != None and ( int(attr_dict['_groups']) == int(attr_dict[in_key]) ): ### depthwise conv, if conv is depthwise, use pre channel as cur_channel _logger.warn( "If convolution is a depthwise conv, output channel change" \ " to the same channel with input, output channel in search is not used." ) cur_channel = pre_channel else: cur_channel = self.context.channel[0] self.context.channel = self.context.channel[1:] if idx == first_weight_layer_idx: new_attr_dict[in_key[1:]] = attr_dict[in_key] else: new_attr_dict[in_key[1:]] = max(pre_channel) if idx == last_weight_layer_idx: new_attr_dict[out_key[1:]] = attr_dict[out_key] else: new_attr_dict[out_key[1:]] = max(cur_channel) new_attr_dict['candidate_config'].update({ 'channel': cur_channel }) pre_channel = cur_channel else: new_attr_dict[in_key[1:]] = attr_dict[in_key] new_attr_dict[out_key[1:]] = attr_dict[out_key] for attr in new_attr_name: if attr == 'weight_attr': new_attr_dict[attr] = attr_dict['_param_attr'] else: new_attr_dict[attr] = attr_dict['_' + attr] del layer if attr_dict['_groups'] == None or int(attr_dict[ '_groups']) == 1: ### standard conv layer = Block(SuperConv2D(**new_attr_dict), key=key) elif int(attr_dict['_groups']) == int(attr_dict[in_key]): # if conv is depthwise conv, groups = in_channel, out_channel = in_channel, # channel in candidate_config = in_channel_list if 'channel' in new_attr_dict['candidate_config']: new_attr_dict[in_key[1:]] = max(cur_channel) new_attr_dict[out_key[1:]] = new_attr_dict[in_key[1:]] new_attr_dict['candidate_config'][ 'channel'] = cur_channel new_attr_dict['groups'] = new_attr_dict[in_key[1:]] layer = Block( SuperDepthwiseConv2D(**new_attr_dict), key=key) else: ### group conv layer = Block(SuperGroupConv2D(**new_attr_dict), key=key) model[idx] = layer elif (isinstance(layer, nn.BatchNorm2D) or isinstance(layer, nn.BatchNorm)) and ( getattr(self.context, 'expand', None) != None or getattr(self.context, 'channel', None) != None): # num_features in BatchNorm don't change after last weight operators if idx > last_weight_layer_idx: continue use_bn_old = False if isinstance(layer, nn.BatchNorm): use_bn_old = True attr_dict = layer.__dict__ new_attr_name = ['momentum', 'epsilon', 'bias_attr'] if pd_ver == 185 or use_bn_old: new_attr_name += [ 'param_attr', 'act', 'dtype', 'in_place', 'data_layout', 'is_test', 'use_global_stats', 'trainable_statistics' ] else: new_attr_name += ['weight_attr', 'data_format', 'name'] self._change_name(layer, pd_ver, use_bn_old=use_bn_old) new_attr_dict = dict.fromkeys(new_attr_name, None) if pd_ver == 185 or use_bn_old: new_attr_dict['num_channels'] = None else: new_attr_dict['num_features'] = None new_key = 'num_channels' if 'num_channels' in new_attr_dict.keys( ) else 'num_features' if self.context.expand: new_attr_dict[new_key] = int( self.context.expand * layer._parameters['weight'].shape[0]) elif self.context.channel: new_attr_dict[new_key] = max(cur_channel) else: new_attr_dict[new_key] = attr_dict[ '_num_channels'] if '_num_channels' in attr_dict.keys( ) else attr_dict['_num_features'] for attr in new_attr_name: new_attr_dict[attr] = attr_dict['_' + attr] del layer, attr_dict layer = layers_old.SuperBatchNorm( **new_attr_dict ) if pd_ver == 185 or use_bn_old else layers.SuperBatchNorm2D( **new_attr_dict) model[idx] = layer elif isinstance(layer, SyncBatchNorm) and ( getattr(self.context, 'expand', None) != None or getattr(self.context, 'channel', None) != None): # num_features in SyncBatchNorm don't change after last weight operators if idx > last_weight_layer_idx: continue attr_dict = layer.__dict__ new_attr_name = ['momentum', 'epsilon', 'bias_attr'] new_attr_name += ['weight_attr', 'data_format', 'name'] self._change_name(layer, pd_ver) new_attr_dict = dict.fromkeys(new_attr_name, None) new_attr_dict['num_features'] = None new_key = 'num_channels' if 'num_channels' in new_attr_dict.keys( ) else 'num_features' if self.context.expand: new_attr_dict[new_key] = int( self.context.expand * layer._parameters['weight'].shape[0]) elif self.context.channel: new_attr_dict[new_key] = max(cur_channel) else: new_attr_dict[new_key] = attr_dict[ '_num_channels'] if '_num_channels' in attr_dict.keys( ) else attr_dict['_num_features'] for attr in new_attr_name: new_attr_dict[attr] = attr_dict['_' + attr] del layer, attr_dict layer = layers.SuperSyncBatchNorm(**new_attr_dict) model[idx] = layer ### assume output_size = None, filter_size != None ### NOTE: output_size != None may raise error, solve when it happend. elif isinstance(layer, Conv2DTranspose): attr_dict = layer.__dict__ key = attr_dict['_full_name'] new_attr_name = [ 'stride', 'padding', 'dilation', 'groups', 'bias_attr' ] assert getattr( attr_dict, '_filter_size', '_kernel_size' ) != None, "Conv2DTranspose only support kernel size != None now" if pd_ver == 185: new_attr_name += [ 'output_size', 'param_attr', 'use_cudnn', 'act', 'dtype' ] else: new_attr_name += [ 'output_padding', 'weight_attr', 'data_format' ] new_attr_dict = dict.fromkeys(new_attr_name, None) new_attr_dict['candidate_config'] = dict() if pd_ver == 185: new_attr_dict['num_channels'] = None new_attr_dict['num_filters'] = None new_attr_dict['filter_size'] = None else: new_attr_dict['in_channels'] = None new_attr_dict['out_channels'] = None new_attr_dict['kernel_size'] = None self._change_name(layer, pd_ver, conv=True) self.kernel_size = getattr(self.context, 'kernel_size', None) # if the kernel_size of conv transpose is 1, don't change it. fks = '_filter_size' if '_filter_size' in attr_dict.keys( ) else '_kernel_size' ks = [attr_dict[fks]] if isinstance( attr_dict[fks], numbers.Integral) else attr_dict[fks] if self.kernel_size and int(ks[0]) != 1: new_attr_dict['transform_kernel'] = True new_attr_dict[fks[1:]] = max(self.kernel_size) new_attr_dict['candidate_config'].update({ 'kernel_size': self.kernel_size }) else: new_attr_dict[fks[1:]] = attr_dict[fks] in_key = '_num_channels' if '_num_channels' in attr_dict.keys( ) else '_in_channels' out_key = '_num_filters' if '_num_filters' in attr_dict.keys( ) else '_out_channels' if self.context.expand: ### first super convolution transpose if idx == first_weight_layer_idx: new_attr_dict[in_key[1:]] = attr_dict[in_key] else: new_attr_dict[in_key[1:]] = int(self.context.expand * attr_dict[in_key]) ### last super convolution transpose if idx == last_weight_layer_idx: new_attr_dict[out_key[1:]] = attr_dict[out_key] else: new_attr_dict[out_key[1:]] = int(self.context.expand * attr_dict[out_key]) new_attr_dict['candidate_config'].update({ 'expand_ratio': self.context.expand_ratio }) elif self.context.channel: if attr_dict['_groups'] != None and ( int(attr_dict['_groups']) == int(attr_dict[in_key]) ): ### depthwise conv_transpose _logger.warn( "If convolution is a depthwise conv_transpose, output channel " \ "change to the same channel with input, output channel in search is not used." ) cur_channel = pre_channel else: cur_channel = self.context.channel[0] self.context.channel = self.context.channel[1:] if idx == first_weight_layer_idx: new_attr_dict[in_key[1:]] = attr_dict[in_key] else: new_attr_dict[in_key[1:]] = max(pre_channel) if idx == last_weight_layer_idx: new_attr_dict[out_key[1:]] = attr_dict[out_key] else: new_attr_dict[out_key[1:]] = max(cur_channel) new_attr_dict['candidate_config'].update({ 'channel': cur_channel }) pre_channel = cur_channel else: new_attr_dict[in_key[1:]] = attr_dict[in_key] new_attr_dict[out_key[1:]] = attr_dict[out_key] for attr in new_attr_name: if attr == 'weight_attr': new_attr_dict[attr] = attr_dict['_param_attr'] elif attr == 'output_padding': new_attr_dict[attr] = attr_dict[attr] else: new_attr_dict[attr] = attr_dict['_' + attr] del layer if getattr(new_attr_dict, 'output_size', None) == []: new_attr_dict['output_size'] = None if attr_dict['_groups'] == None or int(attr_dict[ '_groups']) == 1: ### standard conv_transpose layer = Block( SuperConv2DTranspose(**new_attr_dict), key=key) elif int(attr_dict['_groups']) == int(attr_dict[in_key]): # if conv is depthwise conv, groups = in_channel, out_channel = in_channel, # channel in candidate_config = in_channel_list if 'channel' in new_attr_dict['candidate_config']: new_attr_dict[in_key[1:]] = max(cur_channel) new_attr_dict[out_key[1:]] = new_attr_dict[in_key[1:]] new_attr_dict['candidate_config'][ 'channel'] = cur_channel new_attr_dict['groups'] = new_attr_dict[in_key[1:]] layer = Block( SuperDepthwiseConv2DTranspose(**new_attr_dict), key=key) else: ### group conv_transpose layer = Block( SuperGroupConv2DTranspose(**new_attr_dict), key=key) model[idx] = layer elif isinstance(layer, Linear) and ( getattr(self.context, 'expand', None) != None or getattr(self.context, 'channel', None) != None): attr_dict = layer.__dict__ key = attr_dict['_full_name'] if pd_ver == 185: new_attr_name = ['act', 'dtype'] else: new_attr_name = ['weight_attr', 'bias_attr'] self._change_name(layer, pd_ver) if pd_ver != 185 else None in_nc, out_nc = layer._parameters['weight'].shape new_attr_dict = dict.fromkeys(new_attr_name, None) new_attr_dict['candidate_config'] = dict() if pd_ver == 185: new_attr_dict['input_dim'] = None new_attr_dict['output_dim'] = None else: new_attr_dict['in_features'] = None new_attr_dict['out_features'] = None in_key = '_input_dim' if pd_ver == 185 else '_in_features' out_key = '_output_dim' if pd_ver == 185 else '_out_features' attr_dict[in_key] = in_nc attr_dict[out_key] = out_nc if self.context.expand: if idx == first_weight_layer_idx: new_attr_dict[in_key[1:]] = int(attr_dict[in_key]) else: new_attr_dict[in_key[1:]] = int(self.context.expand * attr_dict[in_key]) if idx == last_weight_layer_idx: new_attr_dict[out_key[1:]] = int(attr_dict[out_key]) else: new_attr_dict[out_key[1:]] = int(self.context.expand * attr_dict[out_key]) new_attr_dict['candidate_config'].update({ 'expand_ratio': self.context.expand_ratio }) elif self.context.channel: cur_channel = self.context.channel[0] self.context.channel = self.context.channel[1:] if idx == first_weight_layer_idx: new_attr_dict[in_key[1:]] = int(attr_dict[in_key]) else: new_attr_dict[in_key[1:]] = max(pre_channel) if idx == last_weight_layer_idx: new_attr_dict[out_key[1:]] = int(attr_dict[out_key]) else: new_attr_dict[out_key[1:]] = max(cur_channel) new_attr_dict['candidate_config'].update({ 'channel': cur_channel }) pre_channel = cur_channel else: new_attr_dict[in_key[1:]] = int(attr_dict[in_key]) new_attr_dict[out_key[1:]] = int(attr_dict[out_key]) for attr in new_attr_name: new_attr_dict[attr] = attr_dict['_' + attr] del layer, attr_dict layer = Block(SuperLinear(**new_attr_dict), key=key) model[idx] = layer elif isinstance( layer, getattr(nn, 'InstanceNorm2D', paddle.fluid.dygraph.nn.InstanceNorm)) and ( getattr(self.context, 'expand', None) != None or getattr(self.context, 'channel', None) != None): # num_features in InstanceNorm don't change after last weight operators if idx > last_weight_layer_idx: continue attr_dict = layer.__dict__ if pd_ver == 185: new_attr_name = [ 'bias_attr', 'epsilon', 'param_attr', 'dtype' ] else: new_attr_name = ['bias_attr', 'epsilon', 'weight_attr'] self._change_name(layer, pd_ver) new_attr_dict = dict.fromkeys(new_attr_name, None) if pd_ver == 185: new_attr_dict['num_channels'] = None else: new_attr_dict['num_features'] = None new_key = '_num_channels' if '_num_channels' in new_attr_dict.keys( ) else '_num_features' ### 10 is a default channel in the case of weight_attr=False, in this condition, num of channels if useless, so give it arbitrarily. attr_dict[new_key] = layer._parameters['scale'].shape[0] if len( layer._parameters) != 0 else 10 if self.context.expand: new_attr_dict[new_key[1:]] = int(self.context.expand * attr_dict[new_key]) elif self.context.channel: new_attr_dict[new_key[1:]] = max(cur_channel) else: new_attr_dict[new_key[1:]] = attr_dict[new_key] for attr in new_attr_name: new_attr_dict[attr] = attr_dict['_' + attr] del layer, attr_dict layer = layers.SuperInstanceNorm( **new_attr_dict ) if pd_ver == 185 else layers.SuperInstanceNorm2D( **new_attr_dict) model[idx] = layer elif isinstance(layer, LayerNorm) and ( getattr(self.context, 'expand', None) != None or getattr(self.context, 'channel', None) != None): ### TODO(ceci3): fix when normalized_shape != last_dim_of_input if idx > last_weight_layer_idx: continue attr_dict = layer.__dict__ new_attr_name = ['epsilon', 'bias_attr'] if pd_ver == 185: new_attr_name += [ 'scale', 'shift', 'param_attr', 'act', 'dtype' ] else: new_attr_name += ['weight_attr'] self._change_name(layer, pd_ver) new_attr_dict = dict.fromkeys(new_attr_name, None) new_attr_dict['normalized_shape'] = None if self.context.expand: new_attr_dict['normalized_shape'] = int( self.context.expand * attr_dict['_normalized_shape'][0]) elif self.context.channel: new_attr_dict['normalized_shape'] = max(cur_channel) else: new_attr_dict['normalized_shape'] = attr_dict[ '_normalized_shape'] for attr in new_attr_name: new_attr_dict[attr] = attr_dict['_' + attr] del layer, attr_dict layer = SuperLayerNorm(**new_attr_dict) model[idx] = layer elif isinstance(layer, Embedding) and ( getattr(self.context, 'expand', None) != None or getattr(self.context, 'channel', None) != None): attr_dict = layer.__dict__ key = attr_dict['_full_name'] new_attr_name = [] if pd_ver == 185: new_attr_name += [ 'is_sparse', 'is_distributed', 'param_attr', 'dtype' ] else: new_attr_name += ['sparse', 'weight_attr', 'name'] self._change_name(layer, pd_ver, has_bias=False) new_attr_dict = dict.fromkeys(new_attr_name, None) new_attr_dict['candidate_config'] = dict() bef_size = attr_dict['_size'] if self.context.expand: if pd_ver == 185: new_attr_dict['size'] = [ bef_size[0], int(self.context.expand * bef_size[1]) ] else: new_attr_dict['num_embeddings'] = attr_dict[ '_num_embeddings'] new_attr_dict['embedding_dim'] = int( self.context.expand * attr_dict['_embedding_dim']) new_attr_dict['candidate_config'].update({ 'expand_ratio': self.context.expand_ratio }) elif self.context.channel: cur_channel = self.context.channel[0] self.context.channel = self.context.channel[1:] if pd_ver == 185: new_attr_dict['size'] = [bef_size[0], max(cur_channel)] else: new_attr_dict['num_embeddings'] = attr_dict[ '_num_embeddings'] new_attr_dict['embedding_dim'] = max(cur_channel) new_attr_dict['candidate_config'].update({ 'channel': cur_channel }) pre_channel = cur_channel else: if pf_ver == 185: new_attr_dict['size'] = bef_size else: new_attr_dict['num_embeddings'] = attr_dict[ '_num_embeddings'] new_attr_dict['embedding_dim'] = attr_dict[ '_embedding_dim'] for attr in new_attr_name: new_attr_dict[attr] = attr_dict['_' + attr] new_attr_dict['padding_idx'] = None if attr_dict[ '_padding_idx'] == -1 else attr_dict['_padding_idx'] del layer, attr_dict layer = Block(SuperEmbedding(**new_attr_dict), key=key) model[idx] = layer if isinstance(network, Layer): curr_id = 0 self.name_list = [] get_split_names(network, []) for idx, nl in enumerate(self.name_list): if len(nl) > 1: net = split_prefix(network, nl[:-1]) else: net = network setattr(net, nl[-1], model[idx]) return network class supernet: """ Search space of the network. Parameters: kernel_size(list|tuple, optional): search space for the kernel size of the Conv2D. expand_ratio(list|tuple, optional): the search space for the expand ratio of the number of channels of Conv2D, the expand ratio of the output dimensions of the Embedding or Linear, which means this parameter get the number of channels of each OP in the converted super network based on the the channels of each OP in the original model, so this parameter The length is 1. Just set one between this parameter and ``channel``. channel(list|tuple, optional): the search space for the number of channels of Conv2D, the output dimensions of the Embedding or Linear, this parameter directly sets the number of channels of each OP in the super network, so the length of this parameter needs to be the same as the total number that of Conv2D, Embedding, and Linear included in the network. Just set one between this parameter and ``expand_ratio``. """ #def ofa_supernet(kernel_size, expand_ratio): # def _ofa_supernet(func): # @functools.wraps(func) # def convert(*args, **kwargs): # supernet_convert(*args, **kwargs) # return convert # return _ofa_supernet
45.354167
432
0.507206
# 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect import decorator import logging import numbers import paddle from ...common import get_logger from .utils.utils import get_paddle_version pd_ver = get_paddle_version() if pd_ver == 185: import paddle.fluid.dygraph.nn as nn from paddle.fluid.dygraph.nn import Conv2D, Conv2DTranspose, Linear, LayerNorm, Embedding from paddle.fluid import ParamAttr from .layers_old import * from . import layers_old as layers Layer = paddle.fluid.dygraph.Layer else: import paddle.nn as nn from paddle.nn import Conv2D, Conv2DTranspose, Linear, LayerNorm, Embedding, SyncBatchNorm from paddle import ParamAttr from .layers import * from . import layers Layer = paddle.nn.Layer from .layers_base import Block from . import layers_old _logger = get_logger(__name__, level=logging.INFO) __all__ = ['supernet', 'Convert'] WEIGHT_LAYER = ['conv', 'linear', 'embedding'] class Convert: """ Convert network to the supernet according to the search space. Parameters: context(paddleslim.nas.ofa.supernet): search space defined by the user. Examples: .. code-block:: python from paddleslim.nas.ofa import supernet, Convert sp_net_config = supernet(kernel_size=(3, 5, 7), expand_ratio=[1, 2, 4]) convert = Convert(sp_net_config) """ def __init__(self, context): self.context = context def _change_name(self, layer, pd_ver, has_bias=True, conv=False, use_bn_old=False): if conv: w_attr = layer._param_attr else: w_attr = layer._param_attr if pd_ver == 185 or use_bn_old else layer._weight_attr if isinstance(w_attr, ParamAttr): if w_attr != None and not isinstance(w_attr, bool) and w_attr.name != None: w_attr.name = 'super_' + w_attr.name if has_bias: if isinstance(layer._bias_attr, ParamAttr): if layer._bias_attr != None and not isinstance( layer._bias_attr, bool) and layer._bias_attr.name != None: layer._bias_attr.name = 'super_' + layer._bias_attr.name def convert(self, network): """ The function to convert the network to a supernet. Parameters: network(paddle.nn.Layer|list(paddle.nn.Layer)): instance of the model or list of instance of layers. Examples: .. code-block:: python from paddle.vision.models import mobilenet_v1 from paddleslim.nas.ofa import supernet, Convert sp_net_config = supernet(kernel_size=(3, 5, 7), expand_ratio=[1, 2, 4]) convert = Convert(sp_net_config).convert(mobilenet_v1()) """ # search the first and last weight layer, don't change out channel of the last weight layer # don't change in channel of the first weight layer model = [] if isinstance(network, Layer): for name, sublayer in network.named_sublayers(): model.append(sublayer) else: model = network first_weight_layer_idx = -1 last_weight_layer_idx = -1 weight_layer_count = 0 # NOTE: pre_channel store for shortcut module pre_channel = None cur_channel = None for idx, layer in enumerate(model): cls_name = layer.__class__.__name__.lower() ### basic api in paddle if len(layer.sublayers()) == 0: if 'conv' in cls_name or 'linear' in cls_name or 'embedding' in cls_name: weight_layer_count += 1 last_weight_layer_idx = idx if first_weight_layer_idx == -1: first_weight_layer_idx = idx if getattr(self.context, 'channel', None) != None: assert len( self.context.channel ) == weight_layer_count, "length of channel must same as weight layer." for idx, layer in enumerate(model): if isinstance(layer, Conv2D): attr_dict = layer.__dict__ key = attr_dict['_full_name'] new_attr_name = [ 'stride', 'padding', 'dilation', 'groups', 'bias_attr' ] if pd_ver == 185: new_attr_name += ['param_attr', 'use_cudnn', 'act', 'dtype'] else: new_attr_name += [ 'weight_attr', 'data_format', 'padding_mode' ] self._change_name(layer, pd_ver, conv=True) new_attr_dict = dict.fromkeys(new_attr_name, None) new_attr_dict['candidate_config'] = dict() if pd_ver == 185: new_attr_dict['num_channels'] = None new_attr_dict['num_filters'] = None new_attr_dict['filter_size'] = None else: new_attr_dict['in_channels'] = None new_attr_dict['out_channels'] = None new_attr_dict['kernel_size'] = None self.kernel_size = getattr(self.context, 'kernel_size', None) # if the kernel_size of conv is 1, don't change it. fks = '_filter_size' if '_filter_size' in attr_dict.keys( ) else '_kernel_size' ks = [attr_dict[fks]] if isinstance( attr_dict[fks], numbers.Integral) else attr_dict[fks] if self.kernel_size and int(ks[0]) != 1: new_attr_dict['transform_kernel'] = True new_attr_dict[fks[1:]] = max(self.kernel_size) new_attr_dict['candidate_config'].update({ 'kernel_size': self.kernel_size }) else: new_attr_dict[fks[1:]] = attr_dict[fks] in_key = '_num_channels' if '_num_channels' in attr_dict.keys( ) else '_in_channels' out_key = '_num_filters' if '_num_filters' in attr_dict.keys( ) else '_out_channels' if self.context.expand: ### first super convolution if idx == first_weight_layer_idx: new_attr_dict[in_key[1:]] = attr_dict[in_key] else: new_attr_dict[in_key[1:]] = int(self.context.expand * attr_dict[in_key]) ### last super convolution if idx == last_weight_layer_idx: new_attr_dict[out_key[1:]] = attr_dict[out_key] else: new_attr_dict[out_key[1:]] = int(self.context.expand * attr_dict[out_key]) new_attr_dict['candidate_config'].update({ 'expand_ratio': self.context.expand_ratio }) elif self.context.channel: if attr_dict['_groups'] != None and ( int(attr_dict['_groups']) == int(attr_dict[in_key]) ): ### depthwise conv, if conv is depthwise, use pre channel as cur_channel _logger.warn( "If convolution is a depthwise conv, output channel change" \ " to the same channel with input, output channel in search is not used." ) cur_channel = pre_channel else: cur_channel = self.context.channel[0] self.context.channel = self.context.channel[1:] if idx == first_weight_layer_idx: new_attr_dict[in_key[1:]] = attr_dict[in_key] else: new_attr_dict[in_key[1:]] = max(pre_channel) if idx == last_weight_layer_idx: new_attr_dict[out_key[1:]] = attr_dict[out_key] else: new_attr_dict[out_key[1:]] = max(cur_channel) new_attr_dict['candidate_config'].update({ 'channel': cur_channel }) pre_channel = cur_channel else: new_attr_dict[in_key[1:]] = attr_dict[in_key] new_attr_dict[out_key[1:]] = attr_dict[out_key] for attr in new_attr_name: if attr == 'weight_attr': new_attr_dict[attr] = attr_dict['_param_attr'] else: new_attr_dict[attr] = attr_dict['_' + attr] del layer if attr_dict['_groups'] == None or int(attr_dict[ '_groups']) == 1: ### standard conv layer = Block(SuperConv2D(**new_attr_dict), key=key) elif int(attr_dict['_groups']) == int(attr_dict[in_key]): # if conv is depthwise conv, groups = in_channel, out_channel = in_channel, # channel in candidate_config = in_channel_list if 'channel' in new_attr_dict['candidate_config']: new_attr_dict[in_key[1:]] = max(cur_channel) new_attr_dict[out_key[1:]] = new_attr_dict[in_key[1:]] new_attr_dict['candidate_config'][ 'channel'] = cur_channel new_attr_dict['groups'] = new_attr_dict[in_key[1:]] layer = Block( SuperDepthwiseConv2D(**new_attr_dict), key=key) else: ### group conv layer = Block(SuperGroupConv2D(**new_attr_dict), key=key) model[idx] = layer elif (isinstance(layer, nn.BatchNorm2D) or isinstance(layer, nn.BatchNorm)) and ( getattr(self.context, 'expand', None) != None or getattr(self.context, 'channel', None) != None): # num_features in BatchNorm don't change after last weight operators if idx > last_weight_layer_idx: continue use_bn_old = False if isinstance(layer, nn.BatchNorm): use_bn_old = True attr_dict = layer.__dict__ new_attr_name = ['momentum', 'epsilon', 'bias_attr'] if pd_ver == 185 or use_bn_old: new_attr_name += [ 'param_attr', 'act', 'dtype', 'in_place', 'data_layout', 'is_test', 'use_global_stats', 'trainable_statistics' ] else: new_attr_name += ['weight_attr', 'data_format', 'name'] self._change_name(layer, pd_ver, use_bn_old=use_bn_old) new_attr_dict = dict.fromkeys(new_attr_name, None) if pd_ver == 185 or use_bn_old: new_attr_dict['num_channels'] = None else: new_attr_dict['num_features'] = None new_key = 'num_channels' if 'num_channels' in new_attr_dict.keys( ) else 'num_features' if self.context.expand: new_attr_dict[new_key] = int( self.context.expand * layer._parameters['weight'].shape[0]) elif self.context.channel: new_attr_dict[new_key] = max(cur_channel) else: new_attr_dict[new_key] = attr_dict[ '_num_channels'] if '_num_channels' in attr_dict.keys( ) else attr_dict['_num_features'] for attr in new_attr_name: new_attr_dict[attr] = attr_dict['_' + attr] del layer, attr_dict layer = layers_old.SuperBatchNorm( **new_attr_dict ) if pd_ver == 185 or use_bn_old else layers.SuperBatchNorm2D( **new_attr_dict) model[idx] = layer elif isinstance(layer, SyncBatchNorm) and ( getattr(self.context, 'expand', None) != None or getattr(self.context, 'channel', None) != None): # num_features in SyncBatchNorm don't change after last weight operators if idx > last_weight_layer_idx: continue attr_dict = layer.__dict__ new_attr_name = ['momentum', 'epsilon', 'bias_attr'] new_attr_name += ['weight_attr', 'data_format', 'name'] self._change_name(layer, pd_ver) new_attr_dict = dict.fromkeys(new_attr_name, None) new_attr_dict['num_features'] = None new_key = 'num_channels' if 'num_channels' in new_attr_dict.keys( ) else 'num_features' if self.context.expand: new_attr_dict[new_key] = int( self.context.expand * layer._parameters['weight'].shape[0]) elif self.context.channel: new_attr_dict[new_key] = max(cur_channel) else: new_attr_dict[new_key] = attr_dict[ '_num_channels'] if '_num_channels' in attr_dict.keys( ) else attr_dict['_num_features'] for attr in new_attr_name: new_attr_dict[attr] = attr_dict['_' + attr] del layer, attr_dict layer = layers.SuperSyncBatchNorm(**new_attr_dict) model[idx] = layer ### assume output_size = None, filter_size != None ### NOTE: output_size != None may raise error, solve when it happend. elif isinstance(layer, Conv2DTranspose): attr_dict = layer.__dict__ key = attr_dict['_full_name'] new_attr_name = [ 'stride', 'padding', 'dilation', 'groups', 'bias_attr' ] assert getattr( attr_dict, '_filter_size', '_kernel_size' ) != None, "Conv2DTranspose only support kernel size != None now" if pd_ver == 185: new_attr_name += [ 'output_size', 'param_attr', 'use_cudnn', 'act', 'dtype' ] else: new_attr_name += [ 'output_padding', 'weight_attr', 'data_format' ] new_attr_dict = dict.fromkeys(new_attr_name, None) new_attr_dict['candidate_config'] = dict() if pd_ver == 185: new_attr_dict['num_channels'] = None new_attr_dict['num_filters'] = None new_attr_dict['filter_size'] = None else: new_attr_dict['in_channels'] = None new_attr_dict['out_channels'] = None new_attr_dict['kernel_size'] = None self._change_name(layer, pd_ver, conv=True) self.kernel_size = getattr(self.context, 'kernel_size', None) # if the kernel_size of conv transpose is 1, don't change it. fks = '_filter_size' if '_filter_size' in attr_dict.keys( ) else '_kernel_size' ks = [attr_dict[fks]] if isinstance( attr_dict[fks], numbers.Integral) else attr_dict[fks] if self.kernel_size and int(ks[0]) != 1: new_attr_dict['transform_kernel'] = True new_attr_dict[fks[1:]] = max(self.kernel_size) new_attr_dict['candidate_config'].update({ 'kernel_size': self.kernel_size }) else: new_attr_dict[fks[1:]] = attr_dict[fks] in_key = '_num_channels' if '_num_channels' in attr_dict.keys( ) else '_in_channels' out_key = '_num_filters' if '_num_filters' in attr_dict.keys( ) else '_out_channels' if self.context.expand: ### first super convolution transpose if idx == first_weight_layer_idx: new_attr_dict[in_key[1:]] = attr_dict[in_key] else: new_attr_dict[in_key[1:]] = int(self.context.expand * attr_dict[in_key]) ### last super convolution transpose if idx == last_weight_layer_idx: new_attr_dict[out_key[1:]] = attr_dict[out_key] else: new_attr_dict[out_key[1:]] = int(self.context.expand * attr_dict[out_key]) new_attr_dict['candidate_config'].update({ 'expand_ratio': self.context.expand_ratio }) elif self.context.channel: if attr_dict['_groups'] != None and ( int(attr_dict['_groups']) == int(attr_dict[in_key]) ): ### depthwise conv_transpose _logger.warn( "If convolution is a depthwise conv_transpose, output channel " \ "change to the same channel with input, output channel in search is not used." ) cur_channel = pre_channel else: cur_channel = self.context.channel[0] self.context.channel = self.context.channel[1:] if idx == first_weight_layer_idx: new_attr_dict[in_key[1:]] = attr_dict[in_key] else: new_attr_dict[in_key[1:]] = max(pre_channel) if idx == last_weight_layer_idx: new_attr_dict[out_key[1:]] = attr_dict[out_key] else: new_attr_dict[out_key[1:]] = max(cur_channel) new_attr_dict['candidate_config'].update({ 'channel': cur_channel }) pre_channel = cur_channel else: new_attr_dict[in_key[1:]] = attr_dict[in_key] new_attr_dict[out_key[1:]] = attr_dict[out_key] for attr in new_attr_name: if attr == 'weight_attr': new_attr_dict[attr] = attr_dict['_param_attr'] elif attr == 'output_padding': new_attr_dict[attr] = attr_dict[attr] else: new_attr_dict[attr] = attr_dict['_' + attr] del layer if getattr(new_attr_dict, 'output_size', None) == []: new_attr_dict['output_size'] = None if attr_dict['_groups'] == None or int(attr_dict[ '_groups']) == 1: ### standard conv_transpose layer = Block( SuperConv2DTranspose(**new_attr_dict), key=key) elif int(attr_dict['_groups']) == int(attr_dict[in_key]): # if conv is depthwise conv, groups = in_channel, out_channel = in_channel, # channel in candidate_config = in_channel_list if 'channel' in new_attr_dict['candidate_config']: new_attr_dict[in_key[1:]] = max(cur_channel) new_attr_dict[out_key[1:]] = new_attr_dict[in_key[1:]] new_attr_dict['candidate_config'][ 'channel'] = cur_channel new_attr_dict['groups'] = new_attr_dict[in_key[1:]] layer = Block( SuperDepthwiseConv2DTranspose(**new_attr_dict), key=key) else: ### group conv_transpose layer = Block( SuperGroupConv2DTranspose(**new_attr_dict), key=key) model[idx] = layer elif isinstance(layer, Linear) and ( getattr(self.context, 'expand', None) != None or getattr(self.context, 'channel', None) != None): attr_dict = layer.__dict__ key = attr_dict['_full_name'] if pd_ver == 185: new_attr_name = ['act', 'dtype'] else: new_attr_name = ['weight_attr', 'bias_attr'] self._change_name(layer, pd_ver) if pd_ver != 185 else None in_nc, out_nc = layer._parameters['weight'].shape new_attr_dict = dict.fromkeys(new_attr_name, None) new_attr_dict['candidate_config'] = dict() if pd_ver == 185: new_attr_dict['input_dim'] = None new_attr_dict['output_dim'] = None else: new_attr_dict['in_features'] = None new_attr_dict['out_features'] = None in_key = '_input_dim' if pd_ver == 185 else '_in_features' out_key = '_output_dim' if pd_ver == 185 else '_out_features' attr_dict[in_key] = in_nc attr_dict[out_key] = out_nc if self.context.expand: if idx == first_weight_layer_idx: new_attr_dict[in_key[1:]] = int(attr_dict[in_key]) else: new_attr_dict[in_key[1:]] = int(self.context.expand * attr_dict[in_key]) if idx == last_weight_layer_idx: new_attr_dict[out_key[1:]] = int(attr_dict[out_key]) else: new_attr_dict[out_key[1:]] = int(self.context.expand * attr_dict[out_key]) new_attr_dict['candidate_config'].update({ 'expand_ratio': self.context.expand_ratio }) elif self.context.channel: cur_channel = self.context.channel[0] self.context.channel = self.context.channel[1:] if idx == first_weight_layer_idx: new_attr_dict[in_key[1:]] = int(attr_dict[in_key]) else: new_attr_dict[in_key[1:]] = max(pre_channel) if idx == last_weight_layer_idx: new_attr_dict[out_key[1:]] = int(attr_dict[out_key]) else: new_attr_dict[out_key[1:]] = max(cur_channel) new_attr_dict['candidate_config'].update({ 'channel': cur_channel }) pre_channel = cur_channel else: new_attr_dict[in_key[1:]] = int(attr_dict[in_key]) new_attr_dict[out_key[1:]] = int(attr_dict[out_key]) for attr in new_attr_name: new_attr_dict[attr] = attr_dict['_' + attr] del layer, attr_dict layer = Block(SuperLinear(**new_attr_dict), key=key) model[idx] = layer elif isinstance( layer, getattr(nn, 'InstanceNorm2D', paddle.fluid.dygraph.nn.InstanceNorm)) and ( getattr(self.context, 'expand', None) != None or getattr(self.context, 'channel', None) != None): # num_features in InstanceNorm don't change after last weight operators if idx > last_weight_layer_idx: continue attr_dict = layer.__dict__ if pd_ver == 185: new_attr_name = [ 'bias_attr', 'epsilon', 'param_attr', 'dtype' ] else: new_attr_name = ['bias_attr', 'epsilon', 'weight_attr'] self._change_name(layer, pd_ver) new_attr_dict = dict.fromkeys(new_attr_name, None) if pd_ver == 185: new_attr_dict['num_channels'] = None else: new_attr_dict['num_features'] = None new_key = '_num_channels' if '_num_channels' in new_attr_dict.keys( ) else '_num_features' ### 10 is a default channel in the case of weight_attr=False, in this condition, num of channels if useless, so give it arbitrarily. attr_dict[new_key] = layer._parameters['scale'].shape[0] if len( layer._parameters) != 0 else 10 if self.context.expand: new_attr_dict[new_key[1:]] = int(self.context.expand * attr_dict[new_key]) elif self.context.channel: new_attr_dict[new_key[1:]] = max(cur_channel) else: new_attr_dict[new_key[1:]] = attr_dict[new_key] for attr in new_attr_name: new_attr_dict[attr] = attr_dict['_' + attr] del layer, attr_dict layer = layers.SuperInstanceNorm( **new_attr_dict ) if pd_ver == 185 else layers.SuperInstanceNorm2D( **new_attr_dict) model[idx] = layer elif isinstance(layer, LayerNorm) and ( getattr(self.context, 'expand', None) != None or getattr(self.context, 'channel', None) != None): ### TODO(ceci3): fix when normalized_shape != last_dim_of_input if idx > last_weight_layer_idx: continue attr_dict = layer.__dict__ new_attr_name = ['epsilon', 'bias_attr'] if pd_ver == 185: new_attr_name += [ 'scale', 'shift', 'param_attr', 'act', 'dtype' ] else: new_attr_name += ['weight_attr'] self._change_name(layer, pd_ver) new_attr_dict = dict.fromkeys(new_attr_name, None) new_attr_dict['normalized_shape'] = None if self.context.expand: new_attr_dict['normalized_shape'] = int( self.context.expand * attr_dict['_normalized_shape'][0]) elif self.context.channel: new_attr_dict['normalized_shape'] = max(cur_channel) else: new_attr_dict['normalized_shape'] = attr_dict[ '_normalized_shape'] for attr in new_attr_name: new_attr_dict[attr] = attr_dict['_' + attr] del layer, attr_dict layer = SuperLayerNorm(**new_attr_dict) model[idx] = layer elif isinstance(layer, Embedding) and ( getattr(self.context, 'expand', None) != None or getattr(self.context, 'channel', None) != None): attr_dict = layer.__dict__ key = attr_dict['_full_name'] new_attr_name = [] if pd_ver == 185: new_attr_name += [ 'is_sparse', 'is_distributed', 'param_attr', 'dtype' ] else: new_attr_name += ['sparse', 'weight_attr', 'name'] self._change_name(layer, pd_ver, has_bias=False) new_attr_dict = dict.fromkeys(new_attr_name, None) new_attr_dict['candidate_config'] = dict() bef_size = attr_dict['_size'] if self.context.expand: if pd_ver == 185: new_attr_dict['size'] = [ bef_size[0], int(self.context.expand * bef_size[1]) ] else: new_attr_dict['num_embeddings'] = attr_dict[ '_num_embeddings'] new_attr_dict['embedding_dim'] = int( self.context.expand * attr_dict['_embedding_dim']) new_attr_dict['candidate_config'].update({ 'expand_ratio': self.context.expand_ratio }) elif self.context.channel: cur_channel = self.context.channel[0] self.context.channel = self.context.channel[1:] if pd_ver == 185: new_attr_dict['size'] = [bef_size[0], max(cur_channel)] else: new_attr_dict['num_embeddings'] = attr_dict[ '_num_embeddings'] new_attr_dict['embedding_dim'] = max(cur_channel) new_attr_dict['candidate_config'].update({ 'channel': cur_channel }) pre_channel = cur_channel else: if pf_ver == 185: new_attr_dict['size'] = bef_size else: new_attr_dict['num_embeddings'] = attr_dict[ '_num_embeddings'] new_attr_dict['embedding_dim'] = attr_dict[ '_embedding_dim'] for attr in new_attr_name: new_attr_dict[attr] = attr_dict['_' + attr] new_attr_dict['padding_idx'] = None if attr_dict[ '_padding_idx'] == -1 else attr_dict['_padding_idx'] del layer, attr_dict layer = Block(SuperEmbedding(**new_attr_dict), key=key) model[idx] = layer def split_prefix(net, name_list): if len(name_list) > 1: net = split_prefix(getattr(net, name_list[0]), name_list[1:]) elif len(name_list) == 1: net = getattr(net, name_list[0]) else: raise NotImplementedError("name error") return net def get_split_names(layer, name_list): if name_list: self.name_list.append(name_list) for _, (name, sublayer) in enumerate(layer.named_children()): if sublayer.named_children(): get_split_names(sublayer, name_list + [name]) if isinstance(network, Layer): curr_id = 0 self.name_list = [] get_split_names(network, []) for idx, nl in enumerate(self.name_list): if len(nl) > 1: net = split_prefix(network, nl[:-1]) else: net = network setattr(net, nl[-1], model[idx]) return network class supernet: """ Search space of the network. Parameters: kernel_size(list|tuple, optional): search space for the kernel size of the Conv2D. expand_ratio(list|tuple, optional): the search space for the expand ratio of the number of channels of Conv2D, the expand ratio of the output dimensions of the Embedding or Linear, which means this parameter get the number of channels of each OP in the converted super network based on the the channels of each OP in the original model, so this parameter The length is 1. Just set one between this parameter and ``channel``. channel(list|tuple, optional): the search space for the number of channels of Conv2D, the output dimensions of the Embedding or Linear, this parameter directly sets the number of channels of each OP in the super network, so the length of this parameter needs to be the same as the total number that of Conv2D, Embedding, and Linear included in the network. Just set one between this parameter and ``expand_ratio``. """ def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) assert ( getattr(self, 'expand_ratio', None) == None or getattr(self, 'channel', None) == None ), "expand_ratio and channel CANNOT be NOT None at the same time." self.expand = None if 'expand_ratio' in kwargs.keys(): if isinstance(self.expand_ratio, list) or isinstance( self.expand_ratio, tuple): self.expand = max(self.expand_ratio) elif isinstance(self.expand_ratio, int): self.expand = self.expand_ratio if 'channel' not in kwargs.keys(): self.channel = None def __enter__(self): return Convert(self) def __exit__(self, exc_type, exc_val, exc_tb): self.expand = None self.channel = None self.kernel_size = None #def ofa_supernet(kernel_size, expand_ratio): # def _ofa_supernet(func): # @functools.wraps(func) # def convert(*args, **kwargs): # supernet_convert(*args, **kwargs) # return convert # return _ofa_supernet
2,360
0
197
d27d5b61acd3b4c1ac9339b822d86b898b922e93
419
py
Python
ch6/stopwordfacts.py
bronevet-abc/NLPython
edb2f2c558215df556449c0fafb717d3442cfd9b
[ "MIT" ]
null
null
null
ch6/stopwordfacts.py
bronevet-abc/NLPython
edb2f2c558215df556449c0fafb717d3442cfd9b
[ "MIT" ]
null
null
null
ch6/stopwordfacts.py
bronevet-abc/NLPython
edb2f2c558215df556449c0fafb717d3442cfd9b
[ "MIT" ]
null
null
null
from gensim import models w = models.Word2Vec.load_word2vec_format('/home/jalaj/Downloads/GoogleNews-vectors-negative300.bin', binary=True) if 'the' in w.wv.vocab: print("Vector for word 'the' \n") print(w.wv['the']) else: print("Vocabulary doesn't include word 'the'\n") if 'a' in w.wv.vocab: print("Vector for word 'a' \n") print(w.wv['a']) else: print("Vocabulary doesn't include word 'a'\n")
34.916667
113
0.677804
from gensim import models w = models.Word2Vec.load_word2vec_format('/home/jalaj/Downloads/GoogleNews-vectors-negative300.bin', binary=True) if 'the' in w.wv.vocab: print("Vector for word 'the' \n") print(w.wv['the']) else: print("Vocabulary doesn't include word 'the'\n") if 'a' in w.wv.vocab: print("Vector for word 'a' \n") print(w.wv['a']) else: print("Vocabulary doesn't include word 'a'\n")
0
0
0
65d276966f308225a1010b7dd886205ed3264332
327
py
Python
django_yubin/iter_utils.py
pmendezsuarez/django-yubin
6832bb2bb5b3aa8e00c9484475db9c4a593de2f0
[ "Apache-2.0" ]
37
2015-02-27T15:35:55.000Z
2022-02-11T13:58:29.000Z
django_yubin/iter_utils.py
pmendezsuarez/django-yubin
6832bb2bb5b3aa8e00c9484475db9c4a593de2f0
[ "Apache-2.0" ]
56
2015-02-04T00:18:39.000Z
2022-01-17T14:25:18.000Z
django_yubin/iter_utils.py
pmendezsuarez/django-yubin
6832bb2bb5b3aa8e00c9484475db9c4a593de2f0
[ "Apache-2.0" ]
29
2015-05-18T15:53:45.000Z
2021-12-17T11:37:31.000Z
import itertools def peek(sequence): """ Returns the value of the top of the sequence without removing the value from the data. """ iterable = iter(sequence) try: first = next(iterable) return first, itertools.chain([first], iterable) except StopIteration: return None, []
21.8
75
0.633028
import itertools def peek(sequence): """ Returns the value of the top of the sequence without removing the value from the data. """ iterable = iter(sequence) try: first = next(iterable) return first, itertools.chain([first], iterable) except StopIteration: return None, []
0
0
0
efc0190db60d88a60ad8561d578bd624621bc097
5,073
py
Python
RadClass/H0.py
CNERG/RadClass
70b70624e41fee2e0a6229c7ab7aa4f3249b5a0f
[ "BSD-3-Clause" ]
1
2021-03-26T05:30:49.000Z
2021-03-26T05:30:49.000Z
RadClass/H0.py
CNERG/RadClass
70b70624e41fee2e0a6229c7ab7aa4f3249b5a0f
[ "BSD-3-Clause" ]
34
2021-03-29T14:37:14.000Z
2022-03-16T21:35:01.000Z
RadClass/H0.py
CNERG/RadClass
70b70624e41fee2e0a6229c7ab7aa4f3249b5a0f
[ "BSD-3-Clause" ]
2
2021-03-26T19:04:57.000Z
2021-11-24T14:13:13.000Z
import numpy as np from scipy import stats class H0: ''' Applies binomial hypothesis test to data processed with RadClass. Capable of applying a hypothesis test to gross or channel-wise count-rate. This test relies on the assumption that count-rates measured consecutively in time will not be statistical different from each other. That is, they should come from the same baseline background environment. If they are different (and therefore the null hypothesis is rejected), presumably a radioactive event occurred (e.g. SNM transfer). For information on testing regime, see doi: 10.2307/2332612. For information on scipy's binomial test, see: docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binom_test.html Attributes: significance: Significance level for hypothesis test. If the resulting binomial test's p-value is smaller than significance, null hypothesis is rejected. gross: Boolean; determines whether only the gross count-rate is analyzed (True) or each energy channel individually (False). x1: The first timestamp's count-rate to be tested. x2: The second timestamp's count-rate to be compared with x1. triggers: Three things are saved in this array. x1, x2, and the p-value for rejected null hypotheses per the inputted significance level. trigger_times: The timestamp (in Unix epoch timestamp) for rejected null hypothesis via triggers. ''' def run(self, data, timestamp): ''' Method required by RadClass. Called at each integration step. Completes hypothesis testing for passed data and stores results. Wrapper method that chooses run_gross or run_channel based on user input variable: gross. ''' run_method = { True: self.run_gross, False: self.run_channels } run_method[self.gross](data, timestamp) def write(self, filename): ''' Writes results of hypothesis test to file using numpy.savetxt. ''' with open(filename, 'a') as f: header = '' # build/include header if file is new if f.tell() == 0: if self.gross: header = ['timestamps', 'pval', 'x1', 'x2'] elif not self.gross: header = np.append(['timestamp'], np.arange(self.triggers.shape[0]-1).astype(str)) header = ', '.join(col for col in header) np.savetxt(fname=f, X=self.triggers, delimiter=',', header=header)
40.584
87
0.568697
import numpy as np from scipy import stats class H0: ''' Applies binomial hypothesis test to data processed with RadClass. Capable of applying a hypothesis test to gross or channel-wise count-rate. This test relies on the assumption that count-rates measured consecutively in time will not be statistical different from each other. That is, they should come from the same baseline background environment. If they are different (and therefore the null hypothesis is rejected), presumably a radioactive event occurred (e.g. SNM transfer). For information on testing regime, see doi: 10.2307/2332612. For information on scipy's binomial test, see: docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binom_test.html Attributes: significance: Significance level for hypothesis test. If the resulting binomial test's p-value is smaller than significance, null hypothesis is rejected. gross: Boolean; determines whether only the gross count-rate is analyzed (True) or each energy channel individually (False). x1: The first timestamp's count-rate to be tested. x2: The second timestamp's count-rate to be compared with x1. triggers: Three things are saved in this array. x1, x2, and the p-value for rejected null hypotheses per the inputted significance level. trigger_times: The timestamp (in Unix epoch timestamp) for rejected null hypothesis via triggers. ''' def __init__(self, significance=0.05, gross=True, energy_bins=1000): self.significance = significance self.gross = gross self.x1 = None # arrays are structured as matrices (nxm) for writing to file if self.gross: # four values are saved: timestamp, x1, x2, and p-val self.triggers = np.empty((0, 4)) else: # all p-vals for rejected hypothesis are saved in this sparse array self.triggers = np.empty((0, energy_bins+1)) def run_gross(self, data, timestamp): data = np.sum(data) # only needed for the first initialization if self.x1 is None: self.x1 = data self.x1_timestamp = timestamp else: self.x2 = data n = self.x1 + self.x2 p = 0.5 pval = stats.binom_test(self.x1, n, p, alternative='two-sided') # only save instances with rejected null hypothesesf if pval <= self.significance: self.triggers = np.append(self.triggers, [[self.x1_timestamp, pval, self.x1, self.x2]], axis=0) # saving data for the next integration step self.x1 = self.x2 self.x1_timestamp = timestamp def run_channels(self, data, timestamp): # only needed for the first initialization if self.x1 is None: self.x1 = data self.x1_timestamp = timestamp else: self.x2 = data rejections = np.ones_like(data) nvec = self.x1 + self.x2 p = 0.5 for i, (x1, n) in enumerate(zip(self.x1, nvec)): pval = stats.binom_test(x1, n, p, alternative='two-sided') if pval <= self.significance: rejections[i] = pval if np.sum(rejections) != len(rejections): self.triggers = np.append(self.triggers, [np.insert(rejections, 0, self.x1_timestamp)], axis=0) # saving data for the next integration step self.x1 = self.x2 self.x1_timestamp = timestamp def run(self, data, timestamp): ''' Method required by RadClass. Called at each integration step. Completes hypothesis testing for passed data and stores results. Wrapper method that chooses run_gross or run_channel based on user input variable: gross. ''' run_method = { True: self.run_gross, False: self.run_channels } run_method[self.gross](data, timestamp) def write(self, filename): ''' Writes results of hypothesis test to file using numpy.savetxt. ''' with open(filename, 'a') as f: header = '' # build/include header if file is new if f.tell() == 0: if self.gross: header = ['timestamps', 'pval', 'x1', 'x2'] elif not self.gross: header = np.append(['timestamp'], np.arange(self.triggers.shape[0]-1).astype(str)) header = ', '.join(col for col in header) np.savetxt(fname=f, X=self.triggers, delimiter=',', header=header)
2,328
0
81
4d1560d4925bf5bccbfb37740702d79ea76917da
65,128
py
Python
resources/Wireshark/WiresharkDissectorFoo/help/faq.py
joshis1/C_Programming
4a8003321251448a167bfca0b595c5eeab88608d
[ "MIT" ]
2
2020-09-11T05:51:42.000Z
2020-12-31T11:42:02.000Z
resources/Wireshark/WiresharkDissectorFoo/help/faq.py
joshis1/C_Programming
4a8003321251448a167bfca0b595c5eeab88608d
[ "MIT" ]
null
null
null
resources/Wireshark/WiresharkDissectorFoo/help/faq.py
joshis1/C_Programming
4a8003321251448a167bfca0b595c5eeab88608d
[ "MIT" ]
null
null
null
#!/usr/bin/env python # # faq.py # # Routines to assemble a FAQ list for the Wireshark web site. # Questions and answer content can be found below. Section and # question numbers will be automatically generated. # # Wireshark - Network traffic analyzer # By Gerald Combs <gerald@wireshark.org> # Copyright 1998 Gerald Combs # # SPDX-License-Identifier: GPL-2.0-or-later import sys import string sec_num = 0 subsec_num = 0 subsubsec_num = 0 sections = [] current_section = None parent_section = None grandparent_section = None current_question = None current_tag = None # Make a URL of itself # Add a section # Add a subsection # Add a subsubsection # Add a question # Add an answer # Create the index # Print result ################################################################# section("General Questions") ################################################################# question("What is Wireshark?") answer(""" Wireshark&#174; is a network protocol analyzer. It lets you capture and interactively browse the traffic running on a computer network. It has a rich and powerful feature set and is world's most popular tool of its kind. It runs on most computing platforms including Windows, macOS, Linux, and UNIX. Network professionals, security experts, developers, and educators around the world use it regularly. It is freely available as open source, and is released under the GNU General Public License version 2. <br> It is developed and maintained by a global team of protocol experts, and it is an example of a <a href="https://en.wikipedia.org/wiki/Disruptive_technology">disruptive technology</a>. <br> Wireshark used to be known as Ethereal&#174;. See the next question for details about the name change. If you're still using Ethereal, it is strongly recommended that you upgrade to Wireshark as Ethereal is unsupported and has known security vulnerabilities. <br> For more information, please see the <a href="https://www.wireshark.org/about.html">About Wireshark</a> page. """) question("What's up with the name change? Is Wireshark a fork?") answer(""" In May of 2006, Gerald Combs (the original author of Ethereal) went to work for CACE Technologies (best known for WinPcap). Unfortunately, he had to leave the Ethereal trademarks behind. <br> This left the project in an awkward position. The only reasonable way to ensure the continued success of the project was to change the name. This is how Wireshark was born. <br> Wireshark is almost (but not quite) a fork. Normally a "fork" of an open source project results in two names, web sites, development teams, support infrastructures, etc. This is the case with Wireshark except for one notable exception -- every member of the core development team is now working on Wireshark. There has been no active development on Ethereal since the name change. Several parts of the Ethereal web site (such as the mailing lists, source code repository, and build farm) have gone offline. <br> More information on the name change can be found here: </p> <ul class="item_list"> <li><a href="http://www.prweb.com/releases/2006/6/prweb396098.htm">Original press release</a> <li><a href="http://archive09.linux.com/articles/54968">NewsForge article</a> <li>Many other articles in <a href="https://www.wireshark.org/bibliography.html">our bibliography</a> </ul> <p> """) question("Where can I get help?") answer(""" Community support is available on the <a href="https://ask.wireshark.org/">Q&amp;A site</a> and on the wireshark-users mailing list. Subscription information and archives for all of Wireshark's mailing lists can be found at %s. An IRC channel dedicated to Wireshark can be found at %s. <br> Self-paced and instructor-led training is available at <a href="http://www.wiresharktraining.com">Wireshark University</a>. Wireshark University also offers certification via the Wireshark Certified Network Analyst program. """ % (selflink("https://www.wireshark.org/mailman/listinfo"), selflink("irc://irc.freenode.net/wireshark") )) question("What kind of shark is Wireshark?") answer(""" <i>carcharodon photoshopia</i>. """) question("How is Wireshark pronounced, spelled and capitalized?") answer(""" Wireshark is pronounced as the word <i>wire</i> followed immediately by the word <i>shark</i>. Exact pronunciation and emphasis may vary depending on your locale (e.g. Arkansas). <br> It's spelled with a capital <i>W</i>, followed by a lower-case <i>ireshark</i>. It is not a CamelCase word, i.e., <i>WireShark</i> is incorrect. """) question("How much does Wireshark cost?", "but_thats_not_all") answer(""" Wireshark is "free software"; you can download it without paying any license fee. The version of Wireshark you download isn't a "demo" version, with limitations not present in a "full" version; it <em>is</em> the full version. <br> The license under which Wireshark is issued is <a href="https://www.gnu.org/licenses/gpl-2.0.html">the GNU General Public License version 2</a>. See <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html">the GNU GPL FAQ</a> for some more information. """) question("But I just paid someone on eBay for a copy of Wireshark! Did I get ripped off?") answer(""" That depends. Did they provide any sort of value-added product or service, such as installation support, installation media, training, trace file analysis, or funky-colored shark-themed socks? Probably not. <br> Wireshark is <a href="https://www.wireshark.org/download.html">available for anyone to download, absolutely free, at any time</a>. Paying for a copy implies that you should get something for your money. """) question("Can I use Wireshark commercially?") answer(""" Yes, if, for example, you mean "I work for a commercial organization; can I use Wireshark to capture and analyze network traffic in our company's networks or in our customer's networks?" <br> If you mean "Can I use Wireshark as part of my commercial product?", see <a href="#derived_work_gpl">the next entry in the FAQ</a>. """) question("Can I use Wireshark as part of my commercial product?", "derived_work_gpl") answer(""" As noted, Wireshark is licensed under <a href="https://www.gnu.org/licenses/gpl-2.0.html">the GNU General Public License, version 2</a>. The GPL imposes conditions on your use of GPL'ed code in your own products; you cannot, for example, make a "derived work" from Wireshark, by making modifications to it, and then sell the resulting derived work and not allow recipients to give away the resulting work. You must also make the changes you've made to the Wireshark source available to all recipients of your modified version; those changes must also be licensed under the terms of the GPL. See the <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html">GPL FAQ</a> for more details; in particular, note the answer to <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html#GPLCommercially">the question about modifying a GPLed program and selling it commercially</a>, and <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html#LinkingWithGPL">the question about linking GPLed code with other code to make a proprietary program</a>. <br> You can combine a GPLed program such as Wireshark and a commercial program as long as they communicate "at arm's length", as per <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html#GPLInProprietarySystem">this item in the GPL FAQ</a>. <br> We recommend keeping Wireshark and your product completely separate, communicating over sockets or pipes. If you're loading any part of Wireshark as a DLL, you're probably doing it wrong. """) question("What protocols are currently supported?") answer(""" There are currently hundreds of supported protocols and media. Details can be found in the <a href="https://www.wireshark.org/docs/man-pages/wireshark.html">wireshark(1)</a> man page. """) question("Are there any plans to support {your favorite protocol}?") answer(""" Support for particular protocols is added to Wireshark as a result of people contributing that support; no formal plans for adding support for particular protocols in particular future releases exist. """) question("""Can Wireshark read capture files from {your favorite network analyzer}?""") answer(""" Support for particular capture file formats is added to Wireshark as a result of people contributing that support; no formal plans for adding support for particular capture file formats in particular future releases exist. <br> If a network analyzer writes out files in a format already supported by Wireshark (e.g., in libpcap format), Wireshark may already be able to read them, unless the analyzer has added its own proprietary extensions to that format. <br> If a network analyzer writes out files in its own format, or has added proprietary extensions to another format, in order to make Wireshark read captures from that network analyzer, we would either have to have a specification for the file format, or the extensions, sufficient to give us enough information to read the parts of the file relevant to Wireshark, or would need at least one capture file in that format <strong>AND</strong> a detailed textual analysis of the packets in that capture file (showing packet time stamps, packet lengths, and the top-level packet header) in order to reverse-engineer the file format. <br> Note that there is no guarantee that we will be able to reverse-engineer a capture file format. """) question("What devices can Wireshark use to capture packets?") answer(""" Wireshark can read live data from Ethernet, Token-Ring, FDDI, serial (PPP and SLIP) (if the OS on which it's running allows Wireshark to do so), 802.11 wireless LAN (if the OS on which it's running allows Wireshark to do so), ATM connections (if the OS on which it's running allows Wireshark to do so), and the "any" device supported on Linux by recent versions of libpcap. <br> See <a href="https://wiki.wireshark.org/CaptureSetup/NetworkMedia">the list of supported capture media on various OSes</a> for details (several items in there say "Unknown", which doesn't mean "Wireshark can't capture on them", it means "we don't know whether it can capture on them"; we expect that it will be able to capture on many of them, but we haven't tried it ourselves - if you try one of those types and it works, please update the wiki page accordingly. <br> It can also read a variety of capture file formats, including: </p> <ul> <li> AG Group/WildPackets/Savvius EtherPeek/TokenPeek/AiroPeek/EtherHelp/Packet Grabber captures <li> AIX's iptrace captures <li> Accellent's 5Views LAN agent output <li> Cinco Networks NetXRay captures <li> Cisco Secure Intrusion Detection System IPLog output <li> CoSine L2 debug output <li> DBS Etherwatch VMS text output <li> Endace Measurement Systems' ERF format captures <li> EyeSDN USB S0 traces <li> HP-UX nettl captures <li> ISDN4BSD project i4btrace captures <li> Linux Bluez Bluetooth stack hcidump -w traces <li> Lucent/Ascend router debug output <li> Microsoft Network Monitor captures <li> Network Associates Windows-based Sniffer captures <li> Network General/Network Associates DOS-based Sniffer (compressed or uncompressed) captures <li> Network Instruments Observer version 9 captures <li> Novell LANalyzer captures <li> RADCOM's WAN/LAN analyzer captures <li> Shomiti/Finisar Surveyor captures <li> Toshiba's ISDN routers dump output <li> VMS TCPIPtrace/TCPtrace/UCX$TRACE output <li> Visual Networks' Visual UpTime traffic capture <li> libpcap, tcpdump and various other tools using tcpdump's capture format <li> snoop and atmsnoop output </ul> <p> so that it can read traces from various network types, as captured by other applications or equipment, even if it cannot itself capture on those network types. """) question(""" Does Wireshark work on Windows Vista or Windows Server 2008? """) answer(""" Yes, but if you want to capture packets as a normal user, you must make sure npf.sys is loaded. Wireshark's installer enables this by default. This is not a concern if you run Wireshark as Administrator, but this is discouraged. See the <a href="https://wiki.wireshark.org/CaptureSetup/CapturePrivileges#windows">CapturePrivileges</a> page on the wiki for more details. """) ################################################################# section("Installing Wireshark") ################################################################# question("""I installed the Wireshark RPM (or other package); why did it install TShark but not Wireshark?""") answer(""" Many distributions have separate Wireshark packages, one for non-GUI components such as TShark, editcap, dumpcap, etc. and one for the GUI. If this is the case on your system, there's probably a separate package named <code>wireshark-qt</code>. Find it and install it. """) ################################################################# section("Building Wireshark") ################################################################# question("""I have libpcap installed; why did the configure script not find pcap.h or bpf.h?""") answer(""" Are you sure pcap.h and bpf.h are installed? The official distribution of libpcap only installs the libpcap.a library file when "make install" is run. To install pcap.h and bpf.h, you must run "make install-incl". If you're running Debian or Redhat, make sure you have the "libpcap-dev" or "libpcap-devel" packages installed. <br> It's also possible that pcap.h and bpf.h have been installed in a strange location. If this is the case, you may have to tweak aclocal.m4. """) ################################################################# section("Starting Wireshark") ################################################################# question("""When I try to run Wireshark, why does it complain about <code>sprint_realloc_objid</code> being undefined?""") answer(""" Wireshark can only be linked with version 4.2.2 or later of UCD SNMP. Your version of Wireshark was dynamically linked with such a version of UCD SNMP; however, you have an older version of UCD SNMP installed, which means that when Wireshark is run, it tries to link to the older version, and fails. You will have to replace that version of UCD SNMP with version 4.2.2 or a later version. """) question(""" I've installed Wireshark from Fink on macOS; why is it very slow to start up? """) answer(""" When an application is installed on macOS, prior to 10.4, it is usually "prebound" to speed up launching the application. (That's what the "Optimizing" phase of installation is.) <br> Fink normally performs prebinding automatically when you install a package. However, in some rare cases, for whatever reason the prebinding caches get corrupt, and then not only does prebinding fail, but startup actually becomes much slower, because the system tries in vain to perform prebinding "on the fly" as you launch the application. This fails, causing sometimes huge delays. <br> To fix the prebinding caches, run the command </p> <pre> sudo /sw/var/lib/fink/prebound/update-package-prebinding.pl -f </pre> <p> """) ################################################################# section("Crashes and other fatal errors") ################################################################# question(""" I have an XXX network card on my machine; if I try to capture on it, why does my machine crash or reset itself? """) answer(""" This is almost certainly a problem with one or more of: </p> <ul> <li>the operating system you're using; <li>the device driver for the interface you're using; <li>the libpcap/Npcap library and, if this is Windows, the Npcap device driver; </ul> <p> so: </p> <ul> <li>if you are using Windows, see <a href="https://nmap.org/npcap/">the Npcap support page</a> - check the "Patches, Bug Reports, Questions, Suggestions, etc" section; <li>if you are using some Linux distribution, some version of BSD, or some other UNIX-flavored OS, you should report the problem to the company or organization that produces the OS (in the case of a Linux distribution, report the problem to whoever produces the distribution). </ul> <p> """) question(""" Why does my machine crash or reset itself when I select "Start" from the "Capture" menu or select "Preferences" from the "Edit" menu? """) answer(""" Both of those operations cause Wireshark to try to build a list of the interfaces that it can open; it does so by getting a list of interfaces and trying to open them. There is probably an OS, driver, or, for Windows, Npcap bug that causes the system to crash when this happens; see the previous question. """) ################################################################# section("Capturing packets") ################################################################# question("""When I use Wireshark to capture packets, why do I see only packets to and from my machine, or not see all the traffic I'm expecting to see from or to the machine I'm trying to monitor?""", "promiscsniff") answer(""" This might be because the interface on which you're capturing is plugged into an Ethernet or Token Ring switch; on a switched network, unicast traffic between two ports will not necessarily appear on other ports - only broadcast and multicast traffic will be sent to all ports. <br> Note that even if your machine is plugged into a hub, the "hub" may be a switched hub, in which case you're still on a switched network. <br> Note also that on the Linksys Web site, they say that their auto-sensing hubs "broadcast the 10Mb packets to the port that operate at 10Mb only and broadcast the 100Mb packets to the ports that operate at 100Mb only", which would indicate that if you sniff on a 10Mb port, you will not see traffic coming sent to a 100Mb port, and <i>vice versa</i>. This problem has also been reported for Netgear dual-speed hubs, and may exist for other "auto-sensing" or "dual-speed" hubs. <br> Some switches have the ability to replicate all traffic on all ports to a single port so that you can plug your analyzer into that single port to sniff all traffic. You would have to check the documentation for the switch to see if this is possible and, if so, to see how to do this. See <a href="https://wiki.wireshark.org/SwitchReference">the switch reference page</a> on <a href="https://wiki.wireshark.org/">the Wireshark Wiki</a> for information on some switches. (Note that it's a Wiki, so you can update or fix that information, or add additional information on those switches or information on new switches, yourself.) <br> Note also that many firewall/NAT boxes have a switch built into them; this includes many of the "cable/DSL router" boxes. If you have a box of that sort, that has a switch with some number of Ethernet ports into which you plug machines on your network, and another Ethernet port used to connect to a cable or DSL modem, you can, at least, sniff traffic between the machines on your network and the Internet by plugging the Ethernet port on the router going to the modem, the Ethernet port on the modem, and the machine on which you're running Wireshark into a hub (make sure it's not a switching hub, and that, if it's a dual-speed hub, all three of those ports are running at the same speed. <br> If your machine is <em>not</em> plugged into a switched network or a dual-speed hub, or it is plugged into a switched network but the port is set up to have all traffic replicated to it, the problem might be that the network interface on which you're capturing doesn't support "promiscuous" mode, or because your OS can't put the interface into promiscuous mode. Normally, network interfaces supply to the host only: </p> <ul> <li>packets sent to one of that host's link-layer addresses; <li>broadcast packets; <li>multicast packets sent to a multicast address that the host has configured the interface to accept. </ul> <p> Most network interfaces can also be put in "promiscuous" mode, in which they supply to the host all network packets they see. Wireshark will try to put the interface on which it's capturing into promiscuous mode unless the "Capture packets in promiscuous mode" option is turned off in the "Capture Options" dialog box, and TShark will try to put the interface on which it's capturing into promiscuous mode unless the <code>-p</code> option was specified. However, some network interfaces don't support promiscuous mode, and some OSes might not allow interfaces to be put into promiscuous mode. <br> If the interface is not running in promiscuous mode, it won't see any traffic that isn't intended to be seen by your machine. It <strong>will</strong> see broadcast packets, and multicast packets sent to a multicast MAC address the interface is set up to receive. <br> You should ask the vendor of your network interface whether it supports promiscuous mode. If it does, you should ask whoever supplied the driver for the interface (the vendor, or the supplier of the OS you're running on your machine) whether it supports promiscuous mode with that network interface. <br> In the case of token ring interfaces, the drivers for some of them, on Windows, may require you to enable promiscuous mode in order to capture in promiscuous mode. See <a href="https://wiki.wireshark.org/CaptureSetup/TokenRing">the Wireshark Wiki item on Token Ring capturing</a> for details. <br> In the case of wireless LAN interfaces, it appears that, when those interfaces are promiscuously sniffing, they're running in a significantly different mode from the mode that they run in when they're just acting as network interfaces (to the extent that it would be a significant effort for those drivers to support for promiscuously sniffing <em>and</em> acting as regular network interfaces at the same time), so it may be that Windows drivers for those interfaces don't support promiscuous mode. """) question("""When I capture with Wireshark, why can't I see any TCP packets other than packets to and from my machine, even though another analyzer on the network sees those packets?""") answer(""" You're probably not seeing <em>any</em> packets other than unicast packets to or from your machine, and broadcast and multicast packets; a switch will normally send to a port only unicast traffic sent to the MAC address for the interface on that port, and broadcast and multicast traffic - it won't send to that port unicast traffic sent to a MAC address for some other interface - and a network interface not in promiscuous mode will receive only unicast traffic sent to the MAC address for that interface, broadcast traffic, and multicast traffic sent to a multicast MAC address the interface is set up to receive. <br> TCP doesn't use broadcast or multicast, so you will only see your own TCP traffic, but UDP services may use broadcast or multicast so you'll see some UDP traffic - however, this is not a problem with TCP traffic, it's a problem with unicast traffic, as you also won't see all UDP traffic between other machines. <br> I.e., this is probably <a href="#promiscsniff">the same question as this earlier one</a>; see the response to that question. """) question("""Why am I only seeing ARP packets when I try to capture traffic?""") answer(""" You're probably on a switched network, and running Wireshark on a machine that's not sending traffic to the switch and not being sent any traffic from other machines on the switch. ARP packets are often broadcast packets, which are sent to all switch ports. <br> I.e., this is probably <a href="#promiscsniff">the same question as this earlier one</a>; see the response to that question. """) question(""" Why am I not seeing any traffic when I try to capture traffic?""") answer(""" Is the machine running Wireshark sending out any traffic on the network interface on which you're capturing, or receiving any traffic on that network, or is there any broadcast traffic on the network or multicast traffic to a multicast group to which the machine running Wireshark belongs? <br> If not, this may just be a problem with promiscuous sniffing, either due to running on a switched network or a dual-speed hub, or due to problems with the interface not supporting promiscuous mode; see the response to <a href="#promiscsniff">this earlier question</a>. <br> Otherwise, on Windows, see the response to <a href="#capprobwin">this question</a> and, on a UNIX-flavored OS, see the response to <a href="#capprobunix">this question</a>. """) question(""" Can Wireshark capture on (my T1/E1 line, SS7 links, etc.)? """) answer(""" Wireshark can only capture on devices supported by libpcap/Npcap. On most OSes, only devices that can act as network interfaces of the type that support IP are supported as capture devices for libpcap/Npcap, although the device doesn't necessarily have to be running as an IP interface in order to support traffic capture. <br> On Linux and FreeBSD, libpcap 0.8 and later support the API for <a href="http://www.endace.com/products.htm">Endace Measurement Systems' DAG cards</a>, so that a system with one of those cards, and its driver and libraries, installed can capture traffic with those cards with libpcap-based applications. You would either have to have a version of Wireshark built with that version of libpcap, or a dynamically-linked version of Wireshark and a shared libpcap library with DAG support, in order to do so with Wireshark. You should ask Endace whether that could be used to capture traffic on, for example, your T1/E1 link. <br> See <a href="https://wiki.wireshark.org/CaptureSetup/SS7">the SS7 capture setup page</a> on <a href="https://wiki.wireshark.org/">the Wireshark Wiki</a> for current information on capturing SS7 traffic on TDM links. """) question("""How do I put an interface into promiscuous mode?""") answer(""" By not disabling promiscuous mode when running Wireshark or TShark. <br> Note, however, that: </p> <ul> <li>the form of promiscuous mode that libpcap (the library that programs such as tcpdump, Wireshark, etc. use to do packet capture) turns on will <strong>not</strong> necessarily be shown if you run <code>ifconfig</code> on the interface on a UNIX system; <li>some network interfaces might not support promiscuous mode, and some drivers might not allow promiscuous mode to be turned on - see <a href="#promiscsniff">this earlier question</a> for more information on that; <li>the fact that you're not seeing any traffic, or are only seeing broadcast traffic, or aren't seeing any non-broadcast traffic other than traffic to or from the machine running Wireshark, does not mean that promiscuous mode isn't on - see <a href="#promiscsniff">this earlier question</a> for more information on that. </ul> <p> I.e., this is probably <a href="#promiscsniff">the same question as this earlier one</a>; see the response to that question. """) question(""" I can set a display filter just fine; why don't capture filters work? """) answer(""" Capture filters currently use a different syntax than display filters. Here's the corresponding section from the <a href="https://www.wireshark.org/docs/man-pages/wireshark.html">wireshark(1)</a> man page: <br> "Display filters in Wireshark are very powerful; more fields are filterable in Wireshark than in other protocol analyzers, and the syntax you can use to create your filters is richer. As Wireshark progresses, expect more and more protocol fields to be allowed in display filters. <br> Packet capturing is performed with the pcap library. The capture filter syntax follows the rules of the pcap library. This syntax is different from the display filter syntax." <br> The capture filter syntax used by libpcap can be found in the <a href="http://www.tcpdump.org/tcpdump_man.html">tcpdump(8)</a> man page. """) question(""" How can I capture packets with CRC errors? """) answer(""" Wireshark can capture only the packets that the packet capture library - libpcap on UNIX-flavored OSes, and the Npcap port to Windows of libpcap on Windows - can capture, and libpcap/Npcap can capture only the packets that the OS's raw packet capture mechanism (or the Npcap driver, and the underlying OS networking code and network interface drivers, on Windows) will allow it to capture. <br> Unless the OS always supplies packets with errors such as invalid CRCs to the raw packet capture mechanism, or can be configured to do so, invalid CRCs to the raw packet capture mechanism, Wireshark - and other programs that capture raw packets, such as tcpdump - cannot capture those packets. You will have to determine whether your OS needs to be so configured and, if so, can be so configured, configure it if necessary and possible, and make whatever changes to libpcap and the packet capture program you're using are necessary, if any, to support capturing those packets. <br> Most OSes probably do <strong>not</strong> support capturing packets with invalid CRCs on Ethernet, and probably do not support it on most other link-layer types. Some drivers on some OSes do support it, such as some Ethernet drivers on FreeBSD; in those OSes, you might always get those packets, or you might only get them if you capture in promiscuous mode (you'd have to determine which is the case). <br> Note that libpcap does not currently supply to programs that use it an indication of whether the packet's CRC was invalid (because the drivers themselves do not supply that information to the raw packet capture mechanism); therefore, Wireshark will not indicate which packets had CRC errors unless the FCS was captured (see the next question) and you're using Wireshark 0.9.15 and later, in which case Wireshark will check the CRC and indicate whether it's correct or not. """) question(""" How can I capture entire frames, including the FCS? """) answer(""" Wireshark can only capture data that the packet capture library - libpcap on UNIX-flavored OSes, and the Npcap port to Windows of libpcap on Windows - can capture, and libpcap/Npcap can capture only the data that the OS's raw packet capture mechanism (or the Npcap driver, and the underlying OS networking code and network interface drivers, on Windows) will allow it to capture. <br> For any particular link-layer network type, unless the OS supplies the FCS of a frame as part of the frame, or can be configured to do so, Wireshark - and other programs that capture raw packets, such as tcpdump - cannot capture the FCS of a frame. You will have to determine whether your OS needs to be so configured and, if so, can be so configured, configure it if necessary and possible, and make whatever changes to libpcap and the packet capture program you're using are necessary, if any, to support capturing the FCS of a frame. <br> Most OSes do <strong>not</strong> support capturing the FCS of a frame on Ethernet, and probably do not support it on most other link-layer types. Some drivres on some OSes do support it, such as some (all?) Ethernet drivers on NetBSD and possibly the driver for Apple's gigabit Ethernet interface in macOS; in those OSes, you might always get the FCS, or you might only get the FCS if you capture in promiscuous mode (you'd have to determine which is the case). <br> Versions of Wireshark prior to 0.9.15 will not treat an Ethernet FCS in a captured packet as an FCS. 0.9.15 and later will attempt to determine whether there's an FCS at the end of the frame and, if it thinks there is, will display it as such, and will check whether it's the correct CRC-32 value or not. """) question(""" I'm capturing packets on a machine on a VLAN; why don't the packets I'm capturing have VLAN tags? """) answer(""" You might be capturing on what might be called a "VLAN interface" - the way a particular OS makes VLANs plug into the networking stack might, for example, be to have a network device object for the physical interface, which takes VLAN packets, strips off the VLAN header and constructs an Ethernet header, and passes that packet to an internal network device object for the VLAN, which then passes the packets onto various higher-level protocol implementations. <br> In order to see the raw Ethernet packets, rather than "de-VLANized" packets, you would have to capture not on the virtual interface for the VLAN, but on the interface corresponding to the physical network device, if possible. See <a href="https://wiki.wireshark.org/CaptureSetup/VLAN">the Wireshark Wiki item on VLAN capturing</a> for details. """) question(""" Why does Wireshark hang after I stop a capture? """) answer(""" The most likely reason for this is that Wireshark is trying to look up an IP address in the capture to convert it to a name (so that, for example, it can display the name in the source address or destination address columns), and that lookup process is taking a very long time. <br> Wireshark calls a routine in the OS of the machine on which it's running to convert of IP addresses to the corresponding names. That routine probably does one or more of: </p> <ul><li>a search of a system file listing IP addresses and names; <li>a lookup using DNS; <li>on UNIX systems, a lookup using NIS; <li>on Windows systems, a NetBIOS-over-TCP query. </ul> <p> If a DNS server that's used in an address lookup is not responding, the lookup will fail, but will only fail after a timeout while the system routine waits for a reply. <br> In addition, on Windows systems, if the DNS lookup of the address fails, either because the server isn't responding or because there are no records in the DNS that could be used to map the address to a name, a NetBIOS-over-TCP query will be made. That query involves sending a message to the NetBIOS-over-TCP name service on that machine, asking for the name and other information about the machine. If the machine isn't running software that responds to those queries - for example, many non-Windows machines wouldn't be running that software - the lookup will only fail after a timeout. Those timeouts can cause the lookup to take a long time. <br> If you disable network address-to-name translation - for example, by turning off the "Enable network name resolution" option in the "Capture Options" dialog box for starting a network capture - the lookups of the address won't be done, which may speed up the process of reading the capture file after the capture is stopped. You can make that setting the default by selecting "Preferences" from the "Edit" menu, turning off the "Enable network name resolution" option in the "Name resolution" options in the preferences disalog box, and using the "Save" button in that dialog box; note that this will save <em>all</em> your current preference settings. <br> If Wireshark hangs when reading a capture even with network name resolution turned off, there might, for example, be a bug in one of Wireshark's dissectors for a protocol causing it to loop infinitely. If you're not running the most recent release of Wireshark, you should first upgrade to that release, as, if there's a bug of that sort, it might've been fixed in a release after the one you're running. If the hang occurs in the most recent release of Wireshark, the bug should be reported to <a href="mailto:wireshark-dev@wireshark.org">the Wireshark developers' mailing list</a> at <code>wireshark-dev@wireshark.org</code>. <br> On UNIX-flavored OSes, please try to force Wireshark to dump core, by sending it a <code>SIGABRT</code> signal (usually signal 6) with the <code>kill</code> command, and then get a stack trace if you have a debugger installed. A stack trace can be obtained by using your debugger (<code>gdb</code> in this example), the Wireshark binary, and the resulting core file. Here's an example of how to use the gdb command <code>backtrace</code> to do so. </p> <pre> $ gdb wireshark core (gdb) backtrace ..... prints the stack trace (gdb) quit $ </pre> <p> The core dump file may be named "wireshark.core" rather than "core" on some platforms (e.g., BSD systems). <br> Also, if at all possible, please send a copy of the capture file that caused the problem. When capturing packets, Wireshark normally writes captured packets to a temporary file, which will probably be in <code>/tmp</code> or <code>/var/tmp</code> on UNIX-flavored OSes, <code>\\TEMP</code> on the main system disk (normally <code>\\Documents and Settings\\</code><var>your login name</var> <code>\\Local Settings\\Temp</code> on the main system disk on Windows Windows XP and Server 2003, and <code>\\Users\\<var>your login name</var>\\AppData\\Local\\Temp</code> on the main system disk on Windows Vista and later, so the capture file will probably be there. If you are capturing on a single interface, it will have a name of the form, <code>wireshark_&lt;iface&gt;_YYYYmmddHHMMSS_XXXXXX.&lt;fmt&gt;</code>, where &lt;fmt&gt; is the capture file format (pcap or pcapng), and &lt;iface&gt; is the actual name of the interface you are capturing on; otherwise, if you are capturing on multiple interfaces, it will have a name of the form, <code>wireshark_&lt;N&gt;_interfaces_YYYYmmddHHMMSS_XXXXXX.&lt;fmt&gt;</code>, where &lt;N&gt; is the number of simultaneous interfaces you are capturing on. Please don't send a trace file greater than 1 MB when compressed; instead, make it available via FTP or HTTP, or say it's available but leave it up to a developer to ask for it. If the trace file contains sensitive information (e.g., passwords), then please do not send it. """) ################################################################# section("Capturing packets on Windows") ################################################################# question(""" I'm running Wireshark on Windows; why does some network interface on my machine not show up in the list of interfaces in the "Interface:" field in the dialog box popped up by "Capture->Start", and/or why does Wireshark give me an error if I try to capture on that interface? """, "capprobwin") answer(""" Wireshark relies on the Npcap library, on the Npcap device driver, and and on the facilities that come with the OS on which it's running in order to do captures. <br> Therefore, if the OS, the Npcap library, or the Npcap driver don't support capturing on a particular network interface device, Wireshark won't be able to capture on that device. <br> If an interface doesn't show up in the list of interfaces in the "Interface:" field, and you know the name of the interface, try entering that name in the "Interface:" field and capturing on that device. <br> If the attempt to capture on it succeeds, the interface is somehow not being reported by the mechanism Wireshark uses to get a list of interfaces. Try listing the interfaces with WinDump; see <a href="https://www.windump.org/">the WinDump Web site</a> for information on using WinDump. <br> You would run WinDump with the <code>-D</code> flag; if it lists the interface, please report this to <a href="mailto:wireshark-dev@wireshark.org">wireshark-dev@wireshark.org</a> giving full details of the problem, including </p> <ul> <li>the operating system you're using, and the version of that operating system; <li>the type of network device you're using; <li>the output of WinDump. </ul> <p> If WinDump does <em>not</em> list the interface, this is almost certainly a problem with one or more of: </p> <ul> <li>the operating system you're using; <li>the device driver for the interface you're using; <li>the WinPcap library and/or the WinPcap device driver; </ul> <p> so first check <a href="https://nmap.org/npcap/guide/">the Npcap User's Guide</a> to see if your problem is mentioned there. If not, then see <a href="https://nmap.org/npcap/">the main Npcap page</a> - check the "Patches, Bug Reports, Questions, Suggestions, etc" section. <br> If you are having trouble capturing on a particular network interface, first try capturing on that device with WinDump; see <a href="https://www.windump.org/">the WinDump Web site</a> for information on using WinDump. <br> If you can capture on the interface with WinDump, send mail to <a href="mailto:wireshark-users@wireshark.org">wireshark-users@wireshark.org</a> giving full details of the problem, including </p> <ul> <li>the operating system you're using, and the version of that operating system; <li>the type of network device you're using; <li>the error message you get from Wireshark. </ul> <p> If you <em>cannot</em> capture on the interface with WinDump, this is almost certainly a problem with one or more of: </p> <ul> <li>the operating system you're using; <li>the device driver for the interface you're using; <li>the Npcap library and/or the Npcap device driver; </ul> <p> so first check <a href="https://nmap.org/npcap/guide/">the Npcap User's Guide</a> to see if your problem is mentioned there. If not, then see <a href="https://nmap.org/npcap/">the main Npcap page</a> - check the "Patches, Bug Reports, Questions, Suggestions, etc" section. <br> You may also want to ask the <a href="mailto:wireshark-users@wireshark.org">wireshark-users@wireshark.org</a> and the <a href="mailto:winpcap-users@winpcap.org">winpcap-users@winpcap.org</a> mailing lists to see if anybody happens to know about the problem and know a workaround or fix for the problem. (Note that you will have to subscribe to that list in order to be allowed to mail to it; see <a href="https://nmap.org/npcap/">the Npcap support page</a> for information on the mailing list.) In your mail, please give full details of the problem, as described above, and also indicate that the problem occurs with WinDump, not just with Wireshark. """) question(""" I'm running Wireshark on Windows; why do no network interfaces show up in the list of interfaces in the "Interface:" field in the dialog box popped up by "Capture->Start"? """) answer(""" This is really <a href="#capprobwin">the same question as a previous one</a>; see the response to that question. """) question(""" I'm running Wireshark on Windows; why am I not seeing any traffic being sent by the machine running Wireshark?""") answer(""" If you are running some form of VPN client software, it might be causing this problem; people have seen this problem when they have Check Point's VPN software installed on their machine. If that's the cause of the problem, you will have to remove the VPN software in order to have Wireshark (or any other application using Npcap) see outgoing packets; unfortunately, neither we nor the Npcap developers know any way to make Npcap and the VPN software work well together. <br> Also, some drivers for Windows (especially some wireless network interface drivers) apparently do not, when running in promiscuous mode, arrange that outgoing packets are delivered to the software that requested that the interface run promiscuously; try turning promiscuous mode off. """) question(""" When I capture on Windows in promiscuous mode, I can see packets other than those sent to or from my machine; however, those packets show up with a "Short Frame" indication, unlike packets to or from my machine. What should I do to arrange that I see those packets in their entirety? """) answer(""" In at least some cases, this appears to be the result of PGPnet running on the network interface on which you're capturing; turn it off on that interface. """) question(""" I'm trying to capture 802.11 traffic on Windows; why am I not seeing any packets? """, "win802_11promisc") answer(""" At least some 802.11 card drivers on Windows appear not to see any packets if they're running in promiscuous mode. Try turning promiscuous mode off; you'll only be able to see packets sent by and received by your machine, not third-party traffic, and it'll look like Ethernet traffic and won't include any management or control frames, but that's a limitation of the card drivers. <br> See the archived <a href="https://web.archive.org/web/20090226193157/http://www.micro-logix.com/winpcap/Supported.asp">MicroLogix's list of cards supported with WinPcap</a> for information on support of various adapters and drivers with WinPcap. """) question(""" I'm trying to capture 802.11 traffic on Windows; why am I seeing packets received by the machine on which I'm capturing traffic, but not packets sent by that machine? """) answer(""" This appears to be another problem with promiscuous mode; try turning it off. """) question(""" I'm trying to capture Ethernet VLAN traffic on Windows, and I'm capturing on a "raw" Ethernet device rather than a "VLAN interface", so that I can see the VLAN headers; why am I seeing packets received by the machine on which I'm capturing traffic, but not packets sent by that machine? """) answer(""" The way the Windows networking code works probably means that packets are sent on a "VLAN interface" rather than the "raw" device, so packets sent by the machine will only be seen when you capture on the "VLAN interface". If so, you will be unable to see outgoing packets when capturing on the "raw" device, so you are stuck with a choice between seeing VLAN headers and seeing outgoing packets. """) ################################################################# section("Capturing packets on UN*Xes") ################################################################# question(""" I'm running Wireshark on a UNIX-flavored OS; why does some network interface on my machine not show up in the list of interfaces in the "Interface:" field in the dialog box popped up by "Capture->Start", and/or why does Wireshark give me an error if I try to capture on that interface? """, "capprobunix") answer(""" You may need to run Wireshark from an account with sufficient privileges to capture packets, such as the super-user account, or may need to give your account sufficient privileges to capture packets. Only those interfaces that Wireshark can open for capturing show up in that list; if you don't have sufficient privileges to capture on any interfaces, no interfaces will show up in the list. See <a href="https://wiki.wireshark.org/CaptureSetup/CapturePrivileges">the Wireshark Wiki item on capture privileges</a> for details on how to give a particular account or account group capture privileges on platforms where that can be done. <br> If you are running Wireshark from an account with sufficient privileges, then note that Wireshark relies on the libpcap library, and on the facilities that come with the OS on which it's running in order to do captures. On some OSes, those facilities aren't present by default; see <a href="https://wiki.wireshark.org/CaptureSetup/CaptureSupport">the Wireshark Wiki item on adding capture support</a> for details. <br> And, even if you're running with an account that has sufficient privileges to capture, and capture support is present in your OS, if the OS or the libpcap library don't support capturing on a particular network interface device or particular types of devices, Wireshark won't be able to capture on that device. <br> On Solaris, note that libpcap 0.6.2 and earlier didn't support Token Ring interfaces; the current version, 0.7.2, does support Token Ring, and the current version of Wireshark works with libpcap 0.7.2 and later. <br> If an interface doesn't show up in the list of interfaces in the "Interface:" field, and you know the name of the interface, try entering that name in the "Interface:" field and capturing on that device. <br> If the attempt to capture on it succeeds, the interface is somehow not being reported by the mechanism Wireshark uses to get a list of interfaces; please report this to <a href="mailto:wireshark-dev@wireshark.org">wireshark-dev@wireshark.org</a> giving full details of the problem, including </p> <ul> <li>the operating system you're using, and the version of that operating system (for Linux, give both the version number of the kernel and the name and version number of the distribution you're using); <li>the type of network device you're using. </ul> <p> If you are having trouble capturing on a particular network interface, and you've made sure that (on platforms that require it) you've arranged that packet capture support is present, as per the above, first try capturing on that device with <code>tcpdump</code>. <br> If you can capture on the interface with <code>tcpdump</code>, send mail to <a href="mailto:wireshark-users@wireshark.org">wireshark-users@wireshark.org</a> giving full details of the problem, including </p> <ul> <li>the operating system you're using, and the version of that operating system (for Linux, give both the version number of the kernel and the name and version number of the distribution you're using); <li>the type of network device you're using; <li>the error message you get from Wireshark. </ul> <p> If you <em>cannot</em> capture on the interface with <code>tcpdump</code>, this is almost certainly a problem with one or more of: </p> <ul> <li>the operating system you're using; <li>the device driver for the interface you're using; <li>the libpcap library; </ul> <p> so you should report the problem to the company or organization that produces the OS (in the case of a Linux distribution, report the problem to whoever produces the distribution). <br> You may also want to ask the <a href="mailto:wireshark-users@wireshark.org">wireshark-users@wireshark.org</a> and the <a href="mailto:tcpdump-workers@lists.tcpdump.org">tcpdump-workers@lists.tcpdump.org</a> mailing lists to see if anybody happens to know about the problem and know a workaround or fix for the problem. In your mail, please give full details of the problem, as described above, and also indicate that the problem occurs with <code>tcpdump</code> not just with Wireshark. """) question(""" I'm running Wireshark on a UNIX-flavored OS; why do no network interfaces show up in the list of interfaces in the "Interface:" field in the dialog box popped up by "Capture->Start"? """) answer(""" This is really <a href="#capprobunix">the same question as the previous one</a>; see the response to that question. """) question("""I'm capturing packets on Linux; why do the time stamps have only 100ms resolution, rather than 1us resolution?""") answer(""" Wireshark gets time stamps from libpcap/Npcap, and libpcap/Npcap get them from the OS kernel, so Wireshark - and any other program using libpcap, such as tcpdump - is at the mercy of the time stamping code in the OS for time stamps. <br> At least on x86-based machines, Linux can get high-resolution time stamps on newer processors with the Time Stamp Counter (TSC) register; for example, Intel x86 processors, starting with the Pentium Pro, and including all x86 processors since then, have had a TSC, and other vendors probably added the TSC at some point to their families of x86 processors. The Linux kernel must be configured with the CONFIG_X86_TSC option enabled in order to use the TSC. Make sure this option is enabled in your kernel. <br> In addition, some Linux distributions may have bugs in their versions of the kernel that cause packets not to be given high-resolution time stamps even if the TSC is enabled. See, for example, bug 61111 for Red Hat Linux 7.2. If your distribution has a bug such as this, you may have to run a standard kernel from kernel.org in order to get high-resolution time stamps. """) ################################################################# section("Capturing packets on wireless LANs") ################################################################# question(""" How can I capture raw 802.11 frames, including non-data (management, beacon) frames? """, "raw_80211_sniff") answer(""" That depends on the operating system on which you're running, and on the 802.11 interface on which you're capturing. <br> This would probably require that you capture in promiscuous mode or in the mode called "monitor mode" or "RFMON mode". On some platforms, or with some cards, this might require that you capture in monitor mode - promiscuous mode might not be sufficient. If you want to capture traffic on networks other than the one with which you're associated, you will have to capture in monitor mode. <br> Not all operating systems support capturing non-data packets and, even on operating systems that do support it, not all drivers, and thus not all interfaces, support it. Even on those that do, monitor mode might not be supported by the operating system or by the drivers for all interfaces. <br> <strong>NOTE:</strong> an interface running in monitor mode will, on most if not all platforms, not be able to act as a regular network interface; putting it into monitor mode will, in effect, take your machine off of whatever network it's on as long as the interface is in monitor mode, allowing it only to passively capture packets. <br> This means that you should disable name resolution when capturing in monitor mode; otherwise, when Wireshark (or TShark, or tcpdump) tries to display IP addresses as host names, it will probably block for a long time trying to resolve the name because it will not be able to communicate with any DNS or NIS servers. <br> See <a href="https://wiki.wireshark.org/CaptureSetup/WLAN">the Wireshark Wiki item on 802.11 capturing</a> for details. """) question(""" How do I capture on an 802.11 device in monitor mode?""", "monitor") answer(""" Whether you will be able to capture in monitor mode depends on the operating system, adapter, and driver you're using. See <a href="#raw_80211_sniff">the previous question</a> for information on monitor mode, including a link to the Wireshark Wiki page that gives details on 802.11 capturing. """) ################################################################# section("Viewing traffic") ################################################################# question("Why am I seeing lots of packets with incorrect TCP checksums?") answer(""" If the packets that have incorrect TCP checksums are all being sent by the machine on which Wireshark is running, this is probably because the network interface on which you're capturing does TCP checksum offloading. That means that the TCP checksum is added to the packet by the network interface, not by the OS's TCP/IP stack; when capturing on an interface, packets being sent by the host on which you're capturing are directly handed to the capture interface by the OS, which means that they are handed to the capture interface without a TCP checksum being added to them. <br> The only way to prevent this from happening would be to disable TCP checksum offloading, but </p> <ol> <li>that might not even be possible on some OSes; <li>that could reduce networking performance significantly. </ol> <p> However, you can disable the check that Wireshark does of the TCP checksum, so that it won't report any packets as having TCP checksum errors, and so that it won't refuse to do TCP reassembly due to a packet having an incorrect TCP checksum. That can be set as an Wireshark preference by selecting "Preferences" from the "Edit" menu, opening up the "Protocols" list in the left-hand pane of the "Preferences" dialog box, selecting "TCP", from that list, turning off the "Check the validity of the TCP checksum when possible" option, clicking "Save" if you want to save that setting in your preference file, and clicking "OK". <br> It can also be set on the Wireshark or TShark command line with a <code>-o tcp.check_checksum:false</code> command-line flag, or manually set in your preferences file by adding a <code>tcp.check_checksum:false</code> line. """) question(""" I've just installed Wireshark, and the traffic on my local LAN is boring. Where can I find more interesting captures? """) answer(""" We have a collection of strange and exotic sample capture files at %s""" % (selflink("https://wiki.wireshark.org/SampleCaptures"))) question(""" Why doesn't Wireshark correctly identify RTP packets? It shows them only as UDP.""") answer(""" Wireshark can identify a UDP datagram as containing a packet of a particular protocol running atop UDP only if </p> <ol> <li> The protocol in question has a particular standard port number, and the UDP source or destination port number is that port <li> Packets of that protocol can be identified by looking for a "signature" of some type in the packet - i.e., some data that, if Wireshark finds it in some particular part of a packet, means that the packet is almost certainly a packet of that type. <li> Some <em>other</em> traffic earlier in the capture indicated that, for example, UDP traffic between two particular addresses and ports will be RTP traffic. </ol> <p> RTP doesn't have a standard port number, so 1) doesn't work; it doesn't, as far as I know, have any "signature", so 2) doesn't work. <br> That leaves 3). If there's RTSP traffic that sets up an RTP session, then, at least in some cases, the RTSP dissector will set things up so that subsequent RTP traffic will be identified. Currently, that's the only place we do that; there may be other places. <br> However, there will always be places where Wireshark is simply <b>incapable</b> of deducing that a given UDP flow is RTP; a mechanism would be needed to allow the user to specify that a given conversation should be treated as RTP. As of Wireshark 0.8.16, such a mechanism exists; if you select a UDP or TCP packet, the right mouse button menu will have a "Decode As..." menu item, which will pop up a dialog box letting you specify that the source port, the destination port, or both the source and destination ports of the packet should be dissected as some particular protocol. """) question(""" Why doesn't Wireshark show Yahoo Messenger packets in captures that contain Yahoo Messenger traffic?""") answer(""" Wireshark only recognizes as Yahoo Messenger traffic packets to or from TCP port 3050 that begin with "YPNS", "YHOO", or "YMSG". TCP segments that start with the middle of a Yahoo Messenger packet that takes more than one TCP segment will not be recognized as Yahoo Messenger packets (even if the TCP segment also contains the beginning of another Yahoo Messenger packet). """) ################################################################# section("Filtering traffic") ################################################################# question("""I saved a filter and tried to use its name to filter the display; why do I get an "Unexpected end of filter string" error?""") answer(""" You cannot use the name of a saved display filter as a filter. To filter the display, you can enter a display filter expression - <strong>not</strong> the name of a saved display filter - in the "Filter:" box at the bottom of the display, and type the &lt;Enter&gt; key or press the "Apply" button (that does not require you to have a saved filter), or, if you want to use a saved filter, you can press the "Filter:" button, select the filter in the dialog box that pops up, and press the "OK" button.""") question(""" How can I search for, or filter, packets that have a particular string anywhere in them? """) answer(""" If you want to do this when capturing, you can't. That's a feature that would be hard to implement in capture filters without changes to the capture filter code, which, on many platforms, is in the OS kernel and, on other platforms, is in the libpcap library. <br> After capture, you can search for text by selecting <i>Edit&#8594;Find Packet...</i> and making sure <i>String</i> is selected. Alternately, you can use the "contains" display filter operator or "matches" operator if it's supported on your system. """) question(""" How do I filter a capture to see traffic for virus XXX? """) answer(""" For some viruses/worms there might be a capture filter to recognize the virus traffic. Check the <a href="https://wiki.wireshark.org/CaptureFilters">CaptureFilters</a> page on the <a href="https://wiki.wireshark.org/">Wireshark Wiki</a> to see if anybody's added such a filter. <br> Note that Wireshark was not designed to be an intrusion detection system; you might be able to use it as an IDS, but in most cases software designed to be an IDS, such as <a href="https://www.snort.org/">Snort</a> or <a href="https://www.prelude-siem.org/">Prelude</a>, will probably work better. """) ################################################################# if __name__ == '__main__': sys.exit(main()) #################################################################
35.725727
145
0.741893
#!/usr/bin/env python # # faq.py # # Routines to assemble a FAQ list for the Wireshark web site. # Questions and answer content can be found below. Section and # question numbers will be automatically generated. # # Wireshark - Network traffic analyzer # By Gerald Combs <gerald@wireshark.org> # Copyright 1998 Gerald Combs # # SPDX-License-Identifier: GPL-2.0-or-later import sys import string class faq_section: def __init__(self, name, secnum): self.name = name self.secnum = secnum self.qa = [] self.subsecs = [] def add_qa(self, question, answer, tag): q_num = len(self.qa) + 1 q_id = "%s.%d" % (self.get_num_string(), q_num) self.qa.append( (q_id, question, answer, tag) ) def get_all_qa(self): return self.qa def add_subsec(self, subsec): self.subsecs.append(subsec) def get_all_subsecs(self): return self.subsecs def get_num_string(self): return "%d" % (self.secnum) def get_name(self): return self.name def get_num_name(self): return "%s. %s" % (self.get_num_string(), self.name) def get_header_level(self): return 3 def print_index(self): print(("<a href=#sec%s><h%d>%s:</h%d></a>\n" % (self.get_num_string(), self.get_header_level(), self.get_num_name(), self.get_header_level()))) for qa in self.qa: id = qa[0] question = qa[1] print('<p class="faq_q">') print(('<a class="faq_qnum" href=#q%s>%s %s</a>\n' % (id, id, question))) print('</p>') for subsec in self.subsecs: subsec.print_index() def print_contents(self): # Table header print((""" <h%d id="sec%s">%s</h%d> """ % (self.get_header_level(), self.get_num_string(), self.get_num_name(), self.get_header_level()))) # Questions and Answers for qa in self.qa: id = qa[0] question = qa[1] answer = qa[2] tag = qa[3] print('<p class="faq_q">') if tag is not None: print(('<span id=%s></span>' % (tag))) print(('<a href=#q%s class="faq_qnum" id=q%s>Q %s: %s</a>' % (id, id, id, question))) print('</p>') print('<p class="faq_a">') print('<span class="faq_anum">A:</span>\n') print(answer) print('</p>') # Subsections for subsec in self.subsecs: subsec.print_contents() # Table footer print("") class faq_subsection(faq_section): def __init__(self, name, secnum, subsecnum): self.name = name self.secnum = secnum self.subsecnum = subsecnum self.qa = [] self.subsecs = [] def get_num_string(self): return "%d.%d" % (self.secnum, self.subsecnum) def get_header_level(self): return 2 class faq_subsubsection(faq_section): def __init__(self, name, secnum, subsecnum, subsubsecnum): self.name = name self.secnum = secnum self.subsecnum = subsecnum self.subsubsecnum = subsubsecnum self.qa = [] self.subsecs = [] def get_num_string(self): return "%d.%d.%d" % (self.secnum, self.subsecnum, self.subsubsecnum) def get_header_level(self): return 2 sec_num = 0 subsec_num = 0 subsubsec_num = 0 sections = [] current_section = None parent_section = None grandparent_section = None current_question = None current_tag = None # Make a URL of itself def selflink(text): return "<a href=\"%s\">%s</a>" % (text, text) # Add a section def section(name): global sec_num global subsec_num global subsubsec_num global current_section global grandparent_section assert not current_question sec_num = sec_num + 1 subsec_num = 0 subsubsec_num = 0 sec = faq_section(name, sec_num) sections.append(sec) current_section = sec grandparent_section = sec # Add a subsection def subsection(name): global subsec_num global subsubsec_num global current_section global parent_section global grandparent_section assert not current_question subsec_num = subsec_num + 1 subsubsec_num = 0 sec = faq_subsection(name, sec_num, subsec_num) grandparent_section.add_subsec(sec) current_section = sec parent_section = sec # Add a subsubsection def subsubsection(name): global subsubsec_num global current_section global parent_section assert not current_question subsubsec_num = subsubsec_num + 1 sec = faq_subsubsection(name, sec_num, subsec_num, subsubsec_num) parent_section.add_subsec(sec) current_section = sec # Add a question def question(text, tag=None): global current_question global current_tag assert current_section assert not current_question assert not current_tag current_question = text current_tag = tag # Add an answer def answer(text): global current_question global current_tag assert current_section assert current_question current_section.add_qa(current_question, text, current_tag) current_question = None current_tag = None # Create the index def create_index(): print(""" <h1 id="index">Index</h1> """) for sec in sections: sec.print_index() print(""" """) # Print result def create_output(header='', footer=''): print(header) create_index() for sec in sections: sec.print_contents() print(footer) def main(): header = '''\ <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Wireshark Frequently Asked Questions</title> </head> <body> ''' footer = '''\ </body> </html> ''' if len(sys.argv) > 1 and sys.argv[1] == '-b': # Only print the document body header = '' footer = '' create_output(header, footer) ################################################################# section("General Questions") ################################################################# question("What is Wireshark?") answer(""" Wireshark&#174; is a network protocol analyzer. It lets you capture and interactively browse the traffic running on a computer network. It has a rich and powerful feature set and is world's most popular tool of its kind. It runs on most computing platforms including Windows, macOS, Linux, and UNIX. Network professionals, security experts, developers, and educators around the world use it regularly. It is freely available as open source, and is released under the GNU General Public License version 2. <br> It is developed and maintained by a global team of protocol experts, and it is an example of a <a href="https://en.wikipedia.org/wiki/Disruptive_technology">disruptive technology</a>. <br> Wireshark used to be known as Ethereal&#174;. See the next question for details about the name change. If you're still using Ethereal, it is strongly recommended that you upgrade to Wireshark as Ethereal is unsupported and has known security vulnerabilities. <br> For more information, please see the <a href="https://www.wireshark.org/about.html">About Wireshark</a> page. """) question("What's up with the name change? Is Wireshark a fork?") answer(""" In May of 2006, Gerald Combs (the original author of Ethereal) went to work for CACE Technologies (best known for WinPcap). Unfortunately, he had to leave the Ethereal trademarks behind. <br> This left the project in an awkward position. The only reasonable way to ensure the continued success of the project was to change the name. This is how Wireshark was born. <br> Wireshark is almost (but not quite) a fork. Normally a "fork" of an open source project results in two names, web sites, development teams, support infrastructures, etc. This is the case with Wireshark except for one notable exception -- every member of the core development team is now working on Wireshark. There has been no active development on Ethereal since the name change. Several parts of the Ethereal web site (such as the mailing lists, source code repository, and build farm) have gone offline. <br> More information on the name change can be found here: </p> <ul class="item_list"> <li><a href="http://www.prweb.com/releases/2006/6/prweb396098.htm">Original press release</a> <li><a href="http://archive09.linux.com/articles/54968">NewsForge article</a> <li>Many other articles in <a href="https://www.wireshark.org/bibliography.html">our bibliography</a> </ul> <p> """) question("Where can I get help?") answer(""" Community support is available on the <a href="https://ask.wireshark.org/">Q&amp;A site</a> and on the wireshark-users mailing list. Subscription information and archives for all of Wireshark's mailing lists can be found at %s. An IRC channel dedicated to Wireshark can be found at %s. <br> Self-paced and instructor-led training is available at <a href="http://www.wiresharktraining.com">Wireshark University</a>. Wireshark University also offers certification via the Wireshark Certified Network Analyst program. """ % (selflink("https://www.wireshark.org/mailman/listinfo"), selflink("irc://irc.freenode.net/wireshark") )) question("What kind of shark is Wireshark?") answer(""" <i>carcharodon photoshopia</i>. """) question("How is Wireshark pronounced, spelled and capitalized?") answer(""" Wireshark is pronounced as the word <i>wire</i> followed immediately by the word <i>shark</i>. Exact pronunciation and emphasis may vary depending on your locale (e.g. Arkansas). <br> It's spelled with a capital <i>W</i>, followed by a lower-case <i>ireshark</i>. It is not a CamelCase word, i.e., <i>WireShark</i> is incorrect. """) question("How much does Wireshark cost?", "but_thats_not_all") answer(""" Wireshark is "free software"; you can download it without paying any license fee. The version of Wireshark you download isn't a "demo" version, with limitations not present in a "full" version; it <em>is</em> the full version. <br> The license under which Wireshark is issued is <a href="https://www.gnu.org/licenses/gpl-2.0.html">the GNU General Public License version 2</a>. See <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html">the GNU GPL FAQ</a> for some more information. """) question("But I just paid someone on eBay for a copy of Wireshark! Did I get ripped off?") answer(""" That depends. Did they provide any sort of value-added product or service, such as installation support, installation media, training, trace file analysis, or funky-colored shark-themed socks? Probably not. <br> Wireshark is <a href="https://www.wireshark.org/download.html">available for anyone to download, absolutely free, at any time</a>. Paying for a copy implies that you should get something for your money. """) question("Can I use Wireshark commercially?") answer(""" Yes, if, for example, you mean "I work for a commercial organization; can I use Wireshark to capture and analyze network traffic in our company's networks or in our customer's networks?" <br> If you mean "Can I use Wireshark as part of my commercial product?", see <a href="#derived_work_gpl">the next entry in the FAQ</a>. """) question("Can I use Wireshark as part of my commercial product?", "derived_work_gpl") answer(""" As noted, Wireshark is licensed under <a href="https://www.gnu.org/licenses/gpl-2.0.html">the GNU General Public License, version 2</a>. The GPL imposes conditions on your use of GPL'ed code in your own products; you cannot, for example, make a "derived work" from Wireshark, by making modifications to it, and then sell the resulting derived work and not allow recipients to give away the resulting work. You must also make the changes you've made to the Wireshark source available to all recipients of your modified version; those changes must also be licensed under the terms of the GPL. See the <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html">GPL FAQ</a> for more details; in particular, note the answer to <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html#GPLCommercially">the question about modifying a GPLed program and selling it commercially</a>, and <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html#LinkingWithGPL">the question about linking GPLed code with other code to make a proprietary program</a>. <br> You can combine a GPLed program such as Wireshark and a commercial program as long as they communicate "at arm's length", as per <a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html#GPLInProprietarySystem">this item in the GPL FAQ</a>. <br> We recommend keeping Wireshark and your product completely separate, communicating over sockets or pipes. If you're loading any part of Wireshark as a DLL, you're probably doing it wrong. """) question("What protocols are currently supported?") answer(""" There are currently hundreds of supported protocols and media. Details can be found in the <a href="https://www.wireshark.org/docs/man-pages/wireshark.html">wireshark(1)</a> man page. """) question("Are there any plans to support {your favorite protocol}?") answer(""" Support for particular protocols is added to Wireshark as a result of people contributing that support; no formal plans for adding support for particular protocols in particular future releases exist. """) question("""Can Wireshark read capture files from {your favorite network analyzer}?""") answer(""" Support for particular capture file formats is added to Wireshark as a result of people contributing that support; no formal plans for adding support for particular capture file formats in particular future releases exist. <br> If a network analyzer writes out files in a format already supported by Wireshark (e.g., in libpcap format), Wireshark may already be able to read them, unless the analyzer has added its own proprietary extensions to that format. <br> If a network analyzer writes out files in its own format, or has added proprietary extensions to another format, in order to make Wireshark read captures from that network analyzer, we would either have to have a specification for the file format, or the extensions, sufficient to give us enough information to read the parts of the file relevant to Wireshark, or would need at least one capture file in that format <strong>AND</strong> a detailed textual analysis of the packets in that capture file (showing packet time stamps, packet lengths, and the top-level packet header) in order to reverse-engineer the file format. <br> Note that there is no guarantee that we will be able to reverse-engineer a capture file format. """) question("What devices can Wireshark use to capture packets?") answer(""" Wireshark can read live data from Ethernet, Token-Ring, FDDI, serial (PPP and SLIP) (if the OS on which it's running allows Wireshark to do so), 802.11 wireless LAN (if the OS on which it's running allows Wireshark to do so), ATM connections (if the OS on which it's running allows Wireshark to do so), and the "any" device supported on Linux by recent versions of libpcap. <br> See <a href="https://wiki.wireshark.org/CaptureSetup/NetworkMedia">the list of supported capture media on various OSes</a> for details (several items in there say "Unknown", which doesn't mean "Wireshark can't capture on them", it means "we don't know whether it can capture on them"; we expect that it will be able to capture on many of them, but we haven't tried it ourselves - if you try one of those types and it works, please update the wiki page accordingly. <br> It can also read a variety of capture file formats, including: </p> <ul> <li> AG Group/WildPackets/Savvius EtherPeek/TokenPeek/AiroPeek/EtherHelp/Packet Grabber captures <li> AIX's iptrace captures <li> Accellent's 5Views LAN agent output <li> Cinco Networks NetXRay captures <li> Cisco Secure Intrusion Detection System IPLog output <li> CoSine L2 debug output <li> DBS Etherwatch VMS text output <li> Endace Measurement Systems' ERF format captures <li> EyeSDN USB S0 traces <li> HP-UX nettl captures <li> ISDN4BSD project i4btrace captures <li> Linux Bluez Bluetooth stack hcidump -w traces <li> Lucent/Ascend router debug output <li> Microsoft Network Monitor captures <li> Network Associates Windows-based Sniffer captures <li> Network General/Network Associates DOS-based Sniffer (compressed or uncompressed) captures <li> Network Instruments Observer version 9 captures <li> Novell LANalyzer captures <li> RADCOM's WAN/LAN analyzer captures <li> Shomiti/Finisar Surveyor captures <li> Toshiba's ISDN routers dump output <li> VMS TCPIPtrace/TCPtrace/UCX$TRACE output <li> Visual Networks' Visual UpTime traffic capture <li> libpcap, tcpdump and various other tools using tcpdump's capture format <li> snoop and atmsnoop output </ul> <p> so that it can read traces from various network types, as captured by other applications or equipment, even if it cannot itself capture on those network types. """) question(""" Does Wireshark work on Windows Vista or Windows Server 2008? """) answer(""" Yes, but if you want to capture packets as a normal user, you must make sure npf.sys is loaded. Wireshark's installer enables this by default. This is not a concern if you run Wireshark as Administrator, but this is discouraged. See the <a href="https://wiki.wireshark.org/CaptureSetup/CapturePrivileges#windows">CapturePrivileges</a> page on the wiki for more details. """) ################################################################# section("Installing Wireshark") ################################################################# question("""I installed the Wireshark RPM (or other package); why did it install TShark but not Wireshark?""") answer(""" Many distributions have separate Wireshark packages, one for non-GUI components such as TShark, editcap, dumpcap, etc. and one for the GUI. If this is the case on your system, there's probably a separate package named <code>wireshark-qt</code>. Find it and install it. """) ################################################################# section("Building Wireshark") ################################################################# question("""I have libpcap installed; why did the configure script not find pcap.h or bpf.h?""") answer(""" Are you sure pcap.h and bpf.h are installed? The official distribution of libpcap only installs the libpcap.a library file when "make install" is run. To install pcap.h and bpf.h, you must run "make install-incl". If you're running Debian or Redhat, make sure you have the "libpcap-dev" or "libpcap-devel" packages installed. <br> It's also possible that pcap.h and bpf.h have been installed in a strange location. If this is the case, you may have to tweak aclocal.m4. """) ################################################################# section("Starting Wireshark") ################################################################# question("""When I try to run Wireshark, why does it complain about <code>sprint_realloc_objid</code> being undefined?""") answer(""" Wireshark can only be linked with version 4.2.2 or later of UCD SNMP. Your version of Wireshark was dynamically linked with such a version of UCD SNMP; however, you have an older version of UCD SNMP installed, which means that when Wireshark is run, it tries to link to the older version, and fails. You will have to replace that version of UCD SNMP with version 4.2.2 or a later version. """) question(""" I've installed Wireshark from Fink on macOS; why is it very slow to start up? """) answer(""" When an application is installed on macOS, prior to 10.4, it is usually "prebound" to speed up launching the application. (That's what the "Optimizing" phase of installation is.) <br> Fink normally performs prebinding automatically when you install a package. However, in some rare cases, for whatever reason the prebinding caches get corrupt, and then not only does prebinding fail, but startup actually becomes much slower, because the system tries in vain to perform prebinding "on the fly" as you launch the application. This fails, causing sometimes huge delays. <br> To fix the prebinding caches, run the command </p> <pre> sudo /sw/var/lib/fink/prebound/update-package-prebinding.pl -f </pre> <p> """) ################################################################# section("Crashes and other fatal errors") ################################################################# question(""" I have an XXX network card on my machine; if I try to capture on it, why does my machine crash or reset itself? """) answer(""" This is almost certainly a problem with one or more of: </p> <ul> <li>the operating system you're using; <li>the device driver for the interface you're using; <li>the libpcap/Npcap library and, if this is Windows, the Npcap device driver; </ul> <p> so: </p> <ul> <li>if you are using Windows, see <a href="https://nmap.org/npcap/">the Npcap support page</a> - check the "Patches, Bug Reports, Questions, Suggestions, etc" section; <li>if you are using some Linux distribution, some version of BSD, or some other UNIX-flavored OS, you should report the problem to the company or organization that produces the OS (in the case of a Linux distribution, report the problem to whoever produces the distribution). </ul> <p> """) question(""" Why does my machine crash or reset itself when I select "Start" from the "Capture" menu or select "Preferences" from the "Edit" menu? """) answer(""" Both of those operations cause Wireshark to try to build a list of the interfaces that it can open; it does so by getting a list of interfaces and trying to open them. There is probably an OS, driver, or, for Windows, Npcap bug that causes the system to crash when this happens; see the previous question. """) ################################################################# section("Capturing packets") ################################################################# question("""When I use Wireshark to capture packets, why do I see only packets to and from my machine, or not see all the traffic I'm expecting to see from or to the machine I'm trying to monitor?""", "promiscsniff") answer(""" This might be because the interface on which you're capturing is plugged into an Ethernet or Token Ring switch; on a switched network, unicast traffic between two ports will not necessarily appear on other ports - only broadcast and multicast traffic will be sent to all ports. <br> Note that even if your machine is plugged into a hub, the "hub" may be a switched hub, in which case you're still on a switched network. <br> Note also that on the Linksys Web site, they say that their auto-sensing hubs "broadcast the 10Mb packets to the port that operate at 10Mb only and broadcast the 100Mb packets to the ports that operate at 100Mb only", which would indicate that if you sniff on a 10Mb port, you will not see traffic coming sent to a 100Mb port, and <i>vice versa</i>. This problem has also been reported for Netgear dual-speed hubs, and may exist for other "auto-sensing" or "dual-speed" hubs. <br> Some switches have the ability to replicate all traffic on all ports to a single port so that you can plug your analyzer into that single port to sniff all traffic. You would have to check the documentation for the switch to see if this is possible and, if so, to see how to do this. See <a href="https://wiki.wireshark.org/SwitchReference">the switch reference page</a> on <a href="https://wiki.wireshark.org/">the Wireshark Wiki</a> for information on some switches. (Note that it's a Wiki, so you can update or fix that information, or add additional information on those switches or information on new switches, yourself.) <br> Note also that many firewall/NAT boxes have a switch built into them; this includes many of the "cable/DSL router" boxes. If you have a box of that sort, that has a switch with some number of Ethernet ports into which you plug machines on your network, and another Ethernet port used to connect to a cable or DSL modem, you can, at least, sniff traffic between the machines on your network and the Internet by plugging the Ethernet port on the router going to the modem, the Ethernet port on the modem, and the machine on which you're running Wireshark into a hub (make sure it's not a switching hub, and that, if it's a dual-speed hub, all three of those ports are running at the same speed. <br> If your machine is <em>not</em> plugged into a switched network or a dual-speed hub, or it is plugged into a switched network but the port is set up to have all traffic replicated to it, the problem might be that the network interface on which you're capturing doesn't support "promiscuous" mode, or because your OS can't put the interface into promiscuous mode. Normally, network interfaces supply to the host only: </p> <ul> <li>packets sent to one of that host's link-layer addresses; <li>broadcast packets; <li>multicast packets sent to a multicast address that the host has configured the interface to accept. </ul> <p> Most network interfaces can also be put in "promiscuous" mode, in which they supply to the host all network packets they see. Wireshark will try to put the interface on which it's capturing into promiscuous mode unless the "Capture packets in promiscuous mode" option is turned off in the "Capture Options" dialog box, and TShark will try to put the interface on which it's capturing into promiscuous mode unless the <code>-p</code> option was specified. However, some network interfaces don't support promiscuous mode, and some OSes might not allow interfaces to be put into promiscuous mode. <br> If the interface is not running in promiscuous mode, it won't see any traffic that isn't intended to be seen by your machine. It <strong>will</strong> see broadcast packets, and multicast packets sent to a multicast MAC address the interface is set up to receive. <br> You should ask the vendor of your network interface whether it supports promiscuous mode. If it does, you should ask whoever supplied the driver for the interface (the vendor, or the supplier of the OS you're running on your machine) whether it supports promiscuous mode with that network interface. <br> In the case of token ring interfaces, the drivers for some of them, on Windows, may require you to enable promiscuous mode in order to capture in promiscuous mode. See <a href="https://wiki.wireshark.org/CaptureSetup/TokenRing">the Wireshark Wiki item on Token Ring capturing</a> for details. <br> In the case of wireless LAN interfaces, it appears that, when those interfaces are promiscuously sniffing, they're running in a significantly different mode from the mode that they run in when they're just acting as network interfaces (to the extent that it would be a significant effort for those drivers to support for promiscuously sniffing <em>and</em> acting as regular network interfaces at the same time), so it may be that Windows drivers for those interfaces don't support promiscuous mode. """) question("""When I capture with Wireshark, why can't I see any TCP packets other than packets to and from my machine, even though another analyzer on the network sees those packets?""") answer(""" You're probably not seeing <em>any</em> packets other than unicast packets to or from your machine, and broadcast and multicast packets; a switch will normally send to a port only unicast traffic sent to the MAC address for the interface on that port, and broadcast and multicast traffic - it won't send to that port unicast traffic sent to a MAC address for some other interface - and a network interface not in promiscuous mode will receive only unicast traffic sent to the MAC address for that interface, broadcast traffic, and multicast traffic sent to a multicast MAC address the interface is set up to receive. <br> TCP doesn't use broadcast or multicast, so you will only see your own TCP traffic, but UDP services may use broadcast or multicast so you'll see some UDP traffic - however, this is not a problem with TCP traffic, it's a problem with unicast traffic, as you also won't see all UDP traffic between other machines. <br> I.e., this is probably <a href="#promiscsniff">the same question as this earlier one</a>; see the response to that question. """) question("""Why am I only seeing ARP packets when I try to capture traffic?""") answer(""" You're probably on a switched network, and running Wireshark on a machine that's not sending traffic to the switch and not being sent any traffic from other machines on the switch. ARP packets are often broadcast packets, which are sent to all switch ports. <br> I.e., this is probably <a href="#promiscsniff">the same question as this earlier one</a>; see the response to that question. """) question(""" Why am I not seeing any traffic when I try to capture traffic?""") answer(""" Is the machine running Wireshark sending out any traffic on the network interface on which you're capturing, or receiving any traffic on that network, or is there any broadcast traffic on the network or multicast traffic to a multicast group to which the machine running Wireshark belongs? <br> If not, this may just be a problem with promiscuous sniffing, either due to running on a switched network or a dual-speed hub, or due to problems with the interface not supporting promiscuous mode; see the response to <a href="#promiscsniff">this earlier question</a>. <br> Otherwise, on Windows, see the response to <a href="#capprobwin">this question</a> and, on a UNIX-flavored OS, see the response to <a href="#capprobunix">this question</a>. """) question(""" Can Wireshark capture on (my T1/E1 line, SS7 links, etc.)? """) answer(""" Wireshark can only capture on devices supported by libpcap/Npcap. On most OSes, only devices that can act as network interfaces of the type that support IP are supported as capture devices for libpcap/Npcap, although the device doesn't necessarily have to be running as an IP interface in order to support traffic capture. <br> On Linux and FreeBSD, libpcap 0.8 and later support the API for <a href="http://www.endace.com/products.htm">Endace Measurement Systems' DAG cards</a>, so that a system with one of those cards, and its driver and libraries, installed can capture traffic with those cards with libpcap-based applications. You would either have to have a version of Wireshark built with that version of libpcap, or a dynamically-linked version of Wireshark and a shared libpcap library with DAG support, in order to do so with Wireshark. You should ask Endace whether that could be used to capture traffic on, for example, your T1/E1 link. <br> See <a href="https://wiki.wireshark.org/CaptureSetup/SS7">the SS7 capture setup page</a> on <a href="https://wiki.wireshark.org/">the Wireshark Wiki</a> for current information on capturing SS7 traffic on TDM links. """) question("""How do I put an interface into promiscuous mode?""") answer(""" By not disabling promiscuous mode when running Wireshark or TShark. <br> Note, however, that: </p> <ul> <li>the form of promiscuous mode that libpcap (the library that programs such as tcpdump, Wireshark, etc. use to do packet capture) turns on will <strong>not</strong> necessarily be shown if you run <code>ifconfig</code> on the interface on a UNIX system; <li>some network interfaces might not support promiscuous mode, and some drivers might not allow promiscuous mode to be turned on - see <a href="#promiscsniff">this earlier question</a> for more information on that; <li>the fact that you're not seeing any traffic, or are only seeing broadcast traffic, or aren't seeing any non-broadcast traffic other than traffic to or from the machine running Wireshark, does not mean that promiscuous mode isn't on - see <a href="#promiscsniff">this earlier question</a> for more information on that. </ul> <p> I.e., this is probably <a href="#promiscsniff">the same question as this earlier one</a>; see the response to that question. """) question(""" I can set a display filter just fine; why don't capture filters work? """) answer(""" Capture filters currently use a different syntax than display filters. Here's the corresponding section from the <a href="https://www.wireshark.org/docs/man-pages/wireshark.html">wireshark(1)</a> man page: <br> "Display filters in Wireshark are very powerful; more fields are filterable in Wireshark than in other protocol analyzers, and the syntax you can use to create your filters is richer. As Wireshark progresses, expect more and more protocol fields to be allowed in display filters. <br> Packet capturing is performed with the pcap library. The capture filter syntax follows the rules of the pcap library. This syntax is different from the display filter syntax." <br> The capture filter syntax used by libpcap can be found in the <a href="http://www.tcpdump.org/tcpdump_man.html">tcpdump(8)</a> man page. """) question(""" How can I capture packets with CRC errors? """) answer(""" Wireshark can capture only the packets that the packet capture library - libpcap on UNIX-flavored OSes, and the Npcap port to Windows of libpcap on Windows - can capture, and libpcap/Npcap can capture only the packets that the OS's raw packet capture mechanism (or the Npcap driver, and the underlying OS networking code and network interface drivers, on Windows) will allow it to capture. <br> Unless the OS always supplies packets with errors such as invalid CRCs to the raw packet capture mechanism, or can be configured to do so, invalid CRCs to the raw packet capture mechanism, Wireshark - and other programs that capture raw packets, such as tcpdump - cannot capture those packets. You will have to determine whether your OS needs to be so configured and, if so, can be so configured, configure it if necessary and possible, and make whatever changes to libpcap and the packet capture program you're using are necessary, if any, to support capturing those packets. <br> Most OSes probably do <strong>not</strong> support capturing packets with invalid CRCs on Ethernet, and probably do not support it on most other link-layer types. Some drivers on some OSes do support it, such as some Ethernet drivers on FreeBSD; in those OSes, you might always get those packets, or you might only get them if you capture in promiscuous mode (you'd have to determine which is the case). <br> Note that libpcap does not currently supply to programs that use it an indication of whether the packet's CRC was invalid (because the drivers themselves do not supply that information to the raw packet capture mechanism); therefore, Wireshark will not indicate which packets had CRC errors unless the FCS was captured (see the next question) and you're using Wireshark 0.9.15 and later, in which case Wireshark will check the CRC and indicate whether it's correct or not. """) question(""" How can I capture entire frames, including the FCS? """) answer(""" Wireshark can only capture data that the packet capture library - libpcap on UNIX-flavored OSes, and the Npcap port to Windows of libpcap on Windows - can capture, and libpcap/Npcap can capture only the data that the OS's raw packet capture mechanism (or the Npcap driver, and the underlying OS networking code and network interface drivers, on Windows) will allow it to capture. <br> For any particular link-layer network type, unless the OS supplies the FCS of a frame as part of the frame, or can be configured to do so, Wireshark - and other programs that capture raw packets, such as tcpdump - cannot capture the FCS of a frame. You will have to determine whether your OS needs to be so configured and, if so, can be so configured, configure it if necessary and possible, and make whatever changes to libpcap and the packet capture program you're using are necessary, if any, to support capturing the FCS of a frame. <br> Most OSes do <strong>not</strong> support capturing the FCS of a frame on Ethernet, and probably do not support it on most other link-layer types. Some drivres on some OSes do support it, such as some (all?) Ethernet drivers on NetBSD and possibly the driver for Apple's gigabit Ethernet interface in macOS; in those OSes, you might always get the FCS, or you might only get the FCS if you capture in promiscuous mode (you'd have to determine which is the case). <br> Versions of Wireshark prior to 0.9.15 will not treat an Ethernet FCS in a captured packet as an FCS. 0.9.15 and later will attempt to determine whether there's an FCS at the end of the frame and, if it thinks there is, will display it as such, and will check whether it's the correct CRC-32 value or not. """) question(""" I'm capturing packets on a machine on a VLAN; why don't the packets I'm capturing have VLAN tags? """) answer(""" You might be capturing on what might be called a "VLAN interface" - the way a particular OS makes VLANs plug into the networking stack might, for example, be to have a network device object for the physical interface, which takes VLAN packets, strips off the VLAN header and constructs an Ethernet header, and passes that packet to an internal network device object for the VLAN, which then passes the packets onto various higher-level protocol implementations. <br> In order to see the raw Ethernet packets, rather than "de-VLANized" packets, you would have to capture not on the virtual interface for the VLAN, but on the interface corresponding to the physical network device, if possible. See <a href="https://wiki.wireshark.org/CaptureSetup/VLAN">the Wireshark Wiki item on VLAN capturing</a> for details. """) question(""" Why does Wireshark hang after I stop a capture? """) answer(""" The most likely reason for this is that Wireshark is trying to look up an IP address in the capture to convert it to a name (so that, for example, it can display the name in the source address or destination address columns), and that lookup process is taking a very long time. <br> Wireshark calls a routine in the OS of the machine on which it's running to convert of IP addresses to the corresponding names. That routine probably does one or more of: </p> <ul><li>a search of a system file listing IP addresses and names; <li>a lookup using DNS; <li>on UNIX systems, a lookup using NIS; <li>on Windows systems, a NetBIOS-over-TCP query. </ul> <p> If a DNS server that's used in an address lookup is not responding, the lookup will fail, but will only fail after a timeout while the system routine waits for a reply. <br> In addition, on Windows systems, if the DNS lookup of the address fails, either because the server isn't responding or because there are no records in the DNS that could be used to map the address to a name, a NetBIOS-over-TCP query will be made. That query involves sending a message to the NetBIOS-over-TCP name service on that machine, asking for the name and other information about the machine. If the machine isn't running software that responds to those queries - for example, many non-Windows machines wouldn't be running that software - the lookup will only fail after a timeout. Those timeouts can cause the lookup to take a long time. <br> If you disable network address-to-name translation - for example, by turning off the "Enable network name resolution" option in the "Capture Options" dialog box for starting a network capture - the lookups of the address won't be done, which may speed up the process of reading the capture file after the capture is stopped. You can make that setting the default by selecting "Preferences" from the "Edit" menu, turning off the "Enable network name resolution" option in the "Name resolution" options in the preferences disalog box, and using the "Save" button in that dialog box; note that this will save <em>all</em> your current preference settings. <br> If Wireshark hangs when reading a capture even with network name resolution turned off, there might, for example, be a bug in one of Wireshark's dissectors for a protocol causing it to loop infinitely. If you're not running the most recent release of Wireshark, you should first upgrade to that release, as, if there's a bug of that sort, it might've been fixed in a release after the one you're running. If the hang occurs in the most recent release of Wireshark, the bug should be reported to <a href="mailto:wireshark-dev@wireshark.org">the Wireshark developers' mailing list</a> at <code>wireshark-dev@wireshark.org</code>. <br> On UNIX-flavored OSes, please try to force Wireshark to dump core, by sending it a <code>SIGABRT</code> signal (usually signal 6) with the <code>kill</code> command, and then get a stack trace if you have a debugger installed. A stack trace can be obtained by using your debugger (<code>gdb</code> in this example), the Wireshark binary, and the resulting core file. Here's an example of how to use the gdb command <code>backtrace</code> to do so. </p> <pre> $ gdb wireshark core (gdb) backtrace ..... prints the stack trace (gdb) quit $ </pre> <p> The core dump file may be named "wireshark.core" rather than "core" on some platforms (e.g., BSD systems). <br> Also, if at all possible, please send a copy of the capture file that caused the problem. When capturing packets, Wireshark normally writes captured packets to a temporary file, which will probably be in <code>/tmp</code> or <code>/var/tmp</code> on UNIX-flavored OSes, <code>\\TEMP</code> on the main system disk (normally <code>\\Documents and Settings\\</code><var>your login name</var> <code>\\Local Settings\\Temp</code> on the main system disk on Windows Windows XP and Server 2003, and <code>\\Users\\<var>your login name</var>\\AppData\\Local\\Temp</code> on the main system disk on Windows Vista and later, so the capture file will probably be there. If you are capturing on a single interface, it will have a name of the form, <code>wireshark_&lt;iface&gt;_YYYYmmddHHMMSS_XXXXXX.&lt;fmt&gt;</code>, where &lt;fmt&gt; is the capture file format (pcap or pcapng), and &lt;iface&gt; is the actual name of the interface you are capturing on; otherwise, if you are capturing on multiple interfaces, it will have a name of the form, <code>wireshark_&lt;N&gt;_interfaces_YYYYmmddHHMMSS_XXXXXX.&lt;fmt&gt;</code>, where &lt;N&gt; is the number of simultaneous interfaces you are capturing on. Please don't send a trace file greater than 1 MB when compressed; instead, make it available via FTP or HTTP, or say it's available but leave it up to a developer to ask for it. If the trace file contains sensitive information (e.g., passwords), then please do not send it. """) ################################################################# section("Capturing packets on Windows") ################################################################# question(""" I'm running Wireshark on Windows; why does some network interface on my machine not show up in the list of interfaces in the "Interface:" field in the dialog box popped up by "Capture->Start", and/or why does Wireshark give me an error if I try to capture on that interface? """, "capprobwin") answer(""" Wireshark relies on the Npcap library, on the Npcap device driver, and and on the facilities that come with the OS on which it's running in order to do captures. <br> Therefore, if the OS, the Npcap library, or the Npcap driver don't support capturing on a particular network interface device, Wireshark won't be able to capture on that device. <br> If an interface doesn't show up in the list of interfaces in the "Interface:" field, and you know the name of the interface, try entering that name in the "Interface:" field and capturing on that device. <br> If the attempt to capture on it succeeds, the interface is somehow not being reported by the mechanism Wireshark uses to get a list of interfaces. Try listing the interfaces with WinDump; see <a href="https://www.windump.org/">the WinDump Web site</a> for information on using WinDump. <br> You would run WinDump with the <code>-D</code> flag; if it lists the interface, please report this to <a href="mailto:wireshark-dev@wireshark.org">wireshark-dev@wireshark.org</a> giving full details of the problem, including </p> <ul> <li>the operating system you're using, and the version of that operating system; <li>the type of network device you're using; <li>the output of WinDump. </ul> <p> If WinDump does <em>not</em> list the interface, this is almost certainly a problem with one or more of: </p> <ul> <li>the operating system you're using; <li>the device driver for the interface you're using; <li>the WinPcap library and/or the WinPcap device driver; </ul> <p> so first check <a href="https://nmap.org/npcap/guide/">the Npcap User's Guide</a> to see if your problem is mentioned there. If not, then see <a href="https://nmap.org/npcap/">the main Npcap page</a> - check the "Patches, Bug Reports, Questions, Suggestions, etc" section. <br> If you are having trouble capturing on a particular network interface, first try capturing on that device with WinDump; see <a href="https://www.windump.org/">the WinDump Web site</a> for information on using WinDump. <br> If you can capture on the interface with WinDump, send mail to <a href="mailto:wireshark-users@wireshark.org">wireshark-users@wireshark.org</a> giving full details of the problem, including </p> <ul> <li>the operating system you're using, and the version of that operating system; <li>the type of network device you're using; <li>the error message you get from Wireshark. </ul> <p> If you <em>cannot</em> capture on the interface with WinDump, this is almost certainly a problem with one or more of: </p> <ul> <li>the operating system you're using; <li>the device driver for the interface you're using; <li>the Npcap library and/or the Npcap device driver; </ul> <p> so first check <a href="https://nmap.org/npcap/guide/">the Npcap User's Guide</a> to see if your problem is mentioned there. If not, then see <a href="https://nmap.org/npcap/">the main Npcap page</a> - check the "Patches, Bug Reports, Questions, Suggestions, etc" section. <br> You may also want to ask the <a href="mailto:wireshark-users@wireshark.org">wireshark-users@wireshark.org</a> and the <a href="mailto:winpcap-users@winpcap.org">winpcap-users@winpcap.org</a> mailing lists to see if anybody happens to know about the problem and know a workaround or fix for the problem. (Note that you will have to subscribe to that list in order to be allowed to mail to it; see <a href="https://nmap.org/npcap/">the Npcap support page</a> for information on the mailing list.) In your mail, please give full details of the problem, as described above, and also indicate that the problem occurs with WinDump, not just with Wireshark. """) question(""" I'm running Wireshark on Windows; why do no network interfaces show up in the list of interfaces in the "Interface:" field in the dialog box popped up by "Capture->Start"? """) answer(""" This is really <a href="#capprobwin">the same question as a previous one</a>; see the response to that question. """) question(""" I'm running Wireshark on Windows; why am I not seeing any traffic being sent by the machine running Wireshark?""") answer(""" If you are running some form of VPN client software, it might be causing this problem; people have seen this problem when they have Check Point's VPN software installed on their machine. If that's the cause of the problem, you will have to remove the VPN software in order to have Wireshark (or any other application using Npcap) see outgoing packets; unfortunately, neither we nor the Npcap developers know any way to make Npcap and the VPN software work well together. <br> Also, some drivers for Windows (especially some wireless network interface drivers) apparently do not, when running in promiscuous mode, arrange that outgoing packets are delivered to the software that requested that the interface run promiscuously; try turning promiscuous mode off. """) question(""" When I capture on Windows in promiscuous mode, I can see packets other than those sent to or from my machine; however, those packets show up with a "Short Frame" indication, unlike packets to or from my machine. What should I do to arrange that I see those packets in their entirety? """) answer(""" In at least some cases, this appears to be the result of PGPnet running on the network interface on which you're capturing; turn it off on that interface. """) question(""" I'm trying to capture 802.11 traffic on Windows; why am I not seeing any packets? """, "win802_11promisc") answer(""" At least some 802.11 card drivers on Windows appear not to see any packets if they're running in promiscuous mode. Try turning promiscuous mode off; you'll only be able to see packets sent by and received by your machine, not third-party traffic, and it'll look like Ethernet traffic and won't include any management or control frames, but that's a limitation of the card drivers. <br> See the archived <a href="https://web.archive.org/web/20090226193157/http://www.micro-logix.com/winpcap/Supported.asp">MicroLogix's list of cards supported with WinPcap</a> for information on support of various adapters and drivers with WinPcap. """) question(""" I'm trying to capture 802.11 traffic on Windows; why am I seeing packets received by the machine on which I'm capturing traffic, but not packets sent by that machine? """) answer(""" This appears to be another problem with promiscuous mode; try turning it off. """) question(""" I'm trying to capture Ethernet VLAN traffic on Windows, and I'm capturing on a "raw" Ethernet device rather than a "VLAN interface", so that I can see the VLAN headers; why am I seeing packets received by the machine on which I'm capturing traffic, but not packets sent by that machine? """) answer(""" The way the Windows networking code works probably means that packets are sent on a "VLAN interface" rather than the "raw" device, so packets sent by the machine will only be seen when you capture on the "VLAN interface". If so, you will be unable to see outgoing packets when capturing on the "raw" device, so you are stuck with a choice between seeing VLAN headers and seeing outgoing packets. """) ################################################################# section("Capturing packets on UN*Xes") ################################################################# question(""" I'm running Wireshark on a UNIX-flavored OS; why does some network interface on my machine not show up in the list of interfaces in the "Interface:" field in the dialog box popped up by "Capture->Start", and/or why does Wireshark give me an error if I try to capture on that interface? """, "capprobunix") answer(""" You may need to run Wireshark from an account with sufficient privileges to capture packets, such as the super-user account, or may need to give your account sufficient privileges to capture packets. Only those interfaces that Wireshark can open for capturing show up in that list; if you don't have sufficient privileges to capture on any interfaces, no interfaces will show up in the list. See <a href="https://wiki.wireshark.org/CaptureSetup/CapturePrivileges">the Wireshark Wiki item on capture privileges</a> for details on how to give a particular account or account group capture privileges on platforms where that can be done. <br> If you are running Wireshark from an account with sufficient privileges, then note that Wireshark relies on the libpcap library, and on the facilities that come with the OS on which it's running in order to do captures. On some OSes, those facilities aren't present by default; see <a href="https://wiki.wireshark.org/CaptureSetup/CaptureSupport">the Wireshark Wiki item on adding capture support</a> for details. <br> And, even if you're running with an account that has sufficient privileges to capture, and capture support is present in your OS, if the OS or the libpcap library don't support capturing on a particular network interface device or particular types of devices, Wireshark won't be able to capture on that device. <br> On Solaris, note that libpcap 0.6.2 and earlier didn't support Token Ring interfaces; the current version, 0.7.2, does support Token Ring, and the current version of Wireshark works with libpcap 0.7.2 and later. <br> If an interface doesn't show up in the list of interfaces in the "Interface:" field, and you know the name of the interface, try entering that name in the "Interface:" field and capturing on that device. <br> If the attempt to capture on it succeeds, the interface is somehow not being reported by the mechanism Wireshark uses to get a list of interfaces; please report this to <a href="mailto:wireshark-dev@wireshark.org">wireshark-dev@wireshark.org</a> giving full details of the problem, including </p> <ul> <li>the operating system you're using, and the version of that operating system (for Linux, give both the version number of the kernel and the name and version number of the distribution you're using); <li>the type of network device you're using. </ul> <p> If you are having trouble capturing on a particular network interface, and you've made sure that (on platforms that require it) you've arranged that packet capture support is present, as per the above, first try capturing on that device with <code>tcpdump</code>. <br> If you can capture on the interface with <code>tcpdump</code>, send mail to <a href="mailto:wireshark-users@wireshark.org">wireshark-users@wireshark.org</a> giving full details of the problem, including </p> <ul> <li>the operating system you're using, and the version of that operating system (for Linux, give both the version number of the kernel and the name and version number of the distribution you're using); <li>the type of network device you're using; <li>the error message you get from Wireshark. </ul> <p> If you <em>cannot</em> capture on the interface with <code>tcpdump</code>, this is almost certainly a problem with one or more of: </p> <ul> <li>the operating system you're using; <li>the device driver for the interface you're using; <li>the libpcap library; </ul> <p> so you should report the problem to the company or organization that produces the OS (in the case of a Linux distribution, report the problem to whoever produces the distribution). <br> You may also want to ask the <a href="mailto:wireshark-users@wireshark.org">wireshark-users@wireshark.org</a> and the <a href="mailto:tcpdump-workers@lists.tcpdump.org">tcpdump-workers@lists.tcpdump.org</a> mailing lists to see if anybody happens to know about the problem and know a workaround or fix for the problem. In your mail, please give full details of the problem, as described above, and also indicate that the problem occurs with <code>tcpdump</code> not just with Wireshark. """) question(""" I'm running Wireshark on a UNIX-flavored OS; why do no network interfaces show up in the list of interfaces in the "Interface:" field in the dialog box popped up by "Capture->Start"? """) answer(""" This is really <a href="#capprobunix">the same question as the previous one</a>; see the response to that question. """) question("""I'm capturing packets on Linux; why do the time stamps have only 100ms resolution, rather than 1us resolution?""") answer(""" Wireshark gets time stamps from libpcap/Npcap, and libpcap/Npcap get them from the OS kernel, so Wireshark - and any other program using libpcap, such as tcpdump - is at the mercy of the time stamping code in the OS for time stamps. <br> At least on x86-based machines, Linux can get high-resolution time stamps on newer processors with the Time Stamp Counter (TSC) register; for example, Intel x86 processors, starting with the Pentium Pro, and including all x86 processors since then, have had a TSC, and other vendors probably added the TSC at some point to their families of x86 processors. The Linux kernel must be configured with the CONFIG_X86_TSC option enabled in order to use the TSC. Make sure this option is enabled in your kernel. <br> In addition, some Linux distributions may have bugs in their versions of the kernel that cause packets not to be given high-resolution time stamps even if the TSC is enabled. See, for example, bug 61111 for Red Hat Linux 7.2. If your distribution has a bug such as this, you may have to run a standard kernel from kernel.org in order to get high-resolution time stamps. """) ################################################################# section("Capturing packets on wireless LANs") ################################################################# question(""" How can I capture raw 802.11 frames, including non-data (management, beacon) frames? """, "raw_80211_sniff") answer(""" That depends on the operating system on which you're running, and on the 802.11 interface on which you're capturing. <br> This would probably require that you capture in promiscuous mode or in the mode called "monitor mode" or "RFMON mode". On some platforms, or with some cards, this might require that you capture in monitor mode - promiscuous mode might not be sufficient. If you want to capture traffic on networks other than the one with which you're associated, you will have to capture in monitor mode. <br> Not all operating systems support capturing non-data packets and, even on operating systems that do support it, not all drivers, and thus not all interfaces, support it. Even on those that do, monitor mode might not be supported by the operating system or by the drivers for all interfaces. <br> <strong>NOTE:</strong> an interface running in monitor mode will, on most if not all platforms, not be able to act as a regular network interface; putting it into monitor mode will, in effect, take your machine off of whatever network it's on as long as the interface is in monitor mode, allowing it only to passively capture packets. <br> This means that you should disable name resolution when capturing in monitor mode; otherwise, when Wireshark (or TShark, or tcpdump) tries to display IP addresses as host names, it will probably block for a long time trying to resolve the name because it will not be able to communicate with any DNS or NIS servers. <br> See <a href="https://wiki.wireshark.org/CaptureSetup/WLAN">the Wireshark Wiki item on 802.11 capturing</a> for details. """) question(""" How do I capture on an 802.11 device in monitor mode?""", "monitor") answer(""" Whether you will be able to capture in monitor mode depends on the operating system, adapter, and driver you're using. See <a href="#raw_80211_sniff">the previous question</a> for information on monitor mode, including a link to the Wireshark Wiki page that gives details on 802.11 capturing. """) ################################################################# section("Viewing traffic") ################################################################# question("Why am I seeing lots of packets with incorrect TCP checksums?") answer(""" If the packets that have incorrect TCP checksums are all being sent by the machine on which Wireshark is running, this is probably because the network interface on which you're capturing does TCP checksum offloading. That means that the TCP checksum is added to the packet by the network interface, not by the OS's TCP/IP stack; when capturing on an interface, packets being sent by the host on which you're capturing are directly handed to the capture interface by the OS, which means that they are handed to the capture interface without a TCP checksum being added to them. <br> The only way to prevent this from happening would be to disable TCP checksum offloading, but </p> <ol> <li>that might not even be possible on some OSes; <li>that could reduce networking performance significantly. </ol> <p> However, you can disable the check that Wireshark does of the TCP checksum, so that it won't report any packets as having TCP checksum errors, and so that it won't refuse to do TCP reassembly due to a packet having an incorrect TCP checksum. That can be set as an Wireshark preference by selecting "Preferences" from the "Edit" menu, opening up the "Protocols" list in the left-hand pane of the "Preferences" dialog box, selecting "TCP", from that list, turning off the "Check the validity of the TCP checksum when possible" option, clicking "Save" if you want to save that setting in your preference file, and clicking "OK". <br> It can also be set on the Wireshark or TShark command line with a <code>-o tcp.check_checksum:false</code> command-line flag, or manually set in your preferences file by adding a <code>tcp.check_checksum:false</code> line. """) question(""" I've just installed Wireshark, and the traffic on my local LAN is boring. Where can I find more interesting captures? """) answer(""" We have a collection of strange and exotic sample capture files at %s""" % (selflink("https://wiki.wireshark.org/SampleCaptures"))) question(""" Why doesn't Wireshark correctly identify RTP packets? It shows them only as UDP.""") answer(""" Wireshark can identify a UDP datagram as containing a packet of a particular protocol running atop UDP only if </p> <ol> <li> The protocol in question has a particular standard port number, and the UDP source or destination port number is that port <li> Packets of that protocol can be identified by looking for a "signature" of some type in the packet - i.e., some data that, if Wireshark finds it in some particular part of a packet, means that the packet is almost certainly a packet of that type. <li> Some <em>other</em> traffic earlier in the capture indicated that, for example, UDP traffic between two particular addresses and ports will be RTP traffic. </ol> <p> RTP doesn't have a standard port number, so 1) doesn't work; it doesn't, as far as I know, have any "signature", so 2) doesn't work. <br> That leaves 3). If there's RTSP traffic that sets up an RTP session, then, at least in some cases, the RTSP dissector will set things up so that subsequent RTP traffic will be identified. Currently, that's the only place we do that; there may be other places. <br> However, there will always be places where Wireshark is simply <b>incapable</b> of deducing that a given UDP flow is RTP; a mechanism would be needed to allow the user to specify that a given conversation should be treated as RTP. As of Wireshark 0.8.16, such a mechanism exists; if you select a UDP or TCP packet, the right mouse button menu will have a "Decode As..." menu item, which will pop up a dialog box letting you specify that the source port, the destination port, or both the source and destination ports of the packet should be dissected as some particular protocol. """) question(""" Why doesn't Wireshark show Yahoo Messenger packets in captures that contain Yahoo Messenger traffic?""") answer(""" Wireshark only recognizes as Yahoo Messenger traffic packets to or from TCP port 3050 that begin with "YPNS", "YHOO", or "YMSG". TCP segments that start with the middle of a Yahoo Messenger packet that takes more than one TCP segment will not be recognized as Yahoo Messenger packets (even if the TCP segment also contains the beginning of another Yahoo Messenger packet). """) ################################################################# section("Filtering traffic") ################################################################# question("""I saved a filter and tried to use its name to filter the display; why do I get an "Unexpected end of filter string" error?""") answer(""" You cannot use the name of a saved display filter as a filter. To filter the display, you can enter a display filter expression - <strong>not</strong> the name of a saved display filter - in the "Filter:" box at the bottom of the display, and type the &lt;Enter&gt; key or press the "Apply" button (that does not require you to have a saved filter), or, if you want to use a saved filter, you can press the "Filter:" button, select the filter in the dialog box that pops up, and press the "OK" button.""") question(""" How can I search for, or filter, packets that have a particular string anywhere in them? """) answer(""" If you want to do this when capturing, you can't. That's a feature that would be hard to implement in capture filters without changes to the capture filter code, which, on many platforms, is in the OS kernel and, on other platforms, is in the libpcap library. <br> After capture, you can search for text by selecting <i>Edit&#8594;Find Packet...</i> and making sure <i>String</i> is selected. Alternately, you can use the "contains" display filter operator or "matches" operator if it's supported on your system. """) question(""" How do I filter a capture to see traffic for virus XXX? """) answer(""" For some viruses/worms there might be a capture filter to recognize the virus traffic. Check the <a href="https://wiki.wireshark.org/CaptureFilters">CaptureFilters</a> page on the <a href="https://wiki.wireshark.org/">Wireshark Wiki</a> to see if anybody's added such a filter. <br> Note that Wireshark was not designed to be an intrusion detection system; you might be able to use it as an IDS, but in most cases software designed to be an IDS, such as <a href="https://www.snort.org/">Snort</a> or <a href="https://www.prelude-siem.org/">Prelude</a>, will probably work better. """) ################################################################# if __name__ == '__main__': sys.exit(main()) #################################################################
3,802
26
673
40302b004460699dfe8522c59c9a3e8cf1c35d83
89
py
Python
configs/_base_/filters/savizky_golay.py
pallgeuer/mmpose
d3c17d5e6bdb9dbaca19f3bf53aa2802105355fd
[ "Apache-2.0" ]
null
null
null
configs/_base_/filters/savizky_golay.py
pallgeuer/mmpose
d3c17d5e6bdb9dbaca19f3bf53aa2802105355fd
[ "Apache-2.0" ]
null
null
null
configs/_base_/filters/savizky_golay.py
pallgeuer/mmpose
d3c17d5e6bdb9dbaca19f3bf53aa2802105355fd
[ "Apache-2.0" ]
null
null
null
filter_cfg = dict( type='SavizkyGolayFilter', window_size=11, polyorder=2, )
14.833333
30
0.662921
filter_cfg = dict( type='SavizkyGolayFilter', window_size=11, polyorder=2, )
0
0
0
b8439448287ddf1bbb2368705d0a9643ba1ccc8e
1,363
py
Python
CustomCNN.py
mehtajinesh/Classify-Dog-Breeds-using-CNNs
6ab2549ec592bd4d7fe404f7973663bc4d38ba15
[ "MIT" ]
3
2019-12-09T07:51:31.000Z
2020-12-10T18:30:03.000Z
CustomCNN.py
mehtajinesh/Classify-Dog-Breeds-using-CNNs
6ab2549ec592bd4d7fe404f7973663bc4d38ba15
[ "MIT" ]
4
2021-03-19T10:03:22.000Z
2022-03-12T00:10:53.000Z
CustomCNN.py
mehtajinesh/Classify-Dog-Breeds-using-CNNs
6ab2549ec592bd4d7fe404f7973663bc4d38ba15
[ "MIT" ]
null
null
null
import torch.nn as nn import torch.nn.functional as F # define the CNN architecture ### TODO: choose an architecture, and complete the class
33.243902
66
0.547322
import torch.nn as nn import torch.nn.functional as F # define the CNN architecture class Net(nn.Module): ### TODO: choose an architecture, and complete the class def __init__(self): super(Net, self).__init__() ## Define layers of a CNN self.features = nn.Sequential( # 1st 2D convolution layer nn.Conv2d(3, 16, kernel_size=2, stride=1, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), # Defining another 2D convolution layer nn.Conv2d(16, 32, kernel_size=2, stride=1, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), # Defining another 2D convolution layer nn.Conv2d(32, 64, kernel_size=2, stride=1, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Dropout(p=0.5), nn.AvgPool2d(kernel_size=2, stride=2) ) self.classifier = nn.Sequential( nn.Linear(64 * 14 * 14, 133), nn.LogSoftmax(dim=1) ) def forward(self, x): ## Define forward behavior out = self.features(x) out = out.view(-1, 64*14*14) out = self.classifier(out) return out
1,139
0
79
c5b910ce2d9d382f8cdfb27852093b6ecd72db00
21,559
py
Python
Quaternion/tests/test_all.py
sot/Quaternion
610fe97f875199e0ec41e2b1c6f738457f134fd1
[ "BSD-3-Clause" ]
null
null
null
Quaternion/tests/test_all.py
sot/Quaternion
610fe97f875199e0ec41e2b1c6f738457f134fd1
[ "BSD-3-Clause" ]
28
2016-07-13T18:05:05.000Z
2021-08-31T15:18:26.000Z
Quaternion/tests/test_all.py
sot/Quaternion
610fe97f875199e0ec41e2b1c6f738457f134fd1
[ "BSD-3-Clause" ]
4
2016-11-11T20:54:43.000Z
2021-02-12T02:54:52.000Z
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np import pytest import pickle import os from .. import Quat, normalize ra = 10. dec = 20. roll = 30. q0 = Quat([ra, dec, roll]) equatorial_23 = np.array([[[10, 20, 30], [10, 20, -30], [10, -60, 30]], [[10, 20, 0], [10, 50, 30], [10, -50, -30]]], dtype=float) q_23 = np.zeros(equatorial_23[..., 0].shape + (4,)) for _i, _j in indices(equatorial_23.shape[:-1]): q_23[_i, _j] = Quat(equatorial_23[_i, _j]).q transform_23 = np.zeros(equatorial_23[..., 0].shape + (3, 3)) for _i, _j in indices(transform_23.shape[:-2]): transform_23[_i, _j] = Quat(equatorial_23[_i, _j]).transform def test_from_transform(): """Initialize from inverse of q0 via transform matrix""" q = Quat(q0.transform.transpose()) assert np.allclose(q.q[0], -0.26853582) assert np.allclose(q.q[1], 0.14487813) assert np.allclose(q.q[2], -0.12767944) assert np.allclose(q.q[3], 0.94371436) q = Quat(q0.transform) assert np.allclose(q.roll0, 30) assert np.allclose(q.ra0, 10) q1 = Quat(transform=q0.transform) assert np.all(q1.q == q.q) def test_vector_to_scalar_correspondence(): """ Simple test that all possible transform pathways give the same answer when done in vectorized form as they do for the scalar version. """ atol = 1e-12 # Input equatorial has roll not in 0:360, so fix that for comparisons. eq_23 = equatorial_23.copy() normalize_angles(eq_23[..., -1], 0, 360) # Compare vectorized computations for all possible input/output combos # with the same for the scalar calculation. q = Quat(equatorial=equatorial_23) assert np.all(q.q == q_23) assert np.all(q.equatorial == equatorial_23) assert np.all(q.transform == transform_23) q = Quat(q=q_23) assert np.all(q.q == q_23) assert np.allclose(q.equatorial, eq_23, rtol=0, atol=atol) assert np.allclose(q.transform, transform_23, rtol=0, atol=atol) q = Quat(transform=transform_23) assert np.allclose(q.q, q_23, rtol=0, atol=atol) assert np.allclose(q.equatorial, eq_23, rtol=0, atol=atol) assert np.all(q.transform == transform_23) def test_numeric_underflow(): """ Test new code (below) for numeric issue https://github.com/sot/Quaternion/issues/1. If this code is not included then the test fails with a MathDomainError:: one_minus_xn2 = 1 - xn**2 if one_minus_xn2 < 0: if one_minus_xn2 < -1e-12: raise ValueError('Unexpected negative norm: {}'.format(one_minus_xn2)) one_minus_xn2 = 0 """ quat = Quat((0, 0, 0)) angle = 0 while angle < 360: q = Quat((0, angle, 0)) quat = q * quat _ = quat.equatorial angle += 0.1 def test_mult_and_dq_broadcasted(): """Test mult and delta quat of Quats with different but broadcastable shapes. """ q2 = Quat(equatorial=np.arange(18).reshape(3, 2, 3)) q1 = Quat(equatorial=[[10, 20, 30], [40, 50, 60]]) q0 = Quat(equatorial=[10, 20, 30]) # (3,2) * () = (3,2) q20 = q2 * q0 dq20 = q2.dq(q0) assert q20.shape == (3, 2) assert dq20.shape == (3, 2) for ii in range(3): for jj in range(2): qq = q2[ii, jj] * q0 dq = q2[ii, jj].dq(q0) assert np.allclose(qq.q, q20.q[ii, jj]) assert np.allclose(dq.q, dq20.q[ii, jj]) # (3,2) * (2,) = (3,2) q21 = q2 * q1 dq21 = q2.dq(q1) assert q21.shape == (3, 2) assert dq21.shape == (3, 2) for ii in range(3): for jj in range(2): qq = q2[ii, jj] * q1[jj] dq = q2[ii, jj].dq(q1[jj]) assert np.allclose(qq.q, q21.q[ii, jj]) assert np.allclose(dq.q, dq21.q[ii, jj]) def test_pickle(): """ Pickle file generated using Quaternion v3.4.1: from Quaternion import Quat import pickle q = Quat([10., 20., 30.]) quats = [Quat(q.q), Quat(q.transform), Quat(q.equatorial)] quats.append(q) with open('quaternion-v3.4.1.pkl', 'wb') as f: pickle.dump(quats, f) """ # testing we can unpickle older versions filename = os.path.join(os.path.dirname(__file__), 'data', 'quaternion-v3.4.1.pkl') with open(filename, 'rb') as f: quaternions = pickle.load(f) for q in quaternions: assert np.all(np.isclose(q.q, [0.26853582, -0.14487813, 0.12767944, 0.94371436])) assert np.all(np.isclose(q.equatorial, [10., 20., 30.])) assert np.all(np.isclose(q.transform, [[0.92541658, -0.31879578, -0.20487413], [0.16317591, 0.82317294, -0.54383814], [0.34202014, 0.46984631, 0.81379768]])) def test_rotate_x_to_vec_regress(): """Note that truth values are just results from original code in Ska.quatutil. They have not been independently validated""" vec = [1, 2, 3] q = Quat.rotate_x_to_vec(vec) # method='radec', default assert np.allclose(q.q, [0.2358142, -0.38155539, 0.4698775, 0.76027777]) q = Quat.rotate_x_to_vec(vec, method='shortest') assert np.allclose(q.q, [0., -0.50362718, 0.33575146, 0.79600918]) q = Quat.rotate_x_to_vec(vec, method='keep_z') assert np.allclose(q.q, [-0.16269544, -0.56161937, 0.22572786, 0.77920525]) @pytest.mark.parametrize('method', ('keep_z', 'shortest', 'radec')) @pytest.mark.parametrize('attr', ['q', 'equatorial', 'transform'])
32.714719
91
0.588339
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np import pytest import pickle import os from .. import Quat, normalize def indices(t): import itertools for k in itertools.product(*[range(i) for i in t]): yield k def normalize_angles(x, xmin, xmax): while np.any(x >= xmax): x -= np.where(x > xmax, 360, 0) while np.any(x < xmin): x += np.where(x < xmin, 360, 0) ra = 10. dec = 20. roll = 30. q0 = Quat([ra, dec, roll]) equatorial_23 = np.array([[[10, 20, 30], [10, 20, -30], [10, -60, 30]], [[10, 20, 0], [10, 50, 30], [10, -50, -30]]], dtype=float) q_23 = np.zeros(equatorial_23[..., 0].shape + (4,)) for _i, _j in indices(equatorial_23.shape[:-1]): q_23[_i, _j] = Quat(equatorial_23[_i, _j]).q transform_23 = np.zeros(equatorial_23[..., 0].shape + (3, 3)) for _i, _j in indices(transform_23.shape[:-2]): transform_23[_i, _j] = Quat(equatorial_23[_i, _j]).transform def test_shape(): q = Quat(q=np.zeros(4,)) assert q.shape == () with pytest.raises(AttributeError): q.shape = (4,) def test_init_exceptions(): with pytest.raises(TypeError): _ = Quat(q=np.zeros((3, ))) # old-style API, wrong shape with pytest.raises(TypeError): _ = Quat(equatorial=np.zeros((4, ))) # old-style API, wrong shape with pytest.raises(TypeError): _ = Quat(transform=np.zeros((4, ))) # old-style API, wrong shape with pytest.raises(TypeError): _ = Quat(np.zeros((2, ))) # old-style API, wrong shape with pytest.raises(TypeError): _ = Quat(np.zeros((5, ))) # old-style API, wrong shape with pytest.raises(TypeError): _ = Quat(equatorial_23) # old-style API, wrong shape with pytest.raises(TypeError): _ = Quat(q_23) # old-style API, wrong shape with pytest.raises(TypeError): _ = Quat(transform_23) # old-style API, wrong shape with pytest.raises(ValueError): _ = Quat(q=np.zeros(4), transform=np.zeros((3, 3))) # too many arguments with pytest.raises(ValueError): _ = Quat(q=np.zeros(4), equatorial=np.zeros(3)) # too many arguments with pytest.raises(ValueError): _ = Quat(equatorial=np.zeros(3), transform=np.zeros((3, 3))) # too many arguments with pytest.raises(ValueError): # too many arguments _ = Quat(q=np.zeros(4), transform=np.zeros((3, 3)), equatorial=np.zeros(3)) with pytest.raises(ValueError): _ = Quat(q=[[[1., 0., 0., 1.]]]) # q not normalized with pytest.raises(ValueError): _ = Quat([0, 1, 's']) # could not convert string to float def test_from_q(): q = [0.26853582, -0.14487813, 0.12767944, 0.94371436] q1 = Quat(q) q2 = Quat(q=q) q3 = Quat(q1) q = np.array(q) assert np.all(q1.q == q) assert np.all(q2.q == q) assert np.all(q3.q == q) def test_from_eq(): q = Quat([ra, dec, roll]) assert np.allclose(q.q[0], 0.26853582) assert np.allclose(q.q[1], -0.14487813) assert np.allclose(q.q[2], 0.12767944) assert np.allclose(q.q[3], 0.94371436) assert np.allclose(q.roll0, 30) assert np.allclose(q.ra0, 10) assert q.pitch == -q.dec assert q.yaw == q.ra0 q1 = Quat(equatorial=[ra, dec, roll]) assert np.all(q1.q == q.q) def test_from_eq_vectorized(): # the following line would give unexpected results # because the input is interpreted as a (non-vectorized) transform # the shape of the input is (3,3) # q = Quat(equatorial_23[0]) # this is the proper way: q = Quat(equatorial=equatorial_23[0]) assert q.q.shape == (3, 4) for i in indices(q.shape): # check that Quat(equatorial).q[i] == Quat(equatorial[i]).q assert np.all(q.q[i] == Quat(equatorial_23[0][i]).q) q = Quat(equatorial=equatorial_23) assert q.q.shape == (2, 3, 4) for i in indices(q.shape): # check that Quat(equatorial).q[i] == Quat(equatorial[i]).q assert np.all(q.q[i] == Quat(equatorial_23[i]).q) # test init from list q = Quat(equatorial=[ra, dec, roll]) assert np.all(q.q == q0.q) q = Quat(equatorial=equatorial_23) assert np.all(q.q == q_23) assert np.all(q.equatorial == equatorial_23) assert np.all(q.transform == transform_23) def test_from_eq_shapes(): q = Quat(equatorial=[10., 20., 30.]) assert np.array(q.ra0).shape == () assert np.array(q.roll0).shape == () assert np.array(q.ra).shape == () assert np.array(q.dec).shape == () assert np.array(q.roll).shape == () assert np.array(q.yaw).shape == () assert np.array(q.pitch).shape == () assert q.q.shape == (4, ) assert q.equatorial.shape == (3, ) assert q.transform.shape == (3, 3) q = Quat(equatorial=equatorial_23[:1, :1]) assert q.ra0.shape == (1, 1) assert q.roll0.shape == (1, 1) assert q.ra.shape == (1, 1) assert q.dec.shape == (1, 1) assert q.roll.shape == (1, 1) assert q.yaw.shape == (1, 1) assert q.pitch.shape == (1, 1) assert q.q.shape == (1, 1, 4) assert q.equatorial.shape == (1, 1, 3) assert q.transform.shape == (1, 1, 3, 3) def test_transform_from_eq(): q = Quat(equatorial=equatorial_23) assert q.transform.shape == (2, 3, 3, 3) for i in indices(q.shape): # check that # Quat(equatorial).transform[i] == Quat(equatorial[i]).transform assert np.all(q.transform[i] == Quat(equatorial_23[i]).transform) def test_from_transform(): """Initialize from inverse of q0 via transform matrix""" q = Quat(q0.transform.transpose()) assert np.allclose(q.q[0], -0.26853582) assert np.allclose(q.q[1], 0.14487813) assert np.allclose(q.q[2], -0.12767944) assert np.allclose(q.q[3], 0.94371436) q = Quat(q0.transform) assert np.allclose(q.roll0, 30) assert np.allclose(q.ra0, 10) q1 = Quat(transform=q0.transform) assert np.all(q1.q == q.q) def test_from_transform_vectorized(): q = Quat(transform=transform_23) assert q.q.shape == (2, 3, 4) for i in indices(q.shape): # check that Quat(transform).q[i] == Quat(transform[i]).q assert np.all(q.q[i] == Quat(transform=transform_23[i]).q) q = Quat(transform=transform_23[:1, :1]) assert q.q.shape == (1, 1, 4) t = [[[[9.25416578e-01, -3.18795778e-01, -2.04874129e-01], [1.63175911e-01, 8.23172945e-01, -5.43838142e-01], [3.42020143e-01, 4.69846310e-01, 8.13797681e-01]]]] q = Quat(transform=t) assert q.q.shape == (1, 1, 4) q = Quat(transform=transform_23) assert np.allclose(q.q, q_23) # to compare roll, it has to be normalized to within a fixed angular range (0, 360). eq = np.array(q.equatorial) normalize_angles(eq[..., -1], 0, 360) eq_23 = np.array(equatorial_23) normalize_angles(eq_23[..., -1], 0, 360) assert np.allclose(eq, eq_23) assert np.allclose(q.transform, transform_23) def test_eq_from_transform(): # this raises 'Unexpected negative norm' exception due to roundoff in copy/paste above # q = Quat(transform=transform_23) # assert q.equatorial.shape == (2, 3, 3) # assert np.allclose(q.equatorial, equatorial_23) t = np.zeros((4, 5, 3, 3)) t[:] = q0.transform[np.newaxis][np.newaxis] q = Quat(transform=t) assert np.allclose(q.roll0, 30) assert np.allclose(q.ra0, 10) assert q.equatorial.shape == (4, 5, 3) def test_from_q_vectorized(): q = Quat(q=q_23) assert q.shape == (2, 3) # this also tests that quaternions with negative scalar component are flipped flip = np.sign(q_23[..., -1]).reshape((2, 3, 1)) assert np.allclose(q.q, q_23 * flip) # to compare roll, it has to be normalized to within a fixed angular range (0, 360). eq = np.array(q.equatorial) normalize_angles(eq[..., -1], 0, 360) eq_23 = np.array(equatorial_23) normalize_angles(eq_23[..., -1], 0, 360) assert np.allclose(eq, eq_23, rtol=0) assert np.allclose(q.transform, transform_23, rtol=0) q = Quat(q=q_23[0]) assert q.shape == (3,) q = Quat(q=q_23[:1, :1]) assert q.shape == (1, 1) def test_inv_eq(): q = Quat(q0.equatorial) t = q.transform tinv = q.inv().transform t_tinv = np.dot(t, tinv) for v1, v2 in zip(t_tinv.flatten(), [1, 0, 0, 0, 1, 0, 0, 0, 1]): assert np.allclose(v1, v2) def test_inv_q(): q = Quat(q0.q) assert q.q.shape == q.inv().q.shape t = q.transform tinv = q.inv().transform t_tinv = np.dot(t, tinv) for v1, v2 in zip(t_tinv.flatten(), [1, 0, 0, 0, 1, 0, 0, 0, 1]): assert np.allclose(v1, v2) def test_inv_vectorized(): q1 = Quat(q=q_23[:1, :1]) assert q1.q.shape == (1, 1, 4) q1_inv = q1.inv() assert q1_inv.q.shape == q1.q.shape for i in indices(q1.shape): # check that Quat(q).inv().q[i] == Quat(q[i]).inv().q assert np.all(q1_inv.q[i] == Quat(q=q1.q[i]).inv().q) def test_dq(): q1 = Quat((20, 30, 0)) q2 = Quat((20, 30.1, 1)) dq = q1.dq(q2) assert np.allclose(dq.equatorial, (0, 0.1, 1)) # same from array instead of Quat dq = q1.dq(q2.q) assert np.allclose(dq.equatorial, (0, 0.1, 1)) def test_dq_vectorized(): q1 = Quat(q=q_23[:1, :2]) q2 = Quat(q=q_23[1:, 1:]) assert q1.q.shape == q2.q.shape dq = q1.dq(q2) assert dq.q.shape == q1.q.shape # shape (1,2,4) # same but with array argument instead of Quat dq2 = q1.dq(q=q2.q) assert dq2.q.shape == dq.q.shape assert np.all(dq2.q == dq.q) for i in indices(q1.shape): # check that Quat(q1).dq(q2).q[i] == Quat(q1[i]).dq(q2[i]).q assert np.all(dq.q[i] == Quat(q=q1.q[i]).dq(Quat(q=q2.q[i])).q) # note that both quaternions have same _internal_ shape, should this fail? q1 = Quat((20, 30, 0)) q2 = Quat(equatorial=[[20, 30.1, 1]]) assert np.allclose(q1.dq(q2).equatorial, [[0, 0.1, 1]]) assert np.allclose(q1.dq(q=q2.q).equatorial, [[0, 0.1, 1]]) assert np.allclose(q1.dq(equatorial=q2.equatorial).equatorial, [[0, 0.1, 1]]) assert np.allclose(q1.dq(transform=q2.transform).equatorial, [[0, 0.1, 1]]) # and the interface is the same as the constructor: with pytest.raises(TypeError): q1.dq(q2.q) with pytest.raises(TypeError): q1.dq(q2.equatorial) with pytest.raises(TypeError): q1.dq(q2.transform) def test_vector_to_scalar_correspondence(): """ Simple test that all possible transform pathways give the same answer when done in vectorized form as they do for the scalar version. """ atol = 1e-12 # Input equatorial has roll not in 0:360, so fix that for comparisons. eq_23 = equatorial_23.copy() normalize_angles(eq_23[..., -1], 0, 360) # Compare vectorized computations for all possible input/output combos # with the same for the scalar calculation. q = Quat(equatorial=equatorial_23) assert np.all(q.q == q_23) assert np.all(q.equatorial == equatorial_23) assert np.all(q.transform == transform_23) q = Quat(q=q_23) assert np.all(q.q == q_23) assert np.allclose(q.equatorial, eq_23, rtol=0, atol=atol) assert np.allclose(q.transform, transform_23, rtol=0, atol=atol) q = Quat(transform=transform_23) assert np.allclose(q.q, q_23, rtol=0, atol=atol) assert np.allclose(q.equatorial, eq_23, rtol=0, atol=atol) assert np.all(q.transform == transform_23) def test_ra0_roll0(): q = Quat(Quat([-1, 0, -2]).q) assert np.allclose(q.ra, 359) assert np.allclose(q.ra0, -1) assert np.allclose(q.roll, 358) assert np.allclose(q.roll0, -2) def test_repr(): q = Quat([1, 2, 3]) assert repr(q) == '<Quat q1=0.02632421 q2=-0.01721736 q3=0.00917905 q4=0.99946303>' class SubQuat(Quat): pass q = SubQuat([1, 2, 3]) assert repr(q) == '<SubQuat q1=0.02632421 q2=-0.01721736 q3=0.00917905 q4=0.99946303>' q = Quat(equatorial=[[1, 2, 3]]) assert repr(q) == 'Quat(array([[ 0.02632421, -0.01721736, 0.00917905, 0.99946303]]))' def test_numeric_underflow(): """ Test new code (below) for numeric issue https://github.com/sot/Quaternion/issues/1. If this code is not included then the test fails with a MathDomainError:: one_minus_xn2 = 1 - xn**2 if one_minus_xn2 < 0: if one_minus_xn2 < -1e-12: raise ValueError('Unexpected negative norm: {}'.format(one_minus_xn2)) one_minus_xn2 = 0 """ quat = Quat((0, 0, 0)) angle = 0 while angle < 360: q = Quat((0, angle, 0)) quat = q * quat _ = quat.equatorial angle += 0.1 def test_div_mult(): q1 = Quat((1, 2, 3)) q2 = Quat((10, 20, 30)) q12d = q1 / q2 assert q1.shape == q12d.shape assert q1.shape == q1.inv().shape q12m = q1 * q2.inv() assert q1.shape == q12m.shape assert np.all(q12d.q == q12m.q) q3 = Quat(equatorial=[[10, 20, 30]]) assert (q1 * q3).shape != q1.shape assert (q1 * q3).shape == q3.shape def test_mult_vectorized(): q1 = Quat(q=q_23[:1, :2]) # (shape (2,1) q2 = Quat(q=q_23[1:, 1:]) # (shape (2,1) assert q1.q.shape == q2.q.shape q12 = q1 * q2 assert q12.q.shape == q1.q.shape def test_normalize(): a = [[[1., 0., 0., 1.]]] b = normalize(a) assert np.isclose(np.sum(b**2), 1) def test_copy(): # data members must be copies so they are not modified by accident q = np.array(q_23[0, 0]) q1 = Quat(q=q) q[-1] = 0 assert q1.q[-1] != 0 # this one passes t = np.array(transform_23) q1 = Quat(transform=t) t[-1] = 0 assert not np.all(q1.transform == t) # this one passes eq = np.array([10, 90, 30]) q1 = Quat(equatorial=eq) eq[-1] = 0 assert not np.all(q1.equatorial == eq) def test_format(): # this is to test standard usage downstream q = Quat(q_23[0, 0]) print(f'ra={q.ra:.5f}, dec={q.dec:.5f}, roll={q.roll:.5f}') def test_scalar_attribute_types(): q = Quat(equatorial=[10, 20, 30]) attrs = ['ra', 'dec', 'roll', 'ra0', 'roll0', 'pitch', 'yaw', 'transform', 'q'] types = [np.float64] * 7 + [np.ndarray] * 2 # All returned as scalars for attr, typ in zip(attrs, types): assert type(getattr(q, attr)) is typ q2 = Quat(transform=q.transform.astype(np.float32)) for attr, typ in zip(attrs, types): assert type(getattr(q2, attr)) is typ q2 = Quat(q=q.q.astype(np.float32)) for attr, typ in zip(attrs, types): assert type(getattr(q, attr)) is typ def test_mult_and_dq_broadcasted(): """Test mult and delta quat of Quats with different but broadcastable shapes. """ q2 = Quat(equatorial=np.arange(18).reshape(3, 2, 3)) q1 = Quat(equatorial=[[10, 20, 30], [40, 50, 60]]) q0 = Quat(equatorial=[10, 20, 30]) # (3,2) * () = (3,2) q20 = q2 * q0 dq20 = q2.dq(q0) assert q20.shape == (3, 2) assert dq20.shape == (3, 2) for ii in range(3): for jj in range(2): qq = q2[ii, jj] * q0 dq = q2[ii, jj].dq(q0) assert np.allclose(qq.q, q20.q[ii, jj]) assert np.allclose(dq.q, dq20.q[ii, jj]) # (3,2) * (2,) = (3,2) q21 = q2 * q1 dq21 = q2.dq(q1) assert q21.shape == (3, 2) assert dq21.shape == (3, 2) for ii in range(3): for jj in range(2): qq = q2[ii, jj] * q1[jj] dq = q2[ii, jj].dq(q1[jj]) assert np.allclose(qq.q, q21.q[ii, jj]) assert np.allclose(dq.q, dq21.q[ii, jj]) def test_array_attribute_types(): q = Quat(equatorial=[[10, 20, 30]]) # 1-d attrs = ['ra', 'dec', 'roll', 'ra0', 'roll0', 'pitch', 'yaw', 'transform', 'q'] shapes = [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1, 3, 3), (1, 4)] # All returned as shape (1,) array for attr, shape in zip(attrs, shapes): assert type(getattr(q, attr)) is np.ndarray assert getattr(q, attr).shape == shape q2 = Quat(transform=q.transform.astype(np.float32)) for attr, shape in zip(attrs, shapes): assert type(getattr(q2, attr)) is np.ndarray assert getattr(q, attr).shape == shape q2 = Quat(q=q.q.astype(np.float32)) for attr, shape in zip(attrs, shapes): assert type(getattr(q, attr)) is np.ndarray assert getattr(q, attr).shape == shape def test_pickle(): """ Pickle file generated using Quaternion v3.4.1: from Quaternion import Quat import pickle q = Quat([10., 20., 30.]) quats = [Quat(q.q), Quat(q.transform), Quat(q.equatorial)] quats.append(q) with open('quaternion-v3.4.1.pkl', 'wb') as f: pickle.dump(quats, f) """ # testing we can unpickle older versions filename = os.path.join(os.path.dirname(__file__), 'data', 'quaternion-v3.4.1.pkl') with open(filename, 'rb') as f: quaternions = pickle.load(f) for q in quaternions: assert np.all(np.isclose(q.q, [0.26853582, -0.14487813, 0.12767944, 0.94371436])) assert np.all(np.isclose(q.equatorial, [10., 20., 30.])) assert np.all(np.isclose(q.transform, [[0.92541658, -0.31879578, -0.20487413], [0.16317591, 0.82317294, -0.54383814], [0.34202014, 0.46984631, 0.81379768]])) def test_init_quat_from_attitude(): # Basic tests for Quat.from_attitude q = Quat.from_attitude([Quat([0, 1, 2]), Quat([3, 4, 5])]) # 1-d list of Quat assert np.allclose(q.equatorial, [[0, 1, 2], [3, 4, 5]]) # From existing Quat q2 = Quat.from_attitude(q) assert np.all(q.q == q2.q) assert q is not q2 # Normal Quat initializer: 3-element list implies equatorial q = Quat.from_attitude([10, 20, 30]) assert np.allclose(q.equatorial, [10, 20, 30]) # 2-d list of Quat q = Quat.from_attitude([[Quat([0, 1, 2]), Quat([3, 4, 5])]]) assert np.allclose(q.equatorial, [[[0, 1, 2], [3, 4, 5]]]) # 1-d list of equatorial floats q = Quat.from_attitude([[0, 1, 2], [3, 4, 5]]) assert np.allclose(q.equatorial, [[[0, 1, 2], [3, 4, 5]]]) # Heterogenous list of floats q = Quat.from_attitude([[0, 1, 2], [0, 1, 0, 0]]) assert np.allclose(q.equatorial, [[0, 1, 2], [180, 0, 180]]) # Bad 1-d list of equatorial floats with pytest.raises(ValueError, match="Float input must be a Nx3 or Nx4 array"): q = Quat.from_attitude([[0, 1, 2, 4, 5], [3, 4, 5, 6, 7]]) # 1-d list of 4-vectors q_list = [[0, 0, 1, 0], [0, 1, 0, 0]] q = Quat.from_attitude(q_list) assert np.allclose(q.q, q_list) # Bad input with pytest.raises(ValueError, match="Unable to initialize Quat from 'blah'"): Quat.from_attitude('blah') def test_rotate_x_to_vec_regress(): """Note that truth values are just results from original code in Ska.quatutil. They have not been independently validated""" vec = [1, 2, 3] q = Quat.rotate_x_to_vec(vec) # method='radec', default assert np.allclose(q.q, [0.2358142, -0.38155539, 0.4698775, 0.76027777]) q = Quat.rotate_x_to_vec(vec, method='shortest') assert np.allclose(q.q, [0., -0.50362718, 0.33575146, 0.79600918]) q = Quat.rotate_x_to_vec(vec, method='keep_z') assert np.allclose(q.q, [-0.16269544, -0.56161937, 0.22572786, 0.77920525]) @pytest.mark.parametrize('method', ('keep_z', 'shortest', 'radec')) def test_rotate_x_to_vec_functional(method): vecs = np.random.random((100, 3)) - 0.5 for vec in vecs: vec = vec / np.sqrt(np.sum(vec ** 2)) q = Quat.rotate_x_to_vec(vec, method) vec1 = np.dot(q.transform, [1.0, 0, 0]) assert np.allclose(vec, vec1) if method == 'radec': assert np.isclose(q.roll, 0.0) elif method == 'keep_z': vec1 = np.dot(q.transform, [0, 0, 1.0]) assert np.isclose(vec1[1], 0.0) def test_rotate_x_to_vec_bad_method(): with pytest.raises(ValueError, match='method must be one of'): Quat.rotate_x_to_vec([1, 2, 3], 'not-a-method') def test_rotate_about_vec(): q = Quat([10, 20, 30]) q2 = q.rotate_about_vec([0, 0, 10], 25) assert np.allclose(q2.equatorial, [10 + 25, 20, 30]) q2 = q.rotate_about_vec([-10, 0, 0], 180) assert np.allclose(q2.equatorial, [350., -20., 210.]) def test_rotate_about_vec_exceptions(): q1 = Quat([10, 20, 30]) q2 = Quat(equatorial=[[10, 20, 30], [1, 2, 3]]) with pytest.raises(ValueError, match='vec must be a single 3-vector'): q1.rotate_about_vec([[1, 2, 3], [4, 5, 6]], 25) with pytest.raises(ValueError, match='alpha must be a scalar'): q1.rotate_about_vec([1, 2, 3], [25, 50]) with pytest.raises(ValueError, match='quaternion must be a scalar'): q2.rotate_about_vec([1, 2, 3], 25) @pytest.mark.parametrize('attr', ['q', 'equatorial', 'transform']) def test_setting_different_shape(attr): q0 = Quat([1, 2, 3]) q1 = Quat(equatorial=[[3, 1, 2], [4, 5, 6]]) assert q1.shape == (2,) val = getattr(q1, attr) setattr(q0, attr, val) assert q0.shape == q1.shape assert np.all(getattr(q0, attr) == getattr(q1, attr))
15,136
0
734
65412ef002af7b1dc9bc280643785461f236172e
3,240
py
Python
gdf_tests/test_config_file.py
dunkgray/gdf
7b39f0c90cf63d501b36ea9d754269616d79e0d4
[ "Apache-2.0" ]
7
2015-08-27T09:20:55.000Z
2019-06-27T14:00:11.000Z
gdf_tests/test_config_file.py
alex-ip/gdf
7b39f0c90cf63d501b36ea9d754269616d79e0d4
[ "Apache-2.0" ]
null
null
null
gdf_tests/test_config_file.py
alex-ip/gdf
7b39f0c90cf63d501b36ea9d754269616d79e0d4
[ "Apache-2.0" ]
5
2015-05-13T05:58:13.000Z
2019-12-09T00:36:11.000Z
#!/usr/bin/env python #=============================================================================== # Copyright (c) 2014 Geoscience Australia # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither Geoscience Australia nor the names of its contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #=============================================================================== ''' Created on 12/03/2015 @author: Alex Ip Tests for the gdf._ConfigFile.py module. ''' import os import unittest from gdf._config_file import ConfigFile # # Test cases # # pylint: disable=too-many-public-methods # # Disabled to avoid complaints about the unittest.TestCase class. # class TestConfigFile(unittest.TestCase): """Unit tests for utility functions.""" MODULE = 'gdf._config_file' SUITE = 'TestConfigFile' def test_ConfigFile(self): "Test ConfigFile constructor" # Default config file should be ../gdf/gdf_default.conf default_config_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'gdf', 'gdf_default.conf') config_file_object = ConfigFile(default_config_file) assert config_file_object.path == os.path.abspath(default_config_file), 'path property is not set correctly' # # Define test suites # def test_suite(): """Returns a test suite of all the tests in this module.""" test_classes = [TestConfigFile ] suite_list = map(unittest.defaultTestLoader.loadTestsFromTestCase, test_classes) suite = unittest.TestSuite(suite_list) return suite # Define main function # # Run unit tests if in __main__ # if __name__ == '__main__': main()
34.83871
117
0.671605
#!/usr/bin/env python #=============================================================================== # Copyright (c) 2014 Geoscience Australia # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither Geoscience Australia nor the names of its contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #=============================================================================== ''' Created on 12/03/2015 @author: Alex Ip Tests for the gdf._ConfigFile.py module. ''' import os import unittest from gdf._config_file import ConfigFile # # Test cases # # pylint: disable=too-many-public-methods # # Disabled to avoid complaints about the unittest.TestCase class. # class TestConfigFile(unittest.TestCase): """Unit tests for utility functions.""" MODULE = 'gdf._config_file' SUITE = 'TestConfigFile' def test_ConfigFile(self): "Test ConfigFile constructor" # Default config file should be ../gdf/gdf_default.conf default_config_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'gdf', 'gdf_default.conf') config_file_object = ConfigFile(default_config_file) assert config_file_object.path == os.path.abspath(default_config_file), 'path property is not set correctly' # # Define test suites # def test_suite(): """Returns a test suite of all the tests in this module.""" test_classes = [TestConfigFile ] suite_list = map(unittest.defaultTestLoader.loadTestsFromTestCase, test_classes) suite = unittest.TestSuite(suite_list) return suite # Define main function def main(): unittest.TextTestRunner(verbosity=2).run(test_suite()) # # Run unit tests if in __main__ # if __name__ == '__main__': main()
50
0
23
9b3154638b0c846a8de9d8e99c8b465693e7cb4f
250
py
Python
eunice012716/Week1/ch2/2.6/exercise2.py
coookie89/Intern-Training
6e3b26edfee5bdcc98dd5ac05d35cef125778ad5
[ "MIT" ]
1
2021-08-24T12:14:46.000Z
2021-08-24T12:14:46.000Z
eunice012716/Week1/ch2/2.6/exercise2.py
coookie89/Intern-Training
6e3b26edfee5bdcc98dd5ac05d35cef125778ad5
[ "MIT" ]
14
2021-07-09T07:48:35.000Z
2021-08-19T03:06:31.000Z
eunice012716/Week1/ch2/2.6/exercise2.py
coookie89/Intern-Training
6e3b26edfee5bdcc98dd5ac05d35cef125778ad5
[ "MIT" ]
11
2021-07-09T07:35:24.000Z
2021-08-15T07:19:43.000Z
if __name__ == "__main__": print("The upper bound of P(A∪B) = P(A) + P(B)\n") print("The lower bound of P(A∪B) = max(P(A), P(B))\n") print("The upper bound of P(A∩B) = max(P(A), P(B))\n") print("The lower bound of P(A∩B) = 0\n")
41.666667
59
0.532
if __name__ == "__main__": print("The upper bound of P(A∪B) = P(A) + P(B)\n") print("The lower bound of P(A∪B) = max(P(A), P(B))\n") print("The upper bound of P(A∩B) = max(P(A), P(B))\n") print("The lower bound of P(A∩B) = 0\n")
0
0
0
a2103083f0f7d54ec8154290af8a153fcc08a0cd
1,365
py
Python
tests/test_pype_flowgraph.py
Mynti207/TimeDB
08e72c4e237bfe8ee0642179cdc6ccd570a52550
[ "MIT" ]
null
null
null
tests/test_pype_flowgraph.py
Mynti207/TimeDB
08e72c4e237bfe8ee0642179cdc6ccd570a52550
[ "MIT" ]
null
null
null
tests/test_pype_flowgraph.py
Mynti207/TimeDB
08e72c4e237bfe8ee0642179cdc6ccd570a52550
[ "MIT" ]
null
null
null
import pytest from pype import * __author__ = "Mynti207" __copyright__ = "Mynti207" __license__ = "mit"
26.25
72
0.651282
import pytest from pype import * __author__ = "Mynti207" __copyright__ = "Mynti207" __license__ = "mit" def test_flowgraph(): # create flowgraph and nodes FG = fgir.Flowgraph("standardize") FG.new_node(FGNodeType.unknown, None) FG.new_node(FGNodeType.unknown, 1) FG.new_node(FGNodeType.unknown, 2) FG.new_node(FGNodeType.unknown, 3) # add inputs and outputs FG.add_input('@N0') FG.add_output('@N3') # set variables FG.set_var('N0', '@N0') FG.set_var('N3', '@N3') # get variables assert FG.get_var('N0') == '@N0' assert FG.get_var('N3') == '@N3' # check topological sorts assert sorted(FG.topological_sort()) == ['@N0', '@N1', '@N2', '@N3'] # check dotfile FG.dotfile() # note: order changes with each run due to hashing # create FGIR FGIR = fgir.FGIR() FGIR.__setitem__('FG', FG) assert isinstance(FGIR.__getitem__('FG'), Flowgraph) # check node passes FGIR.node_pass(optimize.NodeOptimization()) FGIR.topological_node_pass(optimize.TopologicalNodeOptimization()) # check representations # note: exact memory location will change assert repr(FG)[:30] == '<pype.fgir.Flowgraph object at' assert repr(FG.get_var('N0')) == "'@N0'" test = FG.new_node(FGNodeType.unknown, 3) assert repr(test) == '<FGNodeType.unknown @N4<= : 3>'
1,236
0
23
06b9377e2c1fca5b77db45fb9af0019cb2aaff14
2,268
py
Python
.kodi/addons/script.ftvguide/strings.py
C6SUMMER/allinclusive-kodi-pi
8baf247c79526849c640c6e56ca57a708a65bd11
[ "Apache-2.0" ]
null
null
null
.kodi/addons/script.ftvguide/strings.py
C6SUMMER/allinclusive-kodi-pi
8baf247c79526849c640c6e56ca57a708a65bd11
[ "Apache-2.0" ]
null
null
null
.kodi/addons/script.ftvguide/strings.py
C6SUMMER/allinclusive-kodi-pi
8baf247c79526849c640c6e56ca57a708a65bd11
[ "Apache-2.0" ]
2
2018-04-17T17:34:39.000Z
2020-07-26T03:43:33.000Z
# -*- coding: utf-8 -*- # # Copyright (C) 2012 Tommy Winther # http://tommy.winther.nu # # Modified for FTV Guide (09/2014 onwards) # by Thomas Geppert [bluezed] - bluezed.apps@gmail.com # # This Program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This Program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this Program; see the file LICENSE.txt. If not, write to # the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. # http://www.gnu.org/copyleft/gpl.html # import xbmcaddon ADDON = xbmcaddon.Addon(id = 'script.ftvguide') NO_DESCRIPTION = 30000 CALCULATING_REMAINING_TIME = 30002 TIME_LEFT = 30003 BACKGROUND_UPDATE_IN_PROGRESS = 30004 NO_PROGRAM_AVAILABLE = 30009 NO_STREAM_AVAILABLE_TITLE = 30100 NO_STREAM_AVAILABLE_LINE1 = 30101 NO_STREAM_AVAILABLE_LINE2 = 30102 CLEAR_CACHE = 30104 CLEAR_NOTIFICATIONS = 30108 DONE = 30105 LOAD_ERROR_TITLE = 30150 LOAD_ERROR_LINE1 = 30151 LOAD_ERROR_LINE2 = 30152 CONFIGURATION_ERROR_LINE2 = 30153 SKIN_ERROR_LINE1 = 30154 SKIN_ERROR_LINE2 = 30155 SKIN_ERROR_LINE3 = 30156 NOTIFICATION_5_MINS = 30200 NOTIFICATION_NOW = 30201 WATCH_CHANNEL = 30300 REMIND_PROGRAM = 30301 DONT_REMIND_PROGRAM = 30302 CHOOSE_STRM_FILE = 30304 REMOVE_STRM_FILE = 30306 PREVIEW_STREAM = 30604 STOP_PREVIEW = 30607 WEEBTV_WEBTV_MISSING_1 = 30802 WEEBTV_WEBTV_MISSING_2 = 30803 WEEBTV_WEBTV_MISSING_3 = 30804 DATABASE_SCHEMA_ERROR_1 = 30157 DATABASE_SCHEMA_ERROR_2 = 30158 DATABASE_SCHEMA_ERROR_3 = 30159 FETCH_ERROR_TITLE = 31000 FETCH_ERROR_LINE1 = 31001 FETCH_ERROR_LINE2 = 31002
28
73
0.745591
# -*- coding: utf-8 -*- # # Copyright (C) 2012 Tommy Winther # http://tommy.winther.nu # # Modified for FTV Guide (09/2014 onwards) # by Thomas Geppert [bluezed] - bluezed.apps@gmail.com # # This Program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This Program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this Program; see the file LICENSE.txt. If not, write to # the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. # http://www.gnu.org/copyleft/gpl.html # import xbmcaddon ADDON = xbmcaddon.Addon(id = 'script.ftvguide') NO_DESCRIPTION = 30000 CALCULATING_REMAINING_TIME = 30002 TIME_LEFT = 30003 BACKGROUND_UPDATE_IN_PROGRESS = 30004 NO_PROGRAM_AVAILABLE = 30009 NO_STREAM_AVAILABLE_TITLE = 30100 NO_STREAM_AVAILABLE_LINE1 = 30101 NO_STREAM_AVAILABLE_LINE2 = 30102 CLEAR_CACHE = 30104 CLEAR_NOTIFICATIONS = 30108 DONE = 30105 LOAD_ERROR_TITLE = 30150 LOAD_ERROR_LINE1 = 30151 LOAD_ERROR_LINE2 = 30152 CONFIGURATION_ERROR_LINE2 = 30153 SKIN_ERROR_LINE1 = 30154 SKIN_ERROR_LINE2 = 30155 SKIN_ERROR_LINE3 = 30156 NOTIFICATION_5_MINS = 30200 NOTIFICATION_NOW = 30201 WATCH_CHANNEL = 30300 REMIND_PROGRAM = 30301 DONT_REMIND_PROGRAM = 30302 CHOOSE_STRM_FILE = 30304 REMOVE_STRM_FILE = 30306 PREVIEW_STREAM = 30604 STOP_PREVIEW = 30607 WEEBTV_WEBTV_MISSING_1 = 30802 WEEBTV_WEBTV_MISSING_2 = 30803 WEEBTV_WEBTV_MISSING_3 = 30804 DATABASE_SCHEMA_ERROR_1 = 30157 DATABASE_SCHEMA_ERROR_2 = 30158 DATABASE_SCHEMA_ERROR_3 = 30159 FETCH_ERROR_TITLE = 31000 FETCH_ERROR_LINE1 = 31001 FETCH_ERROR_LINE2 = 31002 def strings(id, replacements = None): string = ADDON.getLocalizedString(id) if replacements is not None: return string % replacements else: return string
165
0
24
40633883c1f46469abf4e2108447cf8284f80196
921
py
Python
cvpods/utils/imports.py
0x4f5da2/BorderDet
a3bdcb2e62b9a395075963b9d400bc2109463d22
[ "Apache-2.0" ]
null
null
null
cvpods/utils/imports.py
0x4f5da2/BorderDet
a3bdcb2e62b9a395075963b9d400bc2109463d22
[ "Apache-2.0" ]
null
null
null
cvpods/utils/imports.py
0x4f5da2/BorderDet
a3bdcb2e62b9a395075963b9d400bc2109463d22
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : imports.py @Time : 2020/05/07 23:59:19 @Author : Benjin Zhu @Contact : poodarchu@gmail.com @Last Modified by : Benjin Zhu @Last Modified time : 2020/05/07 23:59:19 ''' import imp def dynamic_import(config_name, config_path): """ Dynamic import a project. Args: config_name (str): module name config_path (str): the dir that contains the .py with this module. Examples:: >>> root = "/data/repos/cvpods_playground/zhubenjin/retinanet/" >>> project = root + "retinanet.res50.fpn.coco.800size.1x.mrcnn_sigmoid" >>> cfg = dynamic_import("config", project).config >>> net = dynamic_import("net", project) """ fp, pth, desc = imp.find_module(config_name, [config_path]) return imp.load_module(config_name, fp, pth, desc)
28.78125
80
0.603692
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : imports.py @Time : 2020/05/07 23:59:19 @Author : Benjin Zhu @Contact : poodarchu@gmail.com @Last Modified by : Benjin Zhu @Last Modified time : 2020/05/07 23:59:19 ''' import imp def dynamic_import(config_name, config_path): """ Dynamic import a project. Args: config_name (str): module name config_path (str): the dir that contains the .py with this module. Examples:: >>> root = "/data/repos/cvpods_playground/zhubenjin/retinanet/" >>> project = root + "retinanet.res50.fpn.coco.800size.1x.mrcnn_sigmoid" >>> cfg = dynamic_import("config", project).config >>> net = dynamic_import("net", project) """ fp, pth, desc = imp.find_module(config_name, [config_path]) return imp.load_module(config_name, fp, pth, desc)
0
0
0
9ea0669177fcaaa99ed69cff6207ee673a129f43
1,224
py
Python
scripts/kernel_load.py
strawberryhacker/cinnamonOS
6eb663123c07c8573a5bd1993f6001f2fbe1ccb7
[ "MIT" ]
24
2020-08-24T18:31:46.000Z
2020-10-25T09:06:57.000Z
scripts/kernel_load.py
strawberryhacker/citrus-kernel
6eb663123c07c8573a5bd1993f6001f2fbe1ccb7
[ "MIT" ]
35
2020-09-19T13:40:58.000Z
2020-10-27T01:21:59.000Z
scripts/kernel_load.py
strawberryhacker/citrusOS
6eb663123c07c8573a5bd1993f6001f2fbe1ccb7
[ "MIT" ]
1
2021-06-01T17:57:14.000Z
2021-06-01T17:57:14.000Z
# Copyright (C) strawberryhacker import os import sys import serial import time from citrus import citrus_packet from citrus import citrus_file from loading import loading_simple from loading import loading_bar # Used for loading a custom application to the CitrusOS and execute it main()
24.48
70
0.65768
# Copyright (C) strawberryhacker import os import sys import serial import time from citrus import citrus_packet from citrus import citrus_file from loading import loading_simple from loading import loading_bar # Used for loading a custom application to the CitrusOS and execute it def main(): start = int(round(time.time() * 1000)) if len(sys.argv) != 3: print("Check parameters") sys.exit() com_port = sys.argv[1] file_path = sys.argv[2] # Just open a new COM port try: s = serial.Serial(port=com_port, \ baudrate=921600, timeout=1) except serial.SerialException as e: print("Cannot open COM port - ", e) sys.exit() packet = citrus_packet(s) loading_bar_simple = loading_simple() loading_bar_simple.set_message("Downloading") file = citrus_file(packet, loading_bar_simple) print("Entering citrus-boot...") packet.send_packet(b'', packet.CMD_RESET) # We just send the file over file.send_file(file_path) stop = int(round(time.time() * 1000)) print("Kernel download complete in", stop - start, "ms") print("Please wait...", end="\r") s.close() print(' ' * 50, end="\r") main()
908
0
23
787c575813c9701765cb7fe3a2ff8e9fd18f93d3
71
py
Python
tests/__init__.py
reclamador/document_clipper
61be44eb023a5e32c8a2886e579dffe4d4d525ee
[ "MIT" ]
3
2017-11-08T12:58:14.000Z
2021-08-29T06:33:24.000Z
tests/__init__.py
reclamador/document_clipper
61be44eb023a5e32c8a2886e579dffe4d4d525ee
[ "MIT" ]
130
2017-11-13T12:46:48.000Z
2022-03-11T23:11:39.000Z
tests/__init__.py
reclamador/document_clipper
61be44eb023a5e32c8a2886e579dffe4d4d525ee
[ "MIT" ]
1
2020-12-03T09:41:06.000Z
2020-12-03T09:41:06.000Z
# -*- coding: utf-8 -*- """Unit test package for document_clipper."""
17.75
45
0.619718
# -*- coding: utf-8 -*- """Unit test package for document_clipper."""
0
0
0
5cee680d31f450c9770021f82d15a3c5b1d83208
92
py
Python
intensity_normalization/normalize/__init__.py
sarthakpati/intensity-normalization
5f2fc9ea3f305a3bd214b6f42fd8b1664a3ecbdc
[ "Apache-2.0" ]
null
null
null
intensity_normalization/normalize/__init__.py
sarthakpati/intensity-normalization
5f2fc9ea3f305a3bd214b6f42fd8b1664a3ecbdc
[ "Apache-2.0" ]
null
null
null
intensity_normalization/normalize/__init__.py
sarthakpati/intensity-normalization
5f2fc9ea3f305a3bd214b6f42fd8b1664a3ecbdc
[ "Apache-2.0" ]
null
null
null
from intensity_normalization.normalize import fcm, gmm, kde, lsq, nyul, whitestripe, zscore
46
91
0.815217
from intensity_normalization.normalize import fcm, gmm, kde, lsq, nyul, whitestripe, zscore
0
0
0
83f608591f706ae143b4aa3d0c9cc32939ff6de2
733
py
Python
blocksec2go/cli/unlock_pin.py
Infineon/secora-blockchain-python-library
1edcd7ae7299a148448a93110fed101f93623303
[ "MIT" ]
2
2021-11-23T13:44:53.000Z
2021-12-06T19:48:51.000Z
blocksec2go/cli/unlock_pin.py
Infineon/secora-blockchain-python-library
1edcd7ae7299a148448a93110fed101f93623303
[ "MIT" ]
null
null
null
blocksec2go/cli/unlock_pin.py
Infineon/secora-blockchain-python-library
1edcd7ae7299a148448a93110fed101f93623303
[ "MIT" ]
1
2020-10-03T08:27:26.000Z
2020-10-03T08:27:26.000Z
import sys import json import argparse from blocksec2go import open_pyscard, CardError from blocksec2go import select_app, unlock_pin, set_pin from blocksec2go.util import bytes_from_hex
30.541667
84
0.736698
import sys import json import argparse from blocksec2go import open_pyscard, CardError from blocksec2go import select_app, unlock_pin, set_pin from blocksec2go.util import bytes_from_hex def _unlock_pin(args): reader = args.reader unlock_pin(reader, args.puk) set_pin(reader, args.new_pin) if args.machine_readable: json.dump({'status': 'success'}, fp=sys.stdout) else: print('OK - unlocked') def add_subcommand(subparsers): parser = subparsers.add_parser('unlock_pin', description='Unlock a locked card') parser.set_defaults(func=_unlock_pin) parser.add_argument('puk', help='PUK to unlock card', type=bytes_from_hex()) parser.add_argument('new_pin', help='New PIN for card')
499
0
46
48a1b66fc9217ad435e82d602fb6b80f644b9382
547
py
Python
main/libdaemon/template.py
RoastVeg/cports
803c7f07af341eb32f791b6ec1f237edb2764bd5
[ "BSD-2-Clause" ]
46
2021-06-10T02:27:32.000Z
2022-03-27T11:33:24.000Z
main/libdaemon/template.py
RoastVeg/cports
803c7f07af341eb32f791b6ec1f237edb2764bd5
[ "BSD-2-Clause" ]
58
2021-07-03T13:58:20.000Z
2022-03-13T16:45:35.000Z
main/libdaemon/template.py
RoastVeg/cports
803c7f07af341eb32f791b6ec1f237edb2764bd5
[ "BSD-2-Clause" ]
6
2021-07-04T10:46:40.000Z
2022-01-09T00:03:59.000Z
pkgname = "libdaemon" pkgver = "0.14" pkgrel = 0 build_style = "gnu_configure" configure_args = ["--disable-lynx"] hostmakedepends = ["pkgconf"] pkgdesc = "Lightweight C library that eases the writing of UNIX daemons" maintainer = "q66 <q66@chimera-linux.org>" license = "LGPL-2.1-or-later" url = "http://0pointer.de/lennart/projects/libdaemon" source = f"{url}/{pkgname}-{pkgver}.tar.gz" sha256 = "fd23eb5f6f986dcc7e708307355ba3289abe03cc381fc47a80bca4a50aa6b834" @subpackage("libdaemon-devel")
32.176471
75
0.751371
pkgname = "libdaemon" pkgver = "0.14" pkgrel = 0 build_style = "gnu_configure" configure_args = ["--disable-lynx"] hostmakedepends = ["pkgconf"] pkgdesc = "Lightweight C library that eases the writing of UNIX daemons" maintainer = "q66 <q66@chimera-linux.org>" license = "LGPL-2.1-or-later" url = "http://0pointer.de/lennart/projects/libdaemon" source = f"{url}/{pkgname}-{pkgver}.tar.gz" sha256 = "fd23eb5f6f986dcc7e708307355ba3289abe03cc381fc47a80bca4a50aa6b834" @subpackage("libdaemon-devel") def _devel(self): return self.default_devel()
28
0
22
688a19a98edd409433c22d157ee58a5e92da91f9
8,287
py
Python
pyQuASAR/pyQuASAR.py
anthony-aylward/pyQuASAR
9fee9817b576615ff4cd96f08cdaa76ddc1a236e
[ "MIT" ]
null
null
null
pyQuASAR/pyQuASAR.py
anthony-aylward/pyQuASAR
9fee9817b576615ff4cd96f08cdaa76ddc1a236e
[ "MIT" ]
null
null
null
pyQuASAR/pyQuASAR.py
anthony-aylward/pyQuASAR
9fee9817b576615ff4cd96f08cdaa76ddc1a236e
[ "MIT" ]
null
null
null
#=============================================================================== # pyQuASAR.py #=============================================================================== # Imports ====================================================================== import funcgenom import gzip import itertools import os import os.path import pipes import subprocess import tempfile from Bio.bgzf import BgzfWriter from pyQuASAR.env import DIR, SNPS_BED_PATH # Constants ==================================================================== GENOTYPE_DICT = {0: ('0/0', '0/1'), 1: ('0/1', '0/0'), 2: ('1/1', '0/0')} # Functions ==================================================================== def write_compressed_pileup(pileup_bytes: bytes, pileup_file_path: str): """Write a compressed QuASAR intermediate pileup to disk Parameters ---------- pileup_bytes : bytes Pileup file as a bytes object pileup_file_path : str File path to write data """ with gzip.open(pileup_file_path, 'wb') as f: f.write(pileup_bytes) def pileup_to_bed( pileup_bytes, snps_bed_path: str = SNPS_BED_PATH, temp_file_dir=None ) -> str: """Convert a pileup to a BED file in memory Parameters ---------- pileup_bytes : bytes Pileup file as a bytes object snps_bed_path : str Path to BED file containing SNPs temp_file_dir directory for temporary files Returns ------- str BED file """ with tempfile.NamedTemporaryFile(dir=temp_file_dir) as temp_file: temp_file_name = temp_file.name t = pipes.Template() for cmd, kind in ( ('less', '--'), ( ( r"awk -v OFS='\t' " "'{ " "if (" "$4>0 " "&& $5 !~ /[^\^][<>]/ " "&& $5 !~ /\+[0-9]+[ACGTNacgtn]+/ " "&& $5 !~ /-[0-9]+[ACGTNacgtn]+/ " "&& $5 !~ /[^\^]\*/" ") " "print $1,$2-1,$2,$3,$4,$5,$6" "}'" ), '--' ), ('sortBed -i stdin', '--'), (f'intersectBed -a stdin -b {snps_bed_path} -wo', '--'), ('cut -f 1-7,11-14', '--'), ): t.append(cmd, kind) f = t.open(temp_file_name, 'w') f.write(pileup_bytes.decode()) f.close() return open(temp_file_name).read() def write_compressed_pileup_bed( pileup_bytes, pileup_bed_path, snps_bed_path=None, temp_file_dir=None ): """Write a compressed QuASAR intermediate pileup.bed file to disk Parameters ---------- pileup_bytes : bytes Pileup file as a bytes object pileup_bed_path : str File path to write data snps_bed_path : str Path to BED file containing SNPs temp_file_dir directory for temporary files """ with gzip.open(pileup_bed_path, 'wt') as f: f.write( pileup_to_bed( pileup_bytes, snps_bed_path=snps_bed_path, temp_file_dir=temp_file_dir ) ) def bed_to_quasar(bed_path): """Convert the pileup.bed file to quasar input format Write the new file to disk next to the input file. Parameters ---------- bed_path Path to a pileup.bed.gz file """ working_dir = os.getcwd() os.chdir(os.path.dirname(bed_path)) subprocess.call( ( 'Rscript', '--vanilla', f'{DIR}/QuASAR/scripts/convertPileupToQuasar.R', os.path.basename(bed_path) ), stdout=subprocess.DEVNULL ) os.chdir(working_dir) def genotype(*input_file_paths): """Run quasar on formatted input files to obtain genotypes Parameters ---------- input_file_paths paths to input files Returns ------- bytes Standard output from QuASAR """ with subprocess.Popen( ( ( 'Rscript', os.path.join(os.path.dirname(__file__), 'QuASAR_genotype.R') ) + tuple(input_file_paths) ), stdout=subprocess.PIPE ) as quasar_genotype: return quasar_genotype.communicate()[0] def generate_allele_dict_items(snps_bed_path: str): """Generate tuples defining an allele dict Parameters ---------- snps_bed_path : str Path to BED file containing SNPs Yields ------ tuple Variant ID and a pair of alleles """ with open(snps_bed_path, 'r') as f: for line in f: chr, _, pos, id, ref, alt, maf = line.split() yield id, (ref, alt) def genotype_to_vcf( genotype_bytes: bytes, sample_name: str = 'SAMPLE', snps_bed_path: str = SNPS_BED_PATH, threshold: float = 0.99, het_only: bool = False, temp_file_dir=None ): """Convert genotype probabilities from QuASAR to VCF format Parameters ---------- genotype_bytes : bytes Standard output from QuASAR as a bytes object sample_name : str Sample name for the VCF file snps_bed_path : str Path to BED file containing SNPs threshold : float Genotype probability threshold for variants to include het_only : bool Include only heterozygous variants if true temp_file_dir directory for temporary files Yields ------ str A line of a VCF file """ yield from ( '##fileformat=VCFv4.0', '##reference=GRCh37', '##INFO=<ID=BUILD,Number=1,Type=Integer,Description="Genome build">', ( '##INFO=' '<ID=GP,Number=3,Type=Float,Description="Genotype probabilities">' ), '##FORMAT=<ID=GT,Number=1,Type=String,Description=Genotype>', '\t'.join( ( '#CHROM', 'POS', 'ID', 'REF', 'ALT', 'QUAL', 'FILTER', 'INFO', 'FORMAT', sample_name, '{}_COMP'.format(sample_name) ) ) ) allele_dict = dict(generate_allele_dict_items(snps_bed_path)) with tempfile.NamedTemporaryFile(dir=temp_file_dir) as temp_variants: temp_variants.write(genotype_bytes) with funcgenom.Genome() as genome: genome.load_variants( temp_variants.name, add_header=('chr', '_', 'pos', 'id', 'g0', 'g1', 'g2') ) genome.sort_variants() for variant in genome.variants(): g0, g1, g2 = (float(g) for g in variant.tuple[-3:]) if ( any(g > threshold for g in (g0, g1, g2)) and ((not het_only) or (g1 > threshold)) ): ref, alt = allele_dict[variant.id] genotype, complementary_genotype = GENOTYPE_DICT[ (g0, g1, g2).index(max(g0, g1, g2)) ] yield '\t'.join( ( variant.chromosome, str(variant.position), variant.id, ref, alt, '.', 'PASS', 'BUILD=37;GP={},{},{}'.format(g0, g1, g2), 'GT', genotype, complementary_genotype ) ) def write_split_vcf(vcf, prefix: str): """Write VCF data split by chromosome Parameters ---------- vcf Iterator giving lines of VCF data prefix : str Output prefix for split VCF files """ header = [] for key, group in itertools.groupby(vcf, key=lambda l: l[:2]): if key in {'##', '#C'}: header.extend(list(group)) else: with BgzfWriter(f'{prefix}.chr{key.rstrip()}.vcf.gz', 'wb') as f: f.write( '\n' .join(itertools.chain(header, tuple(group), ('',))) .encode() )
26.81877
80
0.485218
#=============================================================================== # pyQuASAR.py #=============================================================================== # Imports ====================================================================== import funcgenom import gzip import itertools import os import os.path import pipes import subprocess import tempfile from Bio.bgzf import BgzfWriter from pyQuASAR.env import DIR, SNPS_BED_PATH # Constants ==================================================================== GENOTYPE_DICT = {0: ('0/0', '0/1'), 1: ('0/1', '0/0'), 2: ('1/1', '0/0')} # Functions ==================================================================== def write_compressed_pileup(pileup_bytes: bytes, pileup_file_path: str): """Write a compressed QuASAR intermediate pileup to disk Parameters ---------- pileup_bytes : bytes Pileup file as a bytes object pileup_file_path : str File path to write data """ with gzip.open(pileup_file_path, 'wb') as f: f.write(pileup_bytes) def pileup_to_bed( pileup_bytes, snps_bed_path: str = SNPS_BED_PATH, temp_file_dir=None ) -> str: """Convert a pileup to a BED file in memory Parameters ---------- pileup_bytes : bytes Pileup file as a bytes object snps_bed_path : str Path to BED file containing SNPs temp_file_dir directory for temporary files Returns ------- str BED file """ with tempfile.NamedTemporaryFile(dir=temp_file_dir) as temp_file: temp_file_name = temp_file.name t = pipes.Template() for cmd, kind in ( ('less', '--'), ( ( r"awk -v OFS='\t' " "'{ " "if (" "$4>0 " "&& $5 !~ /[^\^][<>]/ " "&& $5 !~ /\+[0-9]+[ACGTNacgtn]+/ " "&& $5 !~ /-[0-9]+[ACGTNacgtn]+/ " "&& $5 !~ /[^\^]\*/" ") " "print $1,$2-1,$2,$3,$4,$5,$6" "}'" ), '--' ), ('sortBed -i stdin', '--'), (f'intersectBed -a stdin -b {snps_bed_path} -wo', '--'), ('cut -f 1-7,11-14', '--'), ): t.append(cmd, kind) f = t.open(temp_file_name, 'w') f.write(pileup_bytes.decode()) f.close() return open(temp_file_name).read() def write_compressed_pileup_bed( pileup_bytes, pileup_bed_path, snps_bed_path=None, temp_file_dir=None ): """Write a compressed QuASAR intermediate pileup.bed file to disk Parameters ---------- pileup_bytes : bytes Pileup file as a bytes object pileup_bed_path : str File path to write data snps_bed_path : str Path to BED file containing SNPs temp_file_dir directory for temporary files """ with gzip.open(pileup_bed_path, 'wt') as f: f.write( pileup_to_bed( pileup_bytes, snps_bed_path=snps_bed_path, temp_file_dir=temp_file_dir ) ) def bed_to_quasar(bed_path): """Convert the pileup.bed file to quasar input format Write the new file to disk next to the input file. Parameters ---------- bed_path Path to a pileup.bed.gz file """ working_dir = os.getcwd() os.chdir(os.path.dirname(bed_path)) subprocess.call( ( 'Rscript', '--vanilla', f'{DIR}/QuASAR/scripts/convertPileupToQuasar.R', os.path.basename(bed_path) ), stdout=subprocess.DEVNULL ) os.chdir(working_dir) def genotype(*input_file_paths): """Run quasar on formatted input files to obtain genotypes Parameters ---------- input_file_paths paths to input files Returns ------- bytes Standard output from QuASAR """ with subprocess.Popen( ( ( 'Rscript', os.path.join(os.path.dirname(__file__), 'QuASAR_genotype.R') ) + tuple(input_file_paths) ), stdout=subprocess.PIPE ) as quasar_genotype: return quasar_genotype.communicate()[0] def generate_allele_dict_items(snps_bed_path: str): """Generate tuples defining an allele dict Parameters ---------- snps_bed_path : str Path to BED file containing SNPs Yields ------ tuple Variant ID and a pair of alleles """ with open(snps_bed_path, 'r') as f: for line in f: chr, _, pos, id, ref, alt, maf = line.split() yield id, (ref, alt) def genotype_to_vcf( genotype_bytes: bytes, sample_name: str = 'SAMPLE', snps_bed_path: str = SNPS_BED_PATH, threshold: float = 0.99, het_only: bool = False, temp_file_dir=None ): """Convert genotype probabilities from QuASAR to VCF format Parameters ---------- genotype_bytes : bytes Standard output from QuASAR as a bytes object sample_name : str Sample name for the VCF file snps_bed_path : str Path to BED file containing SNPs threshold : float Genotype probability threshold for variants to include het_only : bool Include only heterozygous variants if true temp_file_dir directory for temporary files Yields ------ str A line of a VCF file """ yield from ( '##fileformat=VCFv4.0', '##reference=GRCh37', '##INFO=<ID=BUILD,Number=1,Type=Integer,Description="Genome build">', ( '##INFO=' '<ID=GP,Number=3,Type=Float,Description="Genotype probabilities">' ), '##FORMAT=<ID=GT,Number=1,Type=String,Description=Genotype>', '\t'.join( ( '#CHROM', 'POS', 'ID', 'REF', 'ALT', 'QUAL', 'FILTER', 'INFO', 'FORMAT', sample_name, '{}_COMP'.format(sample_name) ) ) ) allele_dict = dict(generate_allele_dict_items(snps_bed_path)) with tempfile.NamedTemporaryFile(dir=temp_file_dir) as temp_variants: temp_variants.write(genotype_bytes) with funcgenom.Genome() as genome: genome.load_variants( temp_variants.name, add_header=('chr', '_', 'pos', 'id', 'g0', 'g1', 'g2') ) genome.sort_variants() for variant in genome.variants(): g0, g1, g2 = (float(g) for g in variant.tuple[-3:]) if ( any(g > threshold for g in (g0, g1, g2)) and ((not het_only) or (g1 > threshold)) ): ref, alt = allele_dict[variant.id] genotype, complementary_genotype = GENOTYPE_DICT[ (g0, g1, g2).index(max(g0, g1, g2)) ] yield '\t'.join( ( variant.chromosome, str(variant.position), variant.id, ref, alt, '.', 'PASS', 'BUILD=37;GP={},{},{}'.format(g0, g1, g2), 'GT', genotype, complementary_genotype ) ) def write_split_vcf(vcf, prefix: str): """Write VCF data split by chromosome Parameters ---------- vcf Iterator giving lines of VCF data prefix : str Output prefix for split VCF files """ header = [] for key, group in itertools.groupby(vcf, key=lambda l: l[:2]): if key in {'##', '#C'}: header.extend(list(group)) else: with BgzfWriter(f'{prefix}.chr{key.rstrip()}.vcf.gz', 'wb') as f: f.write( '\n' .join(itertools.chain(header, tuple(group), ('',))) .encode() )
0
0
0
10d4dc862e6d17cf503b0e5b178d5c8b237f342f
2,935
py
Python
helper/views.py
arkRedM/ua-iamai-cg-python
c51aa9c76a9b9734917b39e1bbda673b2a8f9cae
[ "MIT" ]
null
null
null
helper/views.py
arkRedM/ua-iamai-cg-python
c51aa9c76a9b9734917b39e1bbda673b2a8f9cae
[ "MIT" ]
9
2019-12-04T23:22:49.000Z
2022-02-10T07:50:16.000Z
helper/views.py
arkRedM/ua-iamai-abhinav-harish-python
c51aa9c76a9b9734917b39e1bbda673b2a8f9cae
[ "MIT" ]
null
null
null
import re import idna from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from helper.models import UserData, NotesData EMAIL_REGEX = '^[a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$' @csrf_exempt @require_http_methods(['POST']) @csrf_exempt @require_http_methods(['POST']) @require_http_methods(['GET'])
27.688679
160
0.611244
import re import idna from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from helper.models import UserData, NotesData EMAIL_REGEX = '^[a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$' @csrf_exempt @require_http_methods(['POST']) def signup(request): email = request.POST.get('email') name = request.POST.get('name') password = request.POST.get('password') email_enc, validity = is_valid_email(email) name_enc = idna.encode(name).decode('utf-8') password_enc = idna.encode(password).decode('utf-8') print(email_enc) if email_enc is not None and name is not None and password is not None: # validate everything user_instance = UserData.objects.create( email=email_enc, name=name_enc, password=password_enc ) user_instance.save() return JsonResponse({ 'success': True, 'message': 'OK' }) else: return JsonResponse({ 'success': False, 'message': 'Data not valid' }) @csrf_exempt @require_http_methods(['POST']) def take_notes(request): title = request.POST.get('title') text = request.POST.get('text') # validate everything note_instance = NotesData.objects.create( title=idna.encode(title), text=str(idna.encode(text)) ) note_instance.save() return JsonResponse({ 'success': True, 'message': 'OK' }) @require_http_methods(['GET']) def email_list(request): email_list = [] for user_ins in UserData.objects.all(): temp_json = { 'email': get_decoded_email(user_ins.email), 'name': idna.decode(user_ins.name) } email_list.append(temp_json) return JsonResponse(email_list, safe=False) def is_valid_email(email): if email: try: name_part = email.split('@')[0] domain_part = email.split('@')[1] domain_name = domain_part.split('.')[0] domain_tld = domain_part.split('.')[1] print('a', idna.encode(name_part).decode('utf-8') + '@' + idna.encode(domain_name).decode('utf-8') + '.' + idna.encode(domain_tld).decode('utf-8')) return idna.encode(name_part).decode('utf-8') + '@' + idna.encode(domain_name).decode('utf-8') + '.' + idna.encode(domain_tld).decode('utf-8'), True except: return None, False else: return None, False def get_decoded_email(email_encoded): print(email_encoded) name_part = email_encoded.split('@')[0] domain_part = email_encoded.split('@')[1] domain_name = domain_part.split('.')[0] domain_tld = domain_part.split('.')[1] return idna.decode(name_part) + '@' + idna.decode(domain_name) + '.' + \ idna.decode(domain_tld)
2,385
0
112
3f28f8ea9f6d7f7343afdb3a96f06fd29ff0a8bb
1,115
py
Python
microservices/utils.py
estibensmanchego/retail
0b36eb48b080bbde8ac38ac45267d77cebae7432
[ "MIT" ]
null
null
null
microservices/utils.py
estibensmanchego/retail
0b36eb48b080bbde8ac38ac45267d77cebae7432
[ "MIT" ]
null
null
null
microservices/utils.py
estibensmanchego/retail
0b36eb48b080bbde8ac38ac45267d77cebae7432
[ "MIT" ]
null
null
null
import json import datetime import decimal from math import sqrt access_control = {'Access-Control-Allow-Origin': '*','Access-Control-Allow-Credentials': 'true'}
21.037736
102
0.671749
import json import datetime import decimal from math import sqrt access_control = {'Access-Control-Allow-Origin': '*','Access-Control-Allow-Credentials': 'true'} def validate(value): body = {'status': False, 'message': value + " is required."} response = { "statusCode": 400, "headers": access_control, "body": json.dumps(body) } return response def response(module, item, action): response_data = { "success": True, "message": module + " " + action + " successfully.", "data": item } response = { "statusCode": 200, "headers": access_control, "body": json.dumps(response_data, default=decimal_default) } return response def calculateAge(birthDate): today = datetime.date.today() age = today.year - birthDate.year - ((today.month, today.day) < (birthDate.month, birthDate.day)) return age def standardDeviation(values, media): ssum = 0 for val in values: ssum += (val - media) ** 2 residing = ssum / (len(values) - 1) return sqrt(residing) def decimal_default(obj): if isinstance(obj, decimal.Decimal): return int(obj) raise TypeError
836
0
116
977e5030df24240fb62138565ca88a32e059b69d
905
py
Python
api-gateway/server/__init__.py
Niweera/DNSTool-Middleware-API
0e83d9f62fb65d9223b86a7876b3f30b2771befb
[ "Apache-2.0" ]
null
null
null
api-gateway/server/__init__.py
Niweera/DNSTool-Middleware-API
0e83d9f62fb65d9223b86a7876b3f30b2771befb
[ "Apache-2.0" ]
9
2021-06-12T05:39:59.000Z
2021-08-14T09:20:00.000Z
api-gateway/server/__init__.py
Niweera/DNSTool-Middleware-API
0e83d9f62fb65d9223b86a7876b3f30b2771befb
[ "Apache-2.0" ]
2
2021-05-22T15:33:50.000Z
2021-08-28T08:51:25.000Z
from os.path import abspath, join, dirname, realpath from flask import Flask from flask_cors import CORS from cache import initialize_cache from compress import initialize_compress from controllers import initialize_routes from flask_restful import Api from mailer import initialize_mailer from middleware.error_handling import errors from server.logging import initialize_logs from swagger import initialize_swagger from config import Config app: Flask = Flask( __name__, static_folder=abspath(join(dirname(dirname(realpath(__file__))), "static")), static_url_path="/static", ) app.config.from_object(Config) if __name__ != "__main__": initialize_logs(app) cors: CORS = CORS( app, resources={r"/*": {"origins": ["*"]}}, ) api: Api = Api(app, errors=errors) initialize_mailer(app) initialize_cache(app) initialize_compress(app) initialize_swagger(app) initialize_routes(api)
24.459459
80
0.78232
from os.path import abspath, join, dirname, realpath from flask import Flask from flask_cors import CORS from cache import initialize_cache from compress import initialize_compress from controllers import initialize_routes from flask_restful import Api from mailer import initialize_mailer from middleware.error_handling import errors from server.logging import initialize_logs from swagger import initialize_swagger from config import Config app: Flask = Flask( __name__, static_folder=abspath(join(dirname(dirname(realpath(__file__))), "static")), static_url_path="/static", ) app.config.from_object(Config) if __name__ != "__main__": initialize_logs(app) cors: CORS = CORS( app, resources={r"/*": {"origins": ["*"]}}, ) api: Api = Api(app, errors=errors) initialize_mailer(app) initialize_cache(app) initialize_compress(app) initialize_swagger(app) initialize_routes(api)
0
0
0
35a2fe39e3494f6a6cb5353894a5e81463e013c9
1,980
py
Python
scannerKH/bestellung/migrations/0001_initial.py
JanGut/scannerKH
1814d2f110af3abdde75e253cab96300701dd531
[ "MIT" ]
1
2020-05-27T16:18:43.000Z
2020-05-27T16:18:43.000Z
scannerKH/bestellung/migrations/0001_initial.py
JanGut/scannerKH
1814d2f110af3abdde75e253cab96300701dd531
[ "MIT" ]
null
null
null
scannerKH/bestellung/migrations/0001_initial.py
JanGut/scannerKH
1814d2f110af3abdde75e253cab96300701dd531
[ "MIT" ]
null
null
null
# Generated by Django 3.0.5 on 2020-04-18 10:36 import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion
46.046512
156
0.647475
# Generated by Django 3.0.5 on 2020-04-18 10:36 import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('grosshaendler', '0001_initial'), ('artikel', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Position', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('menge', models.IntegerField(verbose_name='Menge')), ('artikel', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='artikel.Artikel')), ], ), migrations.CreateModel( name='Bestellung', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('erstellt', models.DateTimeField(default=datetime.datetime.now)), ('bearbeitet', models.DateTimeField(auto_now=True)), ('uebertragen', models.DateTimeField(blank=True, null=True)), ('bearbeiter', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='bearbeiter', to=settings.AUTH_USER_MODEL)), ('ersteller', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='ersteller', to=settings.AUTH_USER_MODEL)), ('grosshaendler', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='grosshaendler.Grosshaendler')), ('positionen', models.ManyToManyField(to='bestellung.Position')), ('uebertrager', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='uebertrager', to=settings.AUTH_USER_MODEL)), ], ), ]
0
1,784
23
413b9efa3a39ff7dd7a517413b97f43f3549ffa1
4,115
py
Python
BackEnd/table_manager.py
doughnut187/CIS407_FF
a4e5be03824604f99be9dc41c7b9f40e36fbad96
[ "MIT" ]
null
null
null
BackEnd/table_manager.py
doughnut187/CIS407_FF
a4e5be03824604f99be9dc41c7b9f40e36fbad96
[ "MIT" ]
null
null
null
BackEnd/table_manager.py
doughnut187/CIS407_FF
a4e5be03824604f99be9dc41c7b9f40e36fbad96
[ "MIT" ]
null
null
null
""" Filename: table_manager.py Purpose: A program to define and create all tables needed in the database Authors: Jordan Smith Group: Wholesome as Heck Programmers (WaHP) Last modified: 11/13/21 """ from db_manager import db_mgr DROP_ALL = True tables = {} ### # TABLES TO BE ADDED ### tables['fitnessGoal'] = { 'fitness_id': 'int NOT NULL AUTO_INCREMENT', 'name': 'varchar(16) NOT NULL', 'constraints': { 'PRIMARY KEY': 'fitness_id' } } tables['users'] = { 'user_id': 'int NOT NULL AUTO_INCREMENT', 'email': 'varchar(64) NOT NULL', 'username': 'varchar(64) NOT NULL', 'password': 'varchar(255) NOT NULL', 'created_at': 'timestamp DEFAULT CURRENT_TIMESTAMP', 'last_logged_in': 'timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP', 'login_streak': 'int DEFAULT 1', 'height': 'float', 'weight': 'float', 'fitness_goal_id': 'int', 'has_finished_quiz': 'boolean DEFAULT false', 'wants_emails': 'boolean', 'show_tips': 'boolean DEFAULT true', 'experience': 'varchar(16)', 'daysPerWeek': 'int', 'availableEquipment': 'varchar(255)', 'constraints': { 'UNIQUE': 'email', 'UNIQUE': 'username', 'PRIMARY KEY': 'user_id', 'FOREIGN KEY': ['fitness_goal_id', 'fitnessGoal(fitness_id)'] } } tables['monsters'] = { 'monster_id': 'int NOT NULL AUTO_INCREMENT', 'user_id': 'int NOT NULL', 'name': 'varchar(64)', 'species': 'varchar(64) NOT NULL', 'exp': 'int NOT NULL DEFAULT 0', 'level': 'int NOT NULL DEFAULT 1', 'image_name': 'varchar(32)', 'constraints': { 'PRIMARY KEY': 'monster_id', 'FOREIGN KEY': ['user_id', 'users(user_id)'] } } tables['workouts'] = { 'workout_id': 'int NOT NULL AUTO_INCREMENT', 'type': 'varchar(16) NOT NULL', 'name': 'varchar(32) NOT NULL', 'equipment': 'varchar(64) NOT NULL', 'difficulty': 'varchar(16) NOT NULL', 'is_priority': 'bool NOT NULL', 'constraints': { 'PRIMARY KEY': 'workout_id' } } tables['workoutConnection'] = { 'workout_id': 'int NOT NULL', 'fitness_goal_id': 'int NOT NULL', 'constraints': { 'FOREIGN KEY': ['workout_id', 'workouts(workout_id)'], 'FOREIGN KEY': ['fitness_goal_id', 'fitnessGoal(fitness_id)'] } } tables['workoutTips'] = { 'tip_id': 'int NOT NULL AUTO_INCREMENT', 'tip_str': 'varchar(255) NOT NULL', 'workout_id': 'int NOT NULL', 'constraints': { 'PRIMARY KEY': 'tip_id', 'FOREIGN KEY': ['workout_id', 'workouts(workout_id)'] } } tables['workoutLogs'] = { 'log_id': 'int NOT NULL AUTO_INCREMENT', 'user_id': 'int NOT NULL', 'workout_ids': 'varchar(255) NOT NULL', 'time_created': 'timestamp DEFAULT CURRENT_TIMESTAMP', 'user_has_completed': 'bool NOT NULL DEFAULT false', 'reps': 'int', 'sets': 'int', 'weight': 'float', 'time_duration': 'float', 'distance_duration': 'float', 'details': 'varchar(255) NOT NULL', 'user_enjoyment': 'int NOT NULL', 'constraints': { 'PRIMARY KEY': 'log_id', 'FOREIGN KEY': ['user_id', 'users(user_id)'] # 'FOREIGN KEY': ['workout_type_id', 'workouts(workout_id)'] } } tables['userRelationship'] = { 'user_first_id': 'int NOT NULL', 'user_second_id': 'int NOT NULL', 'relationship_type': 'varchar(64) NOT NULL', 'constraints': { 'FOREIGN KEY': ['user_first_id', 'users(user_id)'], 'FOREIGN KEY': ['user_second_id', 'users(user_id)'], } } tables['userPRs'] = { 'user_id': 'int NOT NULL', 'workout_id': 'int NOT NULL', 'weight': 'float', 'time': 'float', 'distance': 'float', 'constraints': { 'FOREIGN KEY': ['user_id', 'users(user_id)'], 'FOREIGN KEY': ['workout_id', 'workouts(workout_id)'] } } # Drop all of the tables for debugging and configuration if DROP_ALL: db_mgr.drop_tables(list(tables.keys())[::-1]) # Add the tables into the database for table_name, table_description in tables.items(): db_mgr.create_table(table_name, table_description)
27.993197
88
0.612394
""" Filename: table_manager.py Purpose: A program to define and create all tables needed in the database Authors: Jordan Smith Group: Wholesome as Heck Programmers (WaHP) Last modified: 11/13/21 """ from db_manager import db_mgr DROP_ALL = True tables = {} ### # TABLES TO BE ADDED ### tables['fitnessGoal'] = { 'fitness_id': 'int NOT NULL AUTO_INCREMENT', 'name': 'varchar(16) NOT NULL', 'constraints': { 'PRIMARY KEY': 'fitness_id' } } tables['users'] = { 'user_id': 'int NOT NULL AUTO_INCREMENT', 'email': 'varchar(64) NOT NULL', 'username': 'varchar(64) NOT NULL', 'password': 'varchar(255) NOT NULL', 'created_at': 'timestamp DEFAULT CURRENT_TIMESTAMP', 'last_logged_in': 'timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP', 'login_streak': 'int DEFAULT 1', 'height': 'float', 'weight': 'float', 'fitness_goal_id': 'int', 'has_finished_quiz': 'boolean DEFAULT false', 'wants_emails': 'boolean', 'show_tips': 'boolean DEFAULT true', 'experience': 'varchar(16)', 'daysPerWeek': 'int', 'availableEquipment': 'varchar(255)', 'constraints': { 'UNIQUE': 'email', 'UNIQUE': 'username', 'PRIMARY KEY': 'user_id', 'FOREIGN KEY': ['fitness_goal_id', 'fitnessGoal(fitness_id)'] } } tables['monsters'] = { 'monster_id': 'int NOT NULL AUTO_INCREMENT', 'user_id': 'int NOT NULL', 'name': 'varchar(64)', 'species': 'varchar(64) NOT NULL', 'exp': 'int NOT NULL DEFAULT 0', 'level': 'int NOT NULL DEFAULT 1', 'image_name': 'varchar(32)', 'constraints': { 'PRIMARY KEY': 'monster_id', 'FOREIGN KEY': ['user_id', 'users(user_id)'] } } tables['workouts'] = { 'workout_id': 'int NOT NULL AUTO_INCREMENT', 'type': 'varchar(16) NOT NULL', 'name': 'varchar(32) NOT NULL', 'equipment': 'varchar(64) NOT NULL', 'difficulty': 'varchar(16) NOT NULL', 'is_priority': 'bool NOT NULL', 'constraints': { 'PRIMARY KEY': 'workout_id' } } tables['workoutConnection'] = { 'workout_id': 'int NOT NULL', 'fitness_goal_id': 'int NOT NULL', 'constraints': { 'FOREIGN KEY': ['workout_id', 'workouts(workout_id)'], 'FOREIGN KEY': ['fitness_goal_id', 'fitnessGoal(fitness_id)'] } } tables['workoutTips'] = { 'tip_id': 'int NOT NULL AUTO_INCREMENT', 'tip_str': 'varchar(255) NOT NULL', 'workout_id': 'int NOT NULL', 'constraints': { 'PRIMARY KEY': 'tip_id', 'FOREIGN KEY': ['workout_id', 'workouts(workout_id)'] } } tables['workoutLogs'] = { 'log_id': 'int NOT NULL AUTO_INCREMENT', 'user_id': 'int NOT NULL', 'workout_ids': 'varchar(255) NOT NULL', 'time_created': 'timestamp DEFAULT CURRENT_TIMESTAMP', 'user_has_completed': 'bool NOT NULL DEFAULT false', 'reps': 'int', 'sets': 'int', 'weight': 'float', 'time_duration': 'float', 'distance_duration': 'float', 'details': 'varchar(255) NOT NULL', 'user_enjoyment': 'int NOT NULL', 'constraints': { 'PRIMARY KEY': 'log_id', 'FOREIGN KEY': ['user_id', 'users(user_id)'] # 'FOREIGN KEY': ['workout_type_id', 'workouts(workout_id)'] } } tables['userRelationship'] = { 'user_first_id': 'int NOT NULL', 'user_second_id': 'int NOT NULL', 'relationship_type': 'varchar(64) NOT NULL', 'constraints': { 'FOREIGN KEY': ['user_first_id', 'users(user_id)'], 'FOREIGN KEY': ['user_second_id', 'users(user_id)'], } } tables['userPRs'] = { 'user_id': 'int NOT NULL', 'workout_id': 'int NOT NULL', 'weight': 'float', 'time': 'float', 'distance': 'float', 'constraints': { 'FOREIGN KEY': ['user_id', 'users(user_id)'], 'FOREIGN KEY': ['workout_id', 'workouts(workout_id)'] } } # Drop all of the tables for debugging and configuration if DROP_ALL: db_mgr.drop_tables(list(tables.keys())[::-1]) # Add the tables into the database for table_name, table_description in tables.items(): db_mgr.create_table(table_name, table_description)
0
0
0
6d2117fd7d99a8171e5259d65c44db731880c38a
27
py
Python
boiler/boiler_template/wsgi.py
projectshift/shift-boiler
5f1d236b97fc814ba72897fa8bc76c7518bd1919
[ "MIT" ]
19
2016-08-06T20:06:21.000Z
2020-10-22T08:31:49.000Z
boiler/boiler_template/wsgi.py
projectshift/shift-boiler
5f1d236b97fc814ba72897fa8bc76c7518bd1919
[ "MIT" ]
104
2016-07-31T19:45:00.000Z
2021-09-15T08:13:36.000Z
boiler/boiler_template/wsgi.py
projectshift/shift-boiler
5f1d236b97fc814ba72897fa8bc76c7518bd1919
[ "MIT" ]
1
2017-12-30T09:07:38.000Z
2017-12-30T09:07:38.000Z
from backend.app import app
27
27
0.851852
from backend.app import app
0
0
0
6a81c5a41ae96203f45ff1b955cf357c3fe8d61d
753
py
Python
postgresqleu/confreg/migrations/0029_drop_mailman_sync.py
bradfordboyle/pgeu-system
bbe70e7a94092c10f11a0f74fda23079532bb018
[ "MIT" ]
11
2020-08-20T11:16:02.000Z
2022-03-12T23:25:04.000Z
postgresqleu/confreg/migrations/0029_drop_mailman_sync.py
bradfordboyle/pgeu-system
bbe70e7a94092c10f11a0f74fda23079532bb018
[ "MIT" ]
71
2019-11-18T10:11:22.000Z
2022-03-27T16:12:57.000Z
postgresqleu/confreg/migrations/0029_drop_mailman_sync.py
bradfordboyle/pgeu-system
bbe70e7a94092c10f11a0f74fda23079532bb018
[ "MIT" ]
18
2019-11-18T09:56:31.000Z
2022-01-08T03:16:43.000Z
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-10-09 14:26 from __future__ import unicode_literals from django.db import migrations
23.53125
49
0.575033
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-10-09 14:26 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('confreg', '0028_conferencenews'), ] operations = [ migrations.RemoveField( model_name='conference', name='listadminpwd', ), migrations.RemoveField( model_name='conference', name='listadminurl', ), migrations.RemoveField( model_name='conference', name='speakerlistadminpwd', ), migrations.RemoveField( model_name='conference', name='speakerlistadminurl', ), ]
0
581
23
54d42ececd3221eab54cf510c69419239e27e1be
9,300
py
Python
python/orca/example/learn/tf/image_segmentation/image_segmentation.py
EmiCareOfCell44/BigDL
6278ee8eed09b5072da53dab3a99530cf5f69ba2
[ "Apache-2.0" ]
null
null
null
python/orca/example/learn/tf/image_segmentation/image_segmentation.py
EmiCareOfCell44/BigDL
6278ee8eed09b5072da53dab3a99530cf5f69ba2
[ "Apache-2.0" ]
null
null
null
python/orca/example/learn/tf/image_segmentation/image_segmentation.py
EmiCareOfCell44/BigDL
6278ee8eed09b5072da53dab3a99530cf5f69ba2
[ "Apache-2.0" ]
null
null
null
# # Copyright 2016 The BigDL Authors. # # 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import argparse import os import zipfile import pandas as pd from PIL import Image import tensorflow as tf from tensorflow.python.keras import layers from tensorflow.python.keras import losses from tensorflow.python.keras import models from tensorflow.python.keras import backend as K import matplotlib.image as mpimg import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import numpy as np from bigdl.orca import init_orca_context, stop_orca_context from bigdl.orca.data import XShards from bigdl.orca.learn.tf.estimator import Estimator if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--cluster_mode', type=str, default="local", help='The mode for the Spark cluster. local, yarn or spark-submit.') parser.add_argument('--file_path', type=str, default="/tmp/carvana/", help="The path to carvana train.zip, train_mask.zip and train_mask.csv.zip") parser.add_argument('--epochs', type=int, default=8, help="The number of epochs to train the model") parser.add_argument('--batch_size', type=int, default=8, help="Batch size for training and prediction") parser.add_argument('--platform', type=str, default="linux", help="The platform you used. Only linux and mac are supported.") parser.add_argument('--non_interactive', default=False, action="store_true", help="Flag to not visualize the result.") args = parser.parse_args() main(args.cluster_mode, args.epochs, args.file_path, args.batch_size, args.platform, args.non_interactive)
41.150442
100
0.670968
# # Copyright 2016 The BigDL Authors. # # 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import argparse import os import zipfile import pandas as pd from PIL import Image import tensorflow as tf from tensorflow.python.keras import layers from tensorflow.python.keras import losses from tensorflow.python.keras import models from tensorflow.python.keras import backend as K import matplotlib.image as mpimg import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import numpy as np from bigdl.orca import init_orca_context, stop_orca_context from bigdl.orca.data import XShards from bigdl.orca.learn.tf.estimator import Estimator def load_data_from_zip(file_path, file): with zipfile.ZipFile(os.path.join(file_path, file), "r") as zip_ref: unzipped_file = zip_ref.namelist()[0] zip_ref.extractall(file_path) def load_data(file_path): load_data_from_zip(file_path, 'train.zip') load_data_from_zip(file_path, 'train_masks.zip') load_data_from_zip(file_path, 'train_masks.csv.zip') def main(cluster_mode, max_epoch, file_path, batch_size, platform, non_interactive): import matplotlib if not non_interactive and platform == "mac": matplotlib.use('qt5agg') if cluster_mode == "local": init_orca_context(cluster_mode="local", cores=4, memory="3g") elif cluster_mode == "yarn": init_orca_context(cluster_mode="yarn-client", num_nodes=2, cores=2, driver_memory="3g") elif cluster_mode == "spark-submit": init_orca_context(cluster_mode="spark-submit") load_data(file_path) img_dir = os.path.join(file_path, "train") label_dir = os.path.join(file_path, "train_masks") # Here we only take the first 1000 files for simplicity df_train = pd.read_csv(os.path.join(file_path, 'train_masks.csv')) ids_train = df_train['img'].map(lambda s: s.split('.')[0]) ids_train = ids_train[:1000] x_train_filenames = [] y_train_filenames = [] for img_id in ids_train: x_train_filenames.append(os.path.join(img_dir, "{}.jpg".format(img_id))) y_train_filenames.append(os.path.join(label_dir, "{}_mask.gif".format(img_id))) x_train_filenames, x_val_filenames, y_train_filenames, y_val_filenames = \ train_test_split(x_train_filenames, y_train_filenames, test_size=0.2, random_state=42) def load_and_process_image(path): array = mpimg.imread(path) result = np.array(Image.fromarray(array).resize(size=(128, 128))) result = result.astype(float) result /= 255.0 return result def load_and_process_image_label(path): array = mpimg.imread(path) result = np.array(Image.fromarray(array).resize(size=(128, 128))) result = np.expand_dims(result[:, :, 1], axis=-1) result = result.astype(float) result /= 255.0 return result train_images = np.stack([load_and_process_image(filepath) for filepath in x_train_filenames]) train_label_images = np.stack([load_and_process_image_label(filepath) for filepath in y_train_filenames]) val_images = np.stack([load_and_process_image(filepath) for filepath in x_val_filenames]) val_label_images = np.stack([load_and_process_image_label(filepath) for filepath in y_val_filenames]) train_shards = XShards.partition({"x": train_images, "y": train_label_images}) val_shards = XShards.partition({"x": val_images, "y": val_label_images}) # Build the U-Net model def conv_block(input_tensor, num_filters): encoder = layers.Conv2D(num_filters, (3, 3), padding='same')(input_tensor) encoder = layers.Activation('relu')(encoder) encoder = layers.Conv2D(num_filters, (3, 3), padding='same')(encoder) encoder = layers.Activation('relu')(encoder) return encoder def encoder_block(input_tensor, num_filters): encoder = conv_block(input_tensor, num_filters) encoder_pool = layers.MaxPooling2D((2, 2), strides=(2, 2))(encoder) return encoder_pool, encoder def decoder_block(input_tensor, concat_tensor, num_filters): decoder = layers.Conv2DTranspose(num_filters, (2, 2), strides=(2, 2), padding='same')( input_tensor) decoder = layers.concatenate([concat_tensor, decoder], axis=-1) decoder = layers.Activation('relu')(decoder) decoder = layers.Conv2D(num_filters, (3, 3), padding='same')(decoder) decoder = layers.Activation('relu')(decoder) decoder = layers.Conv2D(num_filters, (3, 3), padding='same')(decoder) decoder = layers.Activation('relu')(decoder) return decoder inputs = layers.Input(shape=(128, 128, 3)) # 128 encoder0_pool, encoder0 = encoder_block(inputs, 16) # 64 encoder1_pool, encoder1 = encoder_block(encoder0_pool, 32) # 32 encoder2_pool, encoder2 = encoder_block(encoder1_pool, 64) # 16 encoder3_pool, encoder3 = encoder_block(encoder2_pool, 128) # 8 center = conv_block(encoder3_pool, 256) # center decoder3 = decoder_block(center, encoder3, 128) # 16 decoder2 = decoder_block(decoder3, encoder2, 64) # 32 decoder1 = decoder_block(decoder2, encoder1, 32) # 64 decoder0 = decoder_block(decoder1, encoder0, 16) # 128 outputs = layers.Conv2D(1, (1, 1), activation='sigmoid')(decoder0) net = models.Model(inputs=[inputs], outputs=[outputs]) # Define custom metrics def dice_coeff(y_true, y_pred): smooth = 1. # Flatten y_true_f = tf.reshape(y_true, [-1]) y_pred_f = tf.reshape(y_pred, [-1]) intersection = tf.reduce_sum(y_true_f * y_pred_f) score = (2. * intersection + smooth) / \ (tf.reduce_sum(y_true_f) + tf.reduce_sum(y_pred_f) + smooth) return score # Define custom loss function def dice_loss(y_true, y_pred): loss = 1 - dice_coeff(y_true, y_pred) return loss def bce_dice_loss(y_true, y_pred): loss = losses.binary_crossentropy(y_true, y_pred) + dice_loss(y_true, y_pred) return loss # compile model net.compile(optimizer=tf.keras.optimizers.Adam(2e-3), loss=bce_dice_loss) print(net.summary()) # create an estimator from keras model est = Estimator.from_keras(keras_model=net) # fit with estimator est.fit(data=train_shards, batch_size=batch_size, epochs=max_epoch) # evaluate with estimator result = est.evaluate(val_shards) print(result) # predict with estimator val_shards.cache() val_image_shards = val_shards.transform_shard(lambda val_dict: {"x": val_dict["x"]}) pred_shards = est.predict(data=val_image_shards, batch_size=batch_size) pred = pred_shards.collect()[0]["prediction"] val_image_label = val_shards.collect()[0] val_image = val_image_label["x"] val_label = val_image_label["y"] if not non_interactive: # visualize 5 predicted results plt.figure(figsize=(10, 20)) for i in range(5): img = val_image[i] label = val_label[i] predicted_label = pred[i] plt.subplot(5, 3, 3 * i + 1) plt.imshow(img) plt.title("Input image") plt.subplot(5, 3, 3 * i + 2) plt.imshow(label[:, :, 0], cmap='gray') plt.title("Actual Mask") plt.subplot(5, 3, 3 * i + 3) plt.imshow(predicted_label, cmap='gray') plt.title("Predicted Mask") plt.suptitle("Examples of Input Image, Label, and Prediction") plt.show() stop_orca_context() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--cluster_mode', type=str, default="local", help='The mode for the Spark cluster. local, yarn or spark-submit.') parser.add_argument('--file_path', type=str, default="/tmp/carvana/", help="The path to carvana train.zip, train_mask.zip and train_mask.csv.zip") parser.add_argument('--epochs', type=int, default=8, help="The number of epochs to train the model") parser.add_argument('--batch_size', type=int, default=8, help="Batch size for training and prediction") parser.add_argument('--platform', type=str, default="linux", help="The platform you used. Only linux and mac are supported.") parser.add_argument('--non_interactive', default=False, action="store_true", help="Flag to not visualize the result.") args = parser.parse_args() main(args.cluster_mode, args.epochs, args.file_path, args.batch_size, args.platform, args.non_interactive)
6,950
0
69
61559f8d36b7771737d73c305c73f5b98979c15b
15,502
py
Python
fastrk/rk_base.py
BoberSA/fastrk
72b313537428bd4c15bdca29c9c4ef0c01039184
[ "MIT" ]
1
2021-07-12T18:36:27.000Z
2021-07-12T18:36:27.000Z
fastrk/rk_base.py
BoberSA/fastrk
72b313537428bd4c15bdca29c9c4ef0c01039184
[ "MIT" ]
null
null
null
fastrk/rk_base.py
BoberSA/fastrk
72b313537428bd4c15bdca29c9c4ef0c01039184
[ "MIT" ]
null
null
null
""" Algorithms for ode propagation with adaptive step selection using explicit embedded runge-kutta method (rk_step): - select_initial_step: select size of first step - rk_variable_step: make an adaptive rk step according to tolerance - rk_prop: integrate ode from s0, t0 to t (Cauchy's problem) - event_detector: root separation for given event function - prop_event: calculate event function from s0, t0 to t - calc_root_brentq: root calculation procedure for events time location - accurate_events: calculate state and time of given events - rk_prop_ev: integrate ode from s0, t0 up to terminal events or time t (boundary problem) Parts of code was used (and rewrited) from scipy.integrate.solve_ivp: https://github.com/scipy/scipy/tree/v1.7.0/scipy/integrate/_ivp and scipy.optimize.brentq: https://github.com/scipy/scipy/blob/v1.7.0/scipy/optimize/zeros.py """ import numpy as np # minimum feasible tolerance EPS = np.finfo(float).eps # rk_variable_step constants SAFETY = 0.9 # Multiply steps computed from asymptotic behaviour of errors by this MIN_FACTOR = 0.2 # Minimum allowed decrease in a step size MAX_FACTOR = 10 # Maximum allowed increase in a step size # rk_prop constants N_STEPS = 2 ** 13 # 8192, standard array size for rk steps N_STEPS_MUL = 2 # Array size multiplier when array is filled up N_STEPS_MAX = 2 ** 24 # 16777216, maximum allowed steps count # rk_prop_ev constants N_EVENTS = 2 ** 10 # 1024, standard events count N_EVENTS_MUL = 2 # Array size multiplier when array is filled up N_EVENTS_MAX = 2 ** 24 # 16777216, maximum allowed events count def rk_variable_step(fode, t, s, h_abs, direction, t_bound, max_step, atol, rtol, out, *fargs): """ Make one RK step of h_abs size in given direction and calculate size of the next step. :param fode: right part of ODE system, should be @cfunc :param s: current state :param t: current time :param h_abs: absolute value of current step :param direction: step direction (+1/-1) :param t_bound: boundary time :param max_step: maximum allowed step size :param atol: absolute tolerance :param rtol: relative tolerance :param out: (writable) array for time and state after successful step :param fargs: fode additional arguments :return: assumption for size of next step """ min_step = 10 * np.abs(np.nextafter(t, direction * np.inf) - t) error_exponent = -1 / (RK_ORDER[1] + 1) if h_abs > max_step: h_abs = max_step elif h_abs < min_step: h_abs = min_step step_accepted = False step_rejected = False while not step_accepted: if h_abs < min_step: raise ValueError('Step size becomes too small') h = h_abs * direction t_new = t + h if direction * (t_new - t_bound) > 0: # in case of last step t_new = t_bound h = t_new - t h_abs = abs(h) sarr = rk_step(fode, t, s, h, *fargs) s_new = sarr[:, 0] s_err = sarr[:, 1] scale = atol + np.maximum(np.abs(s), np.abs(s_new)) * rtol error_norm = rms_norm(s_err / scale) # _estimate_error_norm(self.K, h, scale) if error_norm < 1: if error_norm == 0: factor = MAX_FACTOR else: factor = min(MAX_FACTOR, SAFETY * error_norm ** error_exponent) if step_rejected: factor = min(1, factor) h_abs *= factor step_accepted = True else: h_abs *= max(MIN_FACTOR, SAFETY * error_norm ** error_exponent) step_rejected = True out[0] = t_new out[1:] = s_new return h_abs def select_initial_step(fode, t0, s0, direction, rtol, atol, *fargs): """ Select good initial step size. See scipy.integrate.solve_ivp for details. :param fode: right part of ODE system, should be @cfunc :param t0: initial time :param s0: initial state :param direction: step direction (+1/-1) :param atol: absolute tolerance :param rtol: relative tolerance :param fargs: fode additional arguments :return: """ if s0.size == 0: return np.inf f0 = fode(t0, s0, *fargs) scale = atol + np.abs(s0) * rtol d0 = rms_norm(s0 / scale) d1 = rms_norm(f0 / scale) if d0 < 1e-5 or d1 < 1e-5: h0 = 1e-6 else: h0 = 0.01 * d0 / d1 s1 = s0 + h0 * direction * f0 f1 = fode(t0 + h0 * direction, s1, *fargs) d2 = rms_norm((f1 - f0) / scale) / h0 if d1 <= 1e-15 and d2 <= 1e-15: h1 = max(1e-6, h0 * 1e-3) else: h1 = (0.01 / max(d1, d2)) ** (1 / (RK_ORDER[1] + 1)) return min(100 * h0, h1) def rk_prop(fode, s0, t0, t, max_step, rtol, atol, *fargs): """ Integrate ODE from t0, s0 to t. See scipy.integrate.solve_ivp for details. :param fode: right part of ODE system, should be @cfunc :param s0: initial state :param t0: initial time :param t: boundary time :param max_step: maximum allowed step size :param rtol: relative tolerance :param atol: absolute tolerance :param fargs: fode additional arguments :return: array [[time, state]] for each integrator step """ direction = 1. if t >= t0 else -1. h_abs = select_initial_step(fode, t0, s0, direction, rtol, atol, *fargs) # h_abs = abs(first_step) n_steps = N_STEPS trajectory = np.empty((n_steps, s0.size + 1), dtype=s0.dtype) trajectory[0, 0] = t0 trajectory[0, 1:] = s0 i = 0 while abs(trajectory[i, 0] - t) > EPS: h_abs = rk_variable_step(fode, trajectory[i, 0], trajectory[i, 1:], h_abs, direction, t, max_step, rtol, atol, trajectory[i + 1], *fargs) i += 1 if i >= n_steps - 1: # resize array n_steps *= N_STEPS_MUL if n_steps > N_STEPS_MAX: raise RuntimeError('Maximum allowed steps count exceeded') tmp = trajectory trajectory = _resize_2darray_axis0(trajectory, n_steps) return trajectory[:i + 1] def event_detector(call_event, t, s, evvals, it, counters, values, terminals, directions, counts, evout, n_evout): """ Separate roots of event functions, i.e. time moments when events triggered. :param call_event: call_event function :param t: current time :param s: current state :param evvals: array with event function values at previous times :param it: number of current iteration (index of state in trajectory) :param counters: current event counters :param values: array of values for event functions :param terminals: array of bools (whether event is terminal) :param directions: array of direction for events :param counts: array of :param evout: (writable) array [[event_index, event_counter, trajectory_index]] :param n_evout: (writable) array of one int (size of evout) :return: """ terminal = False n_events = evvals.shape[1] for i in range(n_events): evvals[it, i] = call_event(t, s, values, i) if it == 0: counters[...] = counts return 0 for i in range(n_events): cur_val = evvals[it][i] prev_val = evvals[it - 1][i] f1 = (prev_val < 0) and (cur_val > 0) and ((directions[i] == 1) or (directions[i] == 0)) f2 = (prev_val > 0) and (cur_val < 0) and ((directions[i] == -1) or (directions[i] == 0)) if (f1 or f2) and ((counters[i] == -1) or (counters[i] > 0)): if counters[i] > 0: counters[i] -= 1 cnt = -1 if counters[i] == -1 else counts[i] - counters[i] # event index, event trigger counter, index of state before event evout[n_evout[0]] = np.array([i, cnt, it - 1]) n_evout[0] += 1 if terminals[i] and ((counters[i] == -1) or (counters[i] == 0)): terminal = True if terminal: return -1 return 0 def prop_event(call_event, values, idx, _fode, _s0, _t0, _t, _max_step, _rtol, _atol, *fargs): """ Propagate ODE state up to t and calculate value of [idx] event function :param call_event: call_event function :param values: events values :param idx: event index :param _rest: rk_prop arguments :param fargs: _fode additional arguments :return: """ trj = rk_prop(_fode, _s0, _t0, _t, _max_step, _rtol, _atol, *fargs) return call_event(trj[-1, 0], trj[-1, 1:], values, idx) def calc_root_brentq(xa, xb, xtol, rtol, maxiter, _fode, _s0, _max_step, _rtol, _atol, __call_event, __values, __idx, *fargs): """ Brent's root finding algorithm for prop_event(t) function. See scipy.optimize.brentq for details. :param xa: left side of segment :param xb: right side of segment :param xtol: absolute tolerance by function argument :param rtol: relative tolerance :param maxiter: maximum number of iterations :param rest: prop_event arguments :return: <x>, where f(<x>) = 0 with specified tolerance """ xpre, xcur = xa, xb xblk, fblk = 0., 0. spre, scur = 0., 0. fpre = prop_event(__call_event, __values, __idx, _fode, _s0, xa, xpre, _max_step, _rtol, _atol, *fargs) fcur = prop_event(__call_event, __values, __idx, _fode, _s0, xa, xcur, _max_step, _rtol, _atol, *fargs) if fpre * fcur > 0: raise ValueError('The event function has the same signs at both ends of the segment') if fpre == 0: return xpre if fcur == 0: return xcur for i in range(maxiter): if fpre * fcur < 0: xblk = xpre fblk = fpre spre = scur = xcur - xpre if abs(fblk) < abs(fcur): xpre = xcur xcur = xblk xblk = xpre fpre = fcur fcur = fblk fblk = fpre delta = (xtol + rtol * abs(xcur)) / 2 sbis = (xblk - xcur) / 2 if fcur == 0 or abs(sbis) < delta: return xcur if abs(spre) > delta and abs(fcur) < abs(fpre): if xpre == xblk: stry = -fcur * (xcur - xpre) / (fcur - fpre) else: dpre = (fpre - fcur) / (xpre - xcur) dblk = (fblk - fcur) / (xblk - xcur) stry = -fcur * (fblk * dblk - fpre * dpre) / (dblk * dpre * (fblk - fpre)) if 2 * abs(stry) < min(abs(spre), 3 * abs(sbis) - delta): spre = scur scur = stry else: spre = sbis scur = sbis else: spre = sbis scur = sbis xpre = xcur fpre = fcur if abs(scur) > delta: xcur += scur else: xcur += delta if sbis > 0 else -delta fcur = prop_event(__call_event, __values, __idx, _fode, _s0, xa, xcur, _max_step, _rtol, _atol, *fargs) raise ValueError('Convergence error') def accurate_events(trajectory, evout, accurates, _call_event, _values, _xtol, _rtol, _maxiter, __fode, __max_step, __rtol, __atol, *fargs): """ Calculate event time and state where it needs to with given tolerance. :param trajectory: calculated trajectory (array of time-states) :param evout: array of [event_index, event_counter, trajectory_index] :param accurates: array of bools (True if event should be calculated accurate) :param _rest: calc_root_brentq, rk_prop arguments :param fargs: _fode additional arguments :return: event-states-array [[event_index, event_counter, time, state]] """ # evout [[event_index, event_counter, trajectory_index]] n = evout.shape[0] res = np.empty((n, trajectory.shape[1] + 2), dtype=trajectory.dtype) for i in range(n): ei = evout[i, 0] ti = evout[i, 2] t0 = trajectory[ti, 0] t1 = trajectory[ti + 1, 0] s0 = trajectory[ti, 1:] res[i, :2] = evout[i, :2] if accurates[ei]: t = calc_root_brentq(t0, t1, _xtol, _rtol, _maxiter, __fode, s0, __max_step, __rtol, __atol, _call_event, _values, ei, *fargs) res[i, 2:] = rk_prop(__fode, s0, t0, t, __max_step, __rtol, __atol, *fargs)[-1] else: res[i, 2:] = trajectory[ti + 1] return res def rk_prop_ev(fode, s0, t0, t, max_step, rtol, atol, _values, _terminals, _directions, _counts, _accurates, __call_event, __xtol, __rtol, __maxiter, *fargs): """ Integrate ODE from t0, s0 up to any terminal event or time t. :param fode: right part of ODE system, should be @cfunc :param s0: initial state :param t0: initial time :param t: end time :param max_step: maximum step size :param rtol: relative tolerance :param atol: absolute tolerance :param _rest: event_detector, rk_variable_step arguments :param fargs: fode additional arguments :return: trajectory-array, event-states-array """ direction = 1. if t >= t0 else -1. h_abs = select_initial_step(fode, t0, s0, direction, rtol, atol, *fargs) n_steps = N_STEPS trajectory = np.empty((n_steps, s0.size + 1), dtype=s0.dtype) trajectory[0, 0] = t0 trajectory[0, 1:] = s0 n_events = N_EVENTS ev_n = _terminals.size evvals = np.empty((n_steps, ev_n), dtype=s0.dtype) counters = np.empty(ev_n, dtype=np.int32) evout = np.empty((n_events, 3), dtype=np.int32) n_evout = np.zeros(1, dtype=np.int32) # first call event_detector(__call_event, t, s0, evvals, 0, counters, _values, _terminals, _directions, _counts, evout, n_evout) i = 0 while abs(trajectory[i, 0] - t) > EPS: h_abs = rk_variable_step(fode, trajectory[i, 0], trajectory[i, 1:], h_abs, direction, t, max_step, rtol, atol, trajectory[i + 1], *fargs) i += 1 if i >= n_steps - 1: n_steps *= N_STEPS_MUL if n_steps > N_STEPS_MAX: raise RuntimeError('Maximum allowed steps count exceeded') tmp = trajectory trajectory = _resize_2darray_axis0(trajectory, n_steps) evvals = _resize_2darray_axis0(evvals, n_steps) trm = event_detector(__call_event, trajectory[i, 0], trajectory[i, 1:], evvals, i, counters, _values, _terminals, _directions, _counts, evout, n_evout) if n_evout[0] >= n_events - 1: n_events *= N_EVENTS_MUL if n_steps > N_EVENTS_MAX: raise RuntimeError('Maximum allowed count of event records exceeded') tmp = evout evout = _resize_2darray_axis0(evout, n_events) if trm != 0: break event_out = accurate_events(trajectory, evout[:n_evout[0]], _accurates, __call_event, _values, __xtol, __rtol, __maxiter, fode, max_step, rtol, atol, *fargs) return trajectory[:i + 1], event_out
34.372506
114
0.600052
""" Algorithms for ode propagation with adaptive step selection using explicit embedded runge-kutta method (rk_step): - select_initial_step: select size of first step - rk_variable_step: make an adaptive rk step according to tolerance - rk_prop: integrate ode from s0, t0 to t (Cauchy's problem) - event_detector: root separation for given event function - prop_event: calculate event function from s0, t0 to t - calc_root_brentq: root calculation procedure for events time location - accurate_events: calculate state and time of given events - rk_prop_ev: integrate ode from s0, t0 up to terminal events or time t (boundary problem) Parts of code was used (and rewrited) from scipy.integrate.solve_ivp: https://github.com/scipy/scipy/tree/v1.7.0/scipy/integrate/_ivp and scipy.optimize.brentq: https://github.com/scipy/scipy/blob/v1.7.0/scipy/optimize/zeros.py """ import numpy as np # minimum feasible tolerance EPS = np.finfo(float).eps # rk_variable_step constants SAFETY = 0.9 # Multiply steps computed from asymptotic behaviour of errors by this MIN_FACTOR = 0.2 # Minimum allowed decrease in a step size MAX_FACTOR = 10 # Maximum allowed increase in a step size # rk_prop constants N_STEPS = 2 ** 13 # 8192, standard array size for rk steps N_STEPS_MUL = 2 # Array size multiplier when array is filled up N_STEPS_MAX = 2 ** 24 # 16777216, maximum allowed steps count # rk_prop_ev constants N_EVENTS = 2 ** 10 # 1024, standard events count N_EVENTS_MUL = 2 # Array size multiplier when array is filled up N_EVENTS_MAX = 2 ** 24 # 16777216, maximum allowed events count def rms_norm(x): return (x @ x / x.size) ** 0.5 def _resize_2darray_axis0(arr, new_size): new_arr = np.empty((new_size, arr.shape[1]), dtype=arr.dtype) new_arr[:min(arr.shape[0], new_size)] = arr return new_arr def rk_variable_step(fode, t, s, h_abs, direction, t_bound, max_step, atol, rtol, out, *fargs): """ Make one RK step of h_abs size in given direction and calculate size of the next step. :param fode: right part of ODE system, should be @cfunc :param s: current state :param t: current time :param h_abs: absolute value of current step :param direction: step direction (+1/-1) :param t_bound: boundary time :param max_step: maximum allowed step size :param atol: absolute tolerance :param rtol: relative tolerance :param out: (writable) array for time and state after successful step :param fargs: fode additional arguments :return: assumption for size of next step """ min_step = 10 * np.abs(np.nextafter(t, direction * np.inf) - t) error_exponent = -1 / (RK_ORDER[1] + 1) if h_abs > max_step: h_abs = max_step elif h_abs < min_step: h_abs = min_step step_accepted = False step_rejected = False while not step_accepted: if h_abs < min_step: raise ValueError('Step size becomes too small') h = h_abs * direction t_new = t + h if direction * (t_new - t_bound) > 0: # in case of last step t_new = t_bound h = t_new - t h_abs = abs(h) sarr = rk_step(fode, t, s, h, *fargs) s_new = sarr[:, 0] s_err = sarr[:, 1] scale = atol + np.maximum(np.abs(s), np.abs(s_new)) * rtol error_norm = rms_norm(s_err / scale) # _estimate_error_norm(self.K, h, scale) if error_norm < 1: if error_norm == 0: factor = MAX_FACTOR else: factor = min(MAX_FACTOR, SAFETY * error_norm ** error_exponent) if step_rejected: factor = min(1, factor) h_abs *= factor step_accepted = True else: h_abs *= max(MIN_FACTOR, SAFETY * error_norm ** error_exponent) step_rejected = True out[0] = t_new out[1:] = s_new return h_abs def select_initial_step(fode, t0, s0, direction, rtol, atol, *fargs): """ Select good initial step size. See scipy.integrate.solve_ivp for details. :param fode: right part of ODE system, should be @cfunc :param t0: initial time :param s0: initial state :param direction: step direction (+1/-1) :param atol: absolute tolerance :param rtol: relative tolerance :param fargs: fode additional arguments :return: """ if s0.size == 0: return np.inf f0 = fode(t0, s0, *fargs) scale = atol + np.abs(s0) * rtol d0 = rms_norm(s0 / scale) d1 = rms_norm(f0 / scale) if d0 < 1e-5 or d1 < 1e-5: h0 = 1e-6 else: h0 = 0.01 * d0 / d1 s1 = s0 + h0 * direction * f0 f1 = fode(t0 + h0 * direction, s1, *fargs) d2 = rms_norm((f1 - f0) / scale) / h0 if d1 <= 1e-15 and d2 <= 1e-15: h1 = max(1e-6, h0 * 1e-3) else: h1 = (0.01 / max(d1, d2)) ** (1 / (RK_ORDER[1] + 1)) return min(100 * h0, h1) def rk_prop(fode, s0, t0, t, max_step, rtol, atol, *fargs): """ Integrate ODE from t0, s0 to t. See scipy.integrate.solve_ivp for details. :param fode: right part of ODE system, should be @cfunc :param s0: initial state :param t0: initial time :param t: boundary time :param max_step: maximum allowed step size :param rtol: relative tolerance :param atol: absolute tolerance :param fargs: fode additional arguments :return: array [[time, state]] for each integrator step """ direction = 1. if t >= t0 else -1. h_abs = select_initial_step(fode, t0, s0, direction, rtol, atol, *fargs) # h_abs = abs(first_step) n_steps = N_STEPS trajectory = np.empty((n_steps, s0.size + 1), dtype=s0.dtype) trajectory[0, 0] = t0 trajectory[0, 1:] = s0 i = 0 while abs(trajectory[i, 0] - t) > EPS: h_abs = rk_variable_step(fode, trajectory[i, 0], trajectory[i, 1:], h_abs, direction, t, max_step, rtol, atol, trajectory[i + 1], *fargs) i += 1 if i >= n_steps - 1: # resize array n_steps *= N_STEPS_MUL if n_steps > N_STEPS_MAX: raise RuntimeError('Maximum allowed steps count exceeded') tmp = trajectory trajectory = _resize_2darray_axis0(trajectory, n_steps) return trajectory[:i + 1] def event_detector(call_event, t, s, evvals, it, counters, values, terminals, directions, counts, evout, n_evout): """ Separate roots of event functions, i.e. time moments when events triggered. :param call_event: call_event function :param t: current time :param s: current state :param evvals: array with event function values at previous times :param it: number of current iteration (index of state in trajectory) :param counters: current event counters :param values: array of values for event functions :param terminals: array of bools (whether event is terminal) :param directions: array of direction for events :param counts: array of :param evout: (writable) array [[event_index, event_counter, trajectory_index]] :param n_evout: (writable) array of one int (size of evout) :return: """ terminal = False n_events = evvals.shape[1] for i in range(n_events): evvals[it, i] = call_event(t, s, values, i) if it == 0: counters[...] = counts return 0 for i in range(n_events): cur_val = evvals[it][i] prev_val = evvals[it - 1][i] f1 = (prev_val < 0) and (cur_val > 0) and ((directions[i] == 1) or (directions[i] == 0)) f2 = (prev_val > 0) and (cur_val < 0) and ((directions[i] == -1) or (directions[i] == 0)) if (f1 or f2) and ((counters[i] == -1) or (counters[i] > 0)): if counters[i] > 0: counters[i] -= 1 cnt = -1 if counters[i] == -1 else counts[i] - counters[i] # event index, event trigger counter, index of state before event evout[n_evout[0]] = np.array([i, cnt, it - 1]) n_evout[0] += 1 if terminals[i] and ((counters[i] == -1) or (counters[i] == 0)): terminal = True if terminal: return -1 return 0 def prop_event(call_event, values, idx, _fode, _s0, _t0, _t, _max_step, _rtol, _atol, *fargs): """ Propagate ODE state up to t and calculate value of [idx] event function :param call_event: call_event function :param values: events values :param idx: event index :param _rest: rk_prop arguments :param fargs: _fode additional arguments :return: """ trj = rk_prop(_fode, _s0, _t0, _t, _max_step, _rtol, _atol, *fargs) return call_event(trj[-1, 0], trj[-1, 1:], values, idx) def calc_root_brentq(xa, xb, xtol, rtol, maxiter, _fode, _s0, _max_step, _rtol, _atol, __call_event, __values, __idx, *fargs): """ Brent's root finding algorithm for prop_event(t) function. See scipy.optimize.brentq for details. :param xa: left side of segment :param xb: right side of segment :param xtol: absolute tolerance by function argument :param rtol: relative tolerance :param maxiter: maximum number of iterations :param rest: prop_event arguments :return: <x>, where f(<x>) = 0 with specified tolerance """ xpre, xcur = xa, xb xblk, fblk = 0., 0. spre, scur = 0., 0. fpre = prop_event(__call_event, __values, __idx, _fode, _s0, xa, xpre, _max_step, _rtol, _atol, *fargs) fcur = prop_event(__call_event, __values, __idx, _fode, _s0, xa, xcur, _max_step, _rtol, _atol, *fargs) if fpre * fcur > 0: raise ValueError('The event function has the same signs at both ends of the segment') if fpre == 0: return xpre if fcur == 0: return xcur for i in range(maxiter): if fpre * fcur < 0: xblk = xpre fblk = fpre spre = scur = xcur - xpre if abs(fblk) < abs(fcur): xpre = xcur xcur = xblk xblk = xpre fpre = fcur fcur = fblk fblk = fpre delta = (xtol + rtol * abs(xcur)) / 2 sbis = (xblk - xcur) / 2 if fcur == 0 or abs(sbis) < delta: return xcur if abs(spre) > delta and abs(fcur) < abs(fpre): if xpre == xblk: stry = -fcur * (xcur - xpre) / (fcur - fpre) else: dpre = (fpre - fcur) / (xpre - xcur) dblk = (fblk - fcur) / (xblk - xcur) stry = -fcur * (fblk * dblk - fpre * dpre) / (dblk * dpre * (fblk - fpre)) if 2 * abs(stry) < min(abs(spre), 3 * abs(sbis) - delta): spre = scur scur = stry else: spre = sbis scur = sbis else: spre = sbis scur = sbis xpre = xcur fpre = fcur if abs(scur) > delta: xcur += scur else: xcur += delta if sbis > 0 else -delta fcur = prop_event(__call_event, __values, __idx, _fode, _s0, xa, xcur, _max_step, _rtol, _atol, *fargs) raise ValueError('Convergence error') def accurate_events(trajectory, evout, accurates, _call_event, _values, _xtol, _rtol, _maxiter, __fode, __max_step, __rtol, __atol, *fargs): """ Calculate event time and state where it needs to with given tolerance. :param trajectory: calculated trajectory (array of time-states) :param evout: array of [event_index, event_counter, trajectory_index] :param accurates: array of bools (True if event should be calculated accurate) :param _rest: calc_root_brentq, rk_prop arguments :param fargs: _fode additional arguments :return: event-states-array [[event_index, event_counter, time, state]] """ # evout [[event_index, event_counter, trajectory_index]] n = evout.shape[0] res = np.empty((n, trajectory.shape[1] + 2), dtype=trajectory.dtype) for i in range(n): ei = evout[i, 0] ti = evout[i, 2] t0 = trajectory[ti, 0] t1 = trajectory[ti + 1, 0] s0 = trajectory[ti, 1:] res[i, :2] = evout[i, :2] if accurates[ei]: t = calc_root_brentq(t0, t1, _xtol, _rtol, _maxiter, __fode, s0, __max_step, __rtol, __atol, _call_event, _values, ei, *fargs) res[i, 2:] = rk_prop(__fode, s0, t0, t, __max_step, __rtol, __atol, *fargs)[-1] else: res[i, 2:] = trajectory[ti + 1] return res def rk_prop_ev(fode, s0, t0, t, max_step, rtol, atol, _values, _terminals, _directions, _counts, _accurates, __call_event, __xtol, __rtol, __maxiter, *fargs): """ Integrate ODE from t0, s0 up to any terminal event or time t. :param fode: right part of ODE system, should be @cfunc :param s0: initial state :param t0: initial time :param t: end time :param max_step: maximum step size :param rtol: relative tolerance :param atol: absolute tolerance :param _rest: event_detector, rk_variable_step arguments :param fargs: fode additional arguments :return: trajectory-array, event-states-array """ direction = 1. if t >= t0 else -1. h_abs = select_initial_step(fode, t0, s0, direction, rtol, atol, *fargs) n_steps = N_STEPS trajectory = np.empty((n_steps, s0.size + 1), dtype=s0.dtype) trajectory[0, 0] = t0 trajectory[0, 1:] = s0 n_events = N_EVENTS ev_n = _terminals.size evvals = np.empty((n_steps, ev_n), dtype=s0.dtype) counters = np.empty(ev_n, dtype=np.int32) evout = np.empty((n_events, 3), dtype=np.int32) n_evout = np.zeros(1, dtype=np.int32) # first call event_detector(__call_event, t, s0, evvals, 0, counters, _values, _terminals, _directions, _counts, evout, n_evout) i = 0 while abs(trajectory[i, 0] - t) > EPS: h_abs = rk_variable_step(fode, trajectory[i, 0], trajectory[i, 1:], h_abs, direction, t, max_step, rtol, atol, trajectory[i + 1], *fargs) i += 1 if i >= n_steps - 1: n_steps *= N_STEPS_MUL if n_steps > N_STEPS_MAX: raise RuntimeError('Maximum allowed steps count exceeded') tmp = trajectory trajectory = _resize_2darray_axis0(trajectory, n_steps) evvals = _resize_2darray_axis0(evvals, n_steps) trm = event_detector(__call_event, trajectory[i, 0], trajectory[i, 1:], evvals, i, counters, _values, _terminals, _directions, _counts, evout, n_evout) if n_evout[0] >= n_events - 1: n_events *= N_EVENTS_MUL if n_steps > N_EVENTS_MAX: raise RuntimeError('Maximum allowed count of event records exceeded') tmp = evout evout = _resize_2darray_axis0(evout, n_events) if trm != 0: break event_out = accurate_events(trajectory, evout[:n_evout[0]], _accurates, __call_event, _values, __xtol, __rtol, __maxiter, fode, max_step, rtol, atol, *fargs) return trajectory[:i + 1], event_out
183
0
46
4a5de15344cb09a35e974ff8ea559ff1ccb96654
12,375
bzl
Python
pw_protobuf_compiler/pw_proto_library.bzl
Tiggerlaboratoriet/pigweed
7d7e7ad6223433f45af680f43ab4d75e23ad3257
[ "Apache-2.0" ]
null
null
null
pw_protobuf_compiler/pw_proto_library.bzl
Tiggerlaboratoriet/pigweed
7d7e7ad6223433f45af680f43ab4d75e23ad3257
[ "Apache-2.0" ]
null
null
null
pw_protobuf_compiler/pw_proto_library.bzl
Tiggerlaboratoriet/pigweed
7d7e7ad6223433f45af680f43ab4d75e23ad3257
[ "Apache-2.0" ]
null
null
null
# Copyright 2022 The Pigweed Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. """WORK IN PROGRESS! This is intended to be a replacement for the proto codegen in proto.bzl, which relies on the transitive proto compilation support removed from newer versions of rules_proto_grpc. However, the version checked in here does not yet support, 1. Proto libraries with dependencies in external repositories. 2. Proto libraries with strip_import_prefix or import_prefix attributes. In addition, nanopb proto files are not yet generated. TODO(pwbug/621): Close these gaps and start using this implementation. # Overview of implementation (If you just want to use pw_proto_library, see its docstring; this section is intended to orient future maintainers.) Proto code generation is carried out by the _pw_proto_library, _pw_raw_rpc_proto_library and _pw_nanopb_rpc_proto_library rules using aspects (https://docs.bazel.build/versions/main/skylark/aspects.html). A _pw_proto_library has a single proto_library as a dependency, but that proto_library may depend on other proto_library targets; as a result, the generated .pwpb.h file #include's .pwpb.h files generated from the dependency proto_libraries. The aspect propagates along the proto_library dependency graph, running the proto compiler on each proto_library in the original target's transitive dependencies, ensuring that we're not missing any .pwpb.h files at C++ compile time. Although we have a separate rule for each protocol compiler plugin (_pw_proto_library, _pw_raw_rpc_proto_library, _pw_nanopb_rpc_proto_library), they actually share an implementation (_pw _impl_pw_proto_library) and use similar aspects, all generated by _proto_compiler_aspect. The only difference between the rules are captured in the PIGWEED_PLUGIN dictonary and the aspect instantiations (_pw_proto_compiler_aspect, etc). """ load("//pw_build:pigweed.bzl", "pw_cc_library") load("@rules_proto//proto:defs.bzl", "ProtoInfo") load("//pw_protobuf_compiler:pw_nanopb_cc_library", "pw_nanopb_cc_library") def pw_proto_library( name = "", deps = [], nanopb_options = None, enabled_targets = None): """Generate Pigweed proto C++ code. This is the only public symbol in this file: everything else is implementation details. Args: name: The name of the target. deps: proto_library targets from which to generate Pigweed C++. nanopb_options: path to file containing nanopb options, if any (https://jpa.kapsi.fi/nanopb/docs/reference.html#proto-file-options). enabled_targets: Specifies which libraries should be generated. Libraries will only be generated as needed, but unnecessary outputs may conflict with other build rules and thus cause build failures. This filter allows manual selection of which libraries should be supported by this build target in order to prevent such conflicts. The argument, if provided, should be a subset of ["pwpb", "nanopb", "raw_rpc", "nanopb_rpc"]. All are enabled by default. Note that "nanopb_rpc" relies on "nanopb". Example usage: proto_library( name = "benchmark_proto", srcs = [ "benchmark.proto", ], ) pw_proto_library( name = "benchmark_pw_proto", deps = [":benchmark_proto"], ) pw_cc_binary( name = "proto_user", srcs = ["proto_user.cc"], deps = [":benchmark_pw_proto.pwpb"], ) The pw_proto_library generates the following targets in this example: "benchmark_pw_proto.pwpb": C++ library exposing the "benchmark.pwpb.h" header. "benchmark_pw_proto.pwpb_rpc": C++ library exposing the "benchmark.rpc.pwpb.h" header. "benchmark_pw_proto.raw_rpc": C++ library exposing the "benchmark.raw_rpc.h" header. "benchmark_pw_proto.nanopb": C++ library exposing the "benchmark.pb.h" header. "benchmark_pw_proto.nanopb_rpc": C++ library exposing the "benchmark.rpc.pb.h" header. """ if is_plugin_enabled("nanobp"): # Use nanopb to generate the pb.h and pb.c files, and the target # exposing them. pw_nanopb_cc_library(name + ".nanopb", deps, options = nanopb_options) # Use Pigweed proto plugins to generate the remaining files and targets. for plugin_name, info in PIGWEED_PLUGIN.items(): if not is_plugin_enabled(plugin_name): continue name_pb = name + "_pb." + plugin_name plugin_rule = info["compiler"] plugin_rule( name = name_pb, deps = deps, ) # The rpc.pb.h header depends on the generated nanopb or pwpb code. if info["include_nanopb_dep"]: lib_deps = info["deps"] + [":" + name + ".nanopb"] elif info["include_pwpb_dep"]: lib_deps = info["deps"] + [":" + name + ".pwpb"] else: lib_deps = info["deps"] pw_cc_library( name = name + "." + plugin_name, hdrs = [name_pb], deps = lib_deps, linkstatic = 1, ) PwProtoInfo = provider( "Returned by PW proto compilation aspect", fields = { "genfiles": "generated C++ header files", }, ) def _proto_compiler_aspect(extension, protoc_plugin): """Returns an aspect that runs the proto compiler. The aspect propagates through the deps of proto_library targets, running the proto compiler with the specified plugin for each of their source files. The proto compiler is assumed to produce one output file per input .proto file. That file is placed under bazel-bin at the same path as the input file, but with the specified extension (i.e., with _extension = .pwpb.h, the aspect converts pw_log/log.proto into bazel-bin/pw_log/log.pwpb.h). The aspect returns a provider exposing all the File objects generated from the dependency graph. """ return aspect( attr_aspects = ["deps"], attrs = { "_extension": attr.string(default = extension), "_protoc": attr.label( default = Label("@com_google_protobuf//:protoc"), executable = True, cfg = "exec", ), "_protoc_plugin": attr.label( default = Label(protoc_plugin), executable = True, cfg = "exec", ), }, implementation = _proto_compiler_aspect_impl, provides = [PwProtoInfo], ) def _impl_pw_proto_library(ctx): """Implementation of the proto codegen rule. The work of actually generating the code is done by the aspect, so here we just gather up all the generated files and return them. """ # Note that we don't distinguish between the files generated from the # target, and the files generated from its dependencies. We return all of # them together, and in pw_proto_library expose all of them as hdrs. # Pigweed's plugins happen to only generate .h files, so this works, but # strictly speaking we should expose only the files generated from the # target itself in hdrs, and place the headers generated from dependencies # in srcs. We don't perform layering_check in Pigweed, so this is not a big # deal. # # TODO(pwbug/621): Tidy this up. all_genfiles = [] for dep in ctx.attr.deps: for f in dep[PwProtoInfo].genfiles: all_genfiles.append(f) return [DefaultInfo(files = depset(all_genfiles))] # Instantiate the aspects and rules for generating code using specific plugins. _pw_proto_compiler_aspect = _proto_compiler_aspect("pwpb.h", "//pw_protobuf/py:plugin") _pw_proto_library = rule( implementation = _impl_pw_proto_library, attrs = { "deps": attr.label_list( providers = [ProtoInfo], aspects = [_pw_proto_compiler_aspect], ), }, ) _pw_pwpb_rpc_proto_compiler_aspect = _proto_compiler_aspect("rpc.pwpb.h", "//pw_rpc/py:plugin_pwpb") _pw_pwpb_rpc_proto_library = rule( implementation = _impl_pw_proto_library, attrs = { "deps": attr.label_list( providers = [ProtoInfo], aspects = [_pw_pwpb_rpc_proto_compiler_aspect], ), }, ) _pw_raw_rpc_proto_compiler_aspect = _proto_compiler_aspect("raw_rpc.pb.h", "//pw_rpc/py:plugin_raw") _pw_raw_rpc_proto_library = rule( implementation = _impl_pw_proto_library, attrs = { "deps": attr.label_list( providers = [ProtoInfo], aspects = [_pw_raw_rpc_proto_compiler_aspect], ), }, ) _pw_nanopb_rpc_proto_compiler_aspect = _proto_compiler_aspect("rpc.pb.h", "//pw_rpc/py:plugin_nanopb") _pw_nanopb_rpc_proto_library = rule( implementation = _impl_pw_proto_library, attrs = { "deps": attr.label_list( providers = [ProtoInfo], aspects = [_pw_nanopb_rpc_proto_compiler_aspect], ), }, ) PIGWEED_PLUGIN = { "pwpb": { "compiler": _pw_proto_library, "deps": [ "//pw_assert:facade", "//pw_containers:vector", "//pw_preprocessor", "//pw_protobuf", "//pw_result", "//pw_span", "//pw_status", ], "include_nanopb_dep": False, "include_pwpb_dep": False, }, "pwpb_rpc": { "compiler": _pw_pwpb_rpc_proto_library, "deps": [ "//pw_protobuf:pw_protobuf", "//pw_rpc", "//pw_rpc/pwpb:client_api", "//pw_rpc/pwpb:server_api", ], "include_nanopb_dep": False, "include_pwpb_dep": True, }, "raw_rpc": { "compiler": _pw_raw_rpc_proto_library, "deps": [ "//pw_rpc", "//pw_rpc/raw:client_api", "//pw_rpc/raw:server_api", ], "include_nanopb_dep": False, "include_pwpb_dep": False, }, "nanopb_rpc": { "compiler": _pw_nanopb_rpc_proto_library, "deps": [ "//pw_rpc", "//pw_rpc/nanopb:client_api", "//pw_rpc/nanopb:server_api", ], "include_nanopb_dep": True, "include_pwpb_dep": False, }, }
35.560345
133
0.664727
# Copyright 2022 The Pigweed Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. """WORK IN PROGRESS! This is intended to be a replacement for the proto codegen in proto.bzl, which relies on the transitive proto compilation support removed from newer versions of rules_proto_grpc. However, the version checked in here does not yet support, 1. Proto libraries with dependencies in external repositories. 2. Proto libraries with strip_import_prefix or import_prefix attributes. In addition, nanopb proto files are not yet generated. TODO(pwbug/621): Close these gaps and start using this implementation. # Overview of implementation (If you just want to use pw_proto_library, see its docstring; this section is intended to orient future maintainers.) Proto code generation is carried out by the _pw_proto_library, _pw_raw_rpc_proto_library and _pw_nanopb_rpc_proto_library rules using aspects (https://docs.bazel.build/versions/main/skylark/aspects.html). A _pw_proto_library has a single proto_library as a dependency, but that proto_library may depend on other proto_library targets; as a result, the generated .pwpb.h file #include's .pwpb.h files generated from the dependency proto_libraries. The aspect propagates along the proto_library dependency graph, running the proto compiler on each proto_library in the original target's transitive dependencies, ensuring that we're not missing any .pwpb.h files at C++ compile time. Although we have a separate rule for each protocol compiler plugin (_pw_proto_library, _pw_raw_rpc_proto_library, _pw_nanopb_rpc_proto_library), they actually share an implementation (_pw _impl_pw_proto_library) and use similar aspects, all generated by _proto_compiler_aspect. The only difference between the rules are captured in the PIGWEED_PLUGIN dictonary and the aspect instantiations (_pw_proto_compiler_aspect, etc). """ load("//pw_build:pigweed.bzl", "pw_cc_library") load("@rules_proto//proto:defs.bzl", "ProtoInfo") load("//pw_protobuf_compiler:pw_nanopb_cc_library", "pw_nanopb_cc_library") def pw_proto_library( name = "", deps = [], nanopb_options = None, enabled_targets = None): """Generate Pigweed proto C++ code. This is the only public symbol in this file: everything else is implementation details. Args: name: The name of the target. deps: proto_library targets from which to generate Pigweed C++. nanopb_options: path to file containing nanopb options, if any (https://jpa.kapsi.fi/nanopb/docs/reference.html#proto-file-options). enabled_targets: Specifies which libraries should be generated. Libraries will only be generated as needed, but unnecessary outputs may conflict with other build rules and thus cause build failures. This filter allows manual selection of which libraries should be supported by this build target in order to prevent such conflicts. The argument, if provided, should be a subset of ["pwpb", "nanopb", "raw_rpc", "nanopb_rpc"]. All are enabled by default. Note that "nanopb_rpc" relies on "nanopb". Example usage: proto_library( name = "benchmark_proto", srcs = [ "benchmark.proto", ], ) pw_proto_library( name = "benchmark_pw_proto", deps = [":benchmark_proto"], ) pw_cc_binary( name = "proto_user", srcs = ["proto_user.cc"], deps = [":benchmark_pw_proto.pwpb"], ) The pw_proto_library generates the following targets in this example: "benchmark_pw_proto.pwpb": C++ library exposing the "benchmark.pwpb.h" header. "benchmark_pw_proto.pwpb_rpc": C++ library exposing the "benchmark.rpc.pwpb.h" header. "benchmark_pw_proto.raw_rpc": C++ library exposing the "benchmark.raw_rpc.h" header. "benchmark_pw_proto.nanopb": C++ library exposing the "benchmark.pb.h" header. "benchmark_pw_proto.nanopb_rpc": C++ library exposing the "benchmark.rpc.pb.h" header. """ def is_plugin_enabled(plugin): return (enabled_targets == None or plugin in enabled_targets) if is_plugin_enabled("nanobp"): # Use nanopb to generate the pb.h and pb.c files, and the target # exposing them. pw_nanopb_cc_library(name + ".nanopb", deps, options = nanopb_options) # Use Pigweed proto plugins to generate the remaining files and targets. for plugin_name, info in PIGWEED_PLUGIN.items(): if not is_plugin_enabled(plugin_name): continue name_pb = name + "_pb." + plugin_name plugin_rule = info["compiler"] plugin_rule( name = name_pb, deps = deps, ) # The rpc.pb.h header depends on the generated nanopb or pwpb code. if info["include_nanopb_dep"]: lib_deps = info["deps"] + [":" + name + ".nanopb"] elif info["include_pwpb_dep"]: lib_deps = info["deps"] + [":" + name + ".pwpb"] else: lib_deps = info["deps"] pw_cc_library( name = name + "." + plugin_name, hdrs = [name_pb], deps = lib_deps, linkstatic = 1, ) PwProtoInfo = provider( "Returned by PW proto compilation aspect", fields = { "genfiles": "generated C++ header files", }, ) def _get_short_path(source): return source.short_path def _get_path(file): return file.path def _proto_compiler_aspect_impl(target, ctx): # List the files we will generate for this proto_library target. genfiles = [] for src in target[ProtoInfo].direct_sources: path = src.basename[:-len("proto")] + ctx.attr._extension genfiles.append(ctx.actions.declare_file(path, sibling = src)) args = ctx.actions.args() args.add("--plugin=protoc-gen-pwpb={}".format(ctx.executable._protoc_plugin.path)) args.add("--pwpb_out={}".format(ctx.bin_dir.path)) args.add_joined( "--descriptor_set_in", target[ProtoInfo].transitive_descriptor_sets, join_with = ctx.host_configuration.host_path_separator, map_each = _get_path, ) args.add_all(target[ProtoInfo].direct_sources, map_each = _get_short_path) ctx.actions.run( inputs = depset(target[ProtoInfo].transitive_sources.to_list(), transitive = [target[ProtoInfo].transitive_descriptor_sets]), progress_message = "Generating %s C++ files for %s" % (ctx.attr._extension, ctx.label.name), tools = [ctx.executable._protoc_plugin], outputs = genfiles, executable = ctx.executable._protoc, arguments = [args], ) transitive_genfiles = genfiles for dep in ctx.rule.attr.deps: transitive_genfiles += dep[PwProtoInfo].genfiles return [PwProtoInfo(genfiles = transitive_genfiles)] def _proto_compiler_aspect(extension, protoc_plugin): """Returns an aspect that runs the proto compiler. The aspect propagates through the deps of proto_library targets, running the proto compiler with the specified plugin for each of their source files. The proto compiler is assumed to produce one output file per input .proto file. That file is placed under bazel-bin at the same path as the input file, but with the specified extension (i.e., with _extension = .pwpb.h, the aspect converts pw_log/log.proto into bazel-bin/pw_log/log.pwpb.h). The aspect returns a provider exposing all the File objects generated from the dependency graph. """ return aspect( attr_aspects = ["deps"], attrs = { "_extension": attr.string(default = extension), "_protoc": attr.label( default = Label("@com_google_protobuf//:protoc"), executable = True, cfg = "exec", ), "_protoc_plugin": attr.label( default = Label(protoc_plugin), executable = True, cfg = "exec", ), }, implementation = _proto_compiler_aspect_impl, provides = [PwProtoInfo], ) def _impl_pw_proto_library(ctx): """Implementation of the proto codegen rule. The work of actually generating the code is done by the aspect, so here we just gather up all the generated files and return them. """ # Note that we don't distinguish between the files generated from the # target, and the files generated from its dependencies. We return all of # them together, and in pw_proto_library expose all of them as hdrs. # Pigweed's plugins happen to only generate .h files, so this works, but # strictly speaking we should expose only the files generated from the # target itself in hdrs, and place the headers generated from dependencies # in srcs. We don't perform layering_check in Pigweed, so this is not a big # deal. # # TODO(pwbug/621): Tidy this up. all_genfiles = [] for dep in ctx.attr.deps: for f in dep[PwProtoInfo].genfiles: all_genfiles.append(f) return [DefaultInfo(files = depset(all_genfiles))] # Instantiate the aspects and rules for generating code using specific plugins. _pw_proto_compiler_aspect = _proto_compiler_aspect("pwpb.h", "//pw_protobuf/py:plugin") _pw_proto_library = rule( implementation = _impl_pw_proto_library, attrs = { "deps": attr.label_list( providers = [ProtoInfo], aspects = [_pw_proto_compiler_aspect], ), }, ) _pw_pwpb_rpc_proto_compiler_aspect = _proto_compiler_aspect("rpc.pwpb.h", "//pw_rpc/py:plugin_pwpb") _pw_pwpb_rpc_proto_library = rule( implementation = _impl_pw_proto_library, attrs = { "deps": attr.label_list( providers = [ProtoInfo], aspects = [_pw_pwpb_rpc_proto_compiler_aspect], ), }, ) _pw_raw_rpc_proto_compiler_aspect = _proto_compiler_aspect("raw_rpc.pb.h", "//pw_rpc/py:plugin_raw") _pw_raw_rpc_proto_library = rule( implementation = _impl_pw_proto_library, attrs = { "deps": attr.label_list( providers = [ProtoInfo], aspects = [_pw_raw_rpc_proto_compiler_aspect], ), }, ) _pw_nanopb_rpc_proto_compiler_aspect = _proto_compiler_aspect("rpc.pb.h", "//pw_rpc/py:plugin_nanopb") _pw_nanopb_rpc_proto_library = rule( implementation = _impl_pw_proto_library, attrs = { "deps": attr.label_list( providers = [ProtoInfo], aspects = [_pw_nanopb_rpc_proto_compiler_aspect], ), }, ) PIGWEED_PLUGIN = { "pwpb": { "compiler": _pw_proto_library, "deps": [ "//pw_assert:facade", "//pw_containers:vector", "//pw_preprocessor", "//pw_protobuf", "//pw_result", "//pw_span", "//pw_status", ], "include_nanopb_dep": False, "include_pwpb_dep": False, }, "pwpb_rpc": { "compiler": _pw_pwpb_rpc_proto_library, "deps": [ "//pw_protobuf:pw_protobuf", "//pw_rpc", "//pw_rpc/pwpb:client_api", "//pw_rpc/pwpb:server_api", ], "include_nanopb_dep": False, "include_pwpb_dep": True, }, "raw_rpc": { "compiler": _pw_raw_rpc_proto_library, "deps": [ "//pw_rpc", "//pw_rpc/raw:client_api", "//pw_rpc/raw:server_api", ], "include_nanopb_dep": False, "include_pwpb_dep": False, }, "nanopb_rpc": { "compiler": _pw_nanopb_rpc_proto_library, "deps": [ "//pw_rpc", "//pw_rpc/nanopb:client_api", "//pw_rpc/nanopb:server_api", ], "include_nanopb_dep": True, "include_pwpb_dep": False, }, }
1,490
0
96
85a6fdd6b78aab7569aa64c0b0f9759be6c49e9d
4,844
py
Python
src/aquarium/trace/upload.py
aquariumbio/aquarium-provenance
63879b181608a9857a4fe514b2d7d0182ca25ed8
[ "MIT" ]
1
2019-03-28T04:10:15.000Z
2019-03-28T04:10:15.000Z
src/aquarium/trace/upload.py
klavinslab/aquarium-provenance
63879b181608a9857a4fe514b2d7d0182ca25ed8
[ "MIT" ]
1
2020-11-16T19:20:33.000Z
2020-11-16T19:20:33.000Z
src/aquarium/trace/upload.py
klavinslab/aquarium-provenance
63879b181608a9857a4fe514b2d7d0182ca25ed8
[ "MIT" ]
null
null
null
import hashlib import json import logging import os from aquarium.provenance import (FileEntity, FileTypes, JobActivity, OperationActivity, ProvenanceTrace) from typing import List, Union
34.35461
78
0.572461
import hashlib import json import logging import os from aquarium.provenance import (FileEntity, FileTypes, JobActivity, OperationActivity, ProvenanceTrace) from typing import List, Union class UploadManager: def __init__(self, *, trace: ProvenanceTrace, basepath=None, bucket=None, s3=None): self.trace = trace self.basepath = None self.bucket = None self.s3 = None def configure(self, *, s3=None, bucket=None, basepath=None): if s3: self.s3 = s3 if bucket: self.bucket = bucket if basepath: self.basepath = basepath def upload(self, *, activity: Union[OperationActivity, JobActivity]): """ Uploads files generated by the given activity if there are any to a subdirectory named after the activity_id. Adds a manifest file to the subdirectory that includes the file name, size and sha256 checksum. Does not upload the provenance. """ activity_id = activity.get_activity_id() file_list = self.trace.get_files(generator=activity) if not file_list: logging.debug("No files for generator %s", activity_id) return dest_path = os.path.join(self.basepath, activity_id) self._upload_directory(path=dest_path, file_list=file_list) def upload_provenance(self): """ Uploads the provenance stored in this manager. """ self._put_provenance(path=self.basepath, trace=self.trace) def _upload_directory(self, *, path, file_list: List[FileEntity]): """ Uploads the files in the file list along with a manifest to the given path. """ files = list() for file_entity in file_list: if file_entity.is_external(): continue logging.debug("Uploading %s", file_entity.name) content_type = self._get_content_type(file_entity) try: file_object = file_entity.upload.data except ConnectionError: logging.error( "Upload of file %s (%s) failed due to closed connection", file_entity.id, file_entity.name ) raise hash_sha = hashlib.sha256() hash_sha.update(file_object) file_entity.check_sum = str(hash_sha.hexdigest()) self._put_object(path=path, filename=file_entity.name, file_object=file_object, content_type=content_type) files.append({ 'name': file_entity.name, 'size': file_entity.size, 'sha256': file_entity.check_sum }) if not files: return self._put_object(path=path, filename='upload_manifest.json', file_object=json.dumps(files, indent=2), content_type="application/json" ) def _get_content_type(self, file_entity: FileEntity) -> str: content_type = file_entity.upload.upload_content_type if file_entity.type == FileTypes.FCS: content_type = 'application/octet-stream' elif file_entity.type == FileTypes.CSV: content_type = 'text/csv' return content_type def _put_object(self, *, path, filename: str, file_object, content_type: str): key_path = os.path.join(path, filename) logging.info("upload %s to %s", key_path, self.bucket) self.s3.put_object( Body=file_object, Bucket=self.bucket, ContentType=content_type, Key=key_path ) def _put_provenance(self, *, path, trace: ProvenanceTrace): self._put_object( path=path, filename='provenance_dump.json', file_object=str(json.dumps(trace.as_dict(), indent=2)), content_type='application/json' ) class S3DumpProxy: def __init__(self, root_dir): self.root_dir = root_dir def put_object(self, *, Body, Bucket, ContentType, Key): # make directory root_dir/Bucket/Key minus file name # write Body to path = os.path.join(*[self.root_dir, Bucket, Key]) directory_path = os.path.join(*(str.split(path, os.sep)[:-1])) if ContentType == 'application/json': output = Body else: output = "would write file to {}".format(path) if not os.path.exists(directory_path): os.makedirs(directory_path) with open(path, 'w') as file: file.write(output)
1,886
2,601
100
5973ac4755bc832fd1e7494ecdcd663b65d8e774
3,197
py
Python
metadrive/utils/interpolating_line.py
liuzuxin/metadrive
850c207536531bc85179084acd7c30ab14a66111
[ "Apache-2.0" ]
125
2021-08-30T06:33:57.000Z
2022-03-31T09:02:44.000Z
metadrive/utils/interpolating_line.py
liuzuxin/metadrive
850c207536531bc85179084acd7c30ab14a66111
[ "Apache-2.0" ]
72
2021-08-30T16:23:41.000Z
2022-03-31T19:17:16.000Z
metadrive/utils/interpolating_line.py
liuzuxin/metadrive
850c207536531bc85179084acd7c30ab14a66111
[ "Apache-2.0" ]
20
2021-09-09T08:20:25.000Z
2022-03-24T13:24:07.000Z
import math import numpy as np from metadrive.utils.math_utils import norm class InterpolatingLine: """ This class provides point set with interpolating function """ @staticmethod @staticmethod @staticmethod @staticmethod def get_point(self, longitudinal, lateral=None): """ Get point on this line by interpolating """ accumulate_len = 0 for seg in self.segment_property: accumulate_len += seg["length"] if accumulate_len + 0.1 >= longitudinal: break if lateral is not None: return (seg["start_point"] + (longitudinal - accumulate_len + seg["length"]) * seg["direction"]) + lateral * seg["lateral_direction"] else: return seg["start_point"] + (longitudinal - accumulate_len + seg["length"]) * seg["direction"] def get_heading_theta(self, longitudinal: float) -> float: """ In rad """ accumulate_len = 0 for seg in self.segment_property: accumulate_len += seg["length"] if accumulate_len > longitudinal: return seg["heading"] return seg["heading"] def segment(self, longitudinal: float): """ Return the segment piece on this lane of current position """ accumulate_len = 0 for index, seg in enumerate(self.segment_property): accumulate_len += seg["length"] if accumulate_len + 0.1 >= longitudinal: return self.segment_property[index] return self.segment_property[index]
34.010638
106
0.598061
import math import numpy as np from metadrive.utils.math_utils import norm class InterpolatingLine: """ This class provides point set with interpolating function """ def __init__(self, points): self.segment_property = self._get_properties(points) self.length = sum([seg["length"] for seg in self.segment_property]) def _get_properties(self, points): ret = [] for idx, p_start in enumerate(points[:-1]): p_end = points[idx + 1] seg_property = { "length": self.points_distance(p_start, p_end), "direction": self.points_direction(p_start, p_end), "lateral_direction": self.points_lateral_direction(p_start, p_end), "heading": self.points_heading(p_start, p_end), "start_point": p_start, "end_point": p_end } ret.append(seg_property) return ret @staticmethod def points_distance(start_p, end_p): return norm((end_p - start_p)[0], (end_p - start_p)[1]) @staticmethod def points_direction(start_p, end_p): return (end_p - start_p) / norm((end_p - start_p)[0], (end_p - start_p)[1]) @staticmethod def points_lateral_direction(start_p, end_p): direction = (end_p - start_p) / norm((end_p - start_p)[0], (end_p - start_p)[1]) return np.array([-direction[1], direction[0]]) @staticmethod def points_heading(start_p, end_p): return math.atan2(end_p[1] - start_p[1], end_p[0] - start_p[0]) def get_point(self, longitudinal, lateral=None): """ Get point on this line by interpolating """ accumulate_len = 0 for seg in self.segment_property: accumulate_len += seg["length"] if accumulate_len + 0.1 >= longitudinal: break if lateral is not None: return (seg["start_point"] + (longitudinal - accumulate_len + seg["length"]) * seg["direction"]) + lateral * seg["lateral_direction"] else: return seg["start_point"] + (longitudinal - accumulate_len + seg["length"]) * seg["direction"] def get_heading_theta(self, longitudinal: float) -> float: """ In rad """ accumulate_len = 0 for seg in self.segment_property: accumulate_len += seg["length"] if accumulate_len > longitudinal: return seg["heading"] return seg["heading"] def segment(self, longitudinal: float): """ Return the segment piece on this lane of current position """ accumulate_len = 0 for index, seg in enumerate(self.segment_property): accumulate_len += seg["length"] if accumulate_len + 0.1 >= longitudinal: return self.segment_property[index] return self.segment_property[index] def lateral_direction(self, longitude): lane_segment = self.segment(longitude) lateral = lane_segment["lateral_direction"] return lateral def destroy(self): self.segment_property = None self.length = None
1,349
0
211
f539a6e9c103aca6a5bb59916fb5b8fef3519e25
6,906
py
Python
tests/test_storage.py
andher1802/dummy_0532
fb953c2785652c583d1147a2b688997e260e6afa
[ "MIT" ]
null
null
null
tests/test_storage.py
andher1802/dummy_0532
fb953c2785652c583d1147a2b688997e260e6afa
[ "MIT" ]
null
null
null
tests/test_storage.py
andher1802/dummy_0532
fb953c2785652c583d1147a2b688997e260e6afa
[ "MIT" ]
null
null
null
import pytest # pylint: disable=unused-import from .context import Storage, Asset, Order from .fixtures import ( ASSET_ID, ORDER_ID, WORKSPACE_ID, auth_mock, auth_live, storage_mock, storage_live, JSON_ASSET, JSON_ORDER, ) def test_paginate_with_limit_smaller_page_size(storage_mock, requests_mock): """ Test pagination with limit <= pagination size. """ url = "http://some_url/assets" limit = 5 size = limit total_pages = 2 total_elements = 12 expected = 5 requests_mock.get( url + f"&size={limit}", json=_mock_one_page_reponse(0, size, total_pages, total_elements), ) requests_mock.get( url + f"&size={limit}&page=1", json=_mock_one_page_reponse(0, size, total_pages, total_elements), ) res = storage_mock._query_paginated(url=url, limit=limit, size=size) assert len(res) == expected @pytest.mark.live def test_get_assets_live(storage_live): """ SDK test account holds too few results to query multiple pages via pagination, needs to be mocked. """ assets = storage_live.get_assets() assert len(assets) >= 2 dates = [asset.info["createdAt"] for asset in assets] # default descending, newest to oldest. descending_dates = sorted(dates)[::-1] assert descending_dates == dates def test_get_assets_pagination(auth_mock, requests_mock): """ Mock result holds 2 pages, each with 50 results. """ json_assets_paginated = { "data": { "content": [JSON_ASSET["data"]] * 50, "pageable": { "sort": {"sorted": True, "unsorted": False, "empty": False}, "pageNumber": 0, "pageSize": 50, "offset": 0, "paged": True, "unpaged": False, }, "totalPages": 2, "totalElements": 100, "last": True, "sort": {"sorted": True, "unsorted": False, "empty": False}, "numberOfElements": 100, "first": True, "size": 50, "number": 0, "empty": False, }, "error": None, } # assets pages url_storage_assets_paginated = ( f"{auth_mock._endpoint()}/workspaces/{auth_mock.workspace_id}/" f"assets?format=paginated&sort=createdAt,asc&size=50" ) requests_mock.get(url=url_storage_assets_paginated, json=json_assets_paginated) storage = Storage(auth=auth_mock) assets = storage.get_assets(limit=74, sortby="createdAt", descending=False) assert len(assets) == 74 assert isinstance(assets[0], Asset) assert assets[0].asset_id == ASSET_ID @pytest.mark.live def test_get_orders_live(storage_live): """ SDK test account holds too few results to query multiple pages via pagination, needs to be mocked. """ orders = storage_live.get_orders() assert len(orders) >= 1 dates = [order.info["createdAt"] for order in orders] # default descending, newest to oldest. descending_dates = sorted(dates)[::-1] assert descending_dates == dates def test_get_orders_pagination(auth_mock, requests_mock): """ Mock result holds 2 pages, each with 50 results. """ json_orders_paginated = { "data": { "content": [JSON_ORDER["data"]] * 50, "pageable": { "sort": {"sorted": True, "unsorted": False, "empty": False}, "pageNumber": 0, "pageSize": 50, "offset": 0, "paged": True, "unpaged": False, }, "totalPages": 2, "totalElements": 100, "last": True, "sort": {"sorted": True, "unsorted": False, "empty": False}, "numberOfElements": 100, "first": True, "size": 50, "number": 0, "empty": False, }, "error": None, } # assets pages url_storage_orders_paginated = ( f"{auth_mock._endpoint()}/workspaces/{auth_mock.workspace_id}/" f"orders?format=paginated&sort=createdAt,asc&size=50" ) requests_mock.get(url=url_storage_orders_paginated, json=json_orders_paginated) storage = Storage(auth=auth_mock) orders = storage.get_orders(limit=74, sortby="createdAt", descending=False) assert len(orders) == 74 assert isinstance(orders[0], Order) assert orders[0].order_id == ORDER_ID
29.387234
83
0.62062
import pytest # pylint: disable=unused-import from .context import Storage, Asset, Order from .fixtures import ( ASSET_ID, ORDER_ID, WORKSPACE_ID, auth_mock, auth_live, storage_mock, storage_live, JSON_ASSET, JSON_ORDER, ) def test_init(storage_mock): assert isinstance(storage_mock, Storage) assert storage_mock.workspace_id == WORKSPACE_ID def _mock_one_page_reponse(page_nr, size, total_pages, total_elements): return { "data": { "content": [{"something1": 1}] * size, "totalPages": total_pages, "totalElements": total_elements, "number": page_nr, }, } def test_paginate_one_page(storage_mock, requests_mock): url = "http://some_url/assets" limit = None size = 50 total_pages = 1 total_elements = 30 expected = 30 requests_mock.get( url + f"&size={size}", json=_mock_one_page_reponse(0, expected, total_pages, total_elements), ) res = storage_mock._query_paginated(url=url, limit=limit, size=size) assert len(res) == expected def test_paginate_multiple_pages(storage_mock, requests_mock): url = "http://some_url/assets" limit = 20 size = 3 total_pages = 4 total_elements = 12 expected = 12 requests_mock.get( url + f"&size={size}", json=_mock_one_page_reponse(0, size, total_pages, total_elements), ) requests_mock.get( url + f"&size={size}&page=1", json=_mock_one_page_reponse(1, size, total_pages, total_elements), ) requests_mock.get( url + f"&size={size}&page=2", json=_mock_one_page_reponse(2, size, total_pages, total_elements), ) requests_mock.get( url + f"&size={size}&page=3", json=_mock_one_page_reponse(3, size, total_pages, total_elements), ) res = storage_mock._query_paginated(url=url, limit=limit, size=size) assert len(res) == expected def test_paginate_with_limit_smaller_page_size(storage_mock, requests_mock): """ Test pagination with limit <= pagination size. """ url = "http://some_url/assets" limit = 5 size = limit total_pages = 2 total_elements = 12 expected = 5 requests_mock.get( url + f"&size={limit}", json=_mock_one_page_reponse(0, size, total_pages, total_elements), ) requests_mock.get( url + f"&size={limit}&page=1", json=_mock_one_page_reponse(0, size, total_pages, total_elements), ) res = storage_mock._query_paginated(url=url, limit=limit, size=size) assert len(res) == expected def test_get_assets(storage_mock): assets = storage_mock.get_assets() assert len(assets) == 1 assert isinstance(assets[0], Asset) assert assets[0].asset_id == ASSET_ID @pytest.mark.live def test_get_assets_live(storage_live): """ SDK test account holds too few results to query multiple pages via pagination, needs to be mocked. """ assets = storage_live.get_assets() assert len(assets) >= 2 dates = [asset.info["createdAt"] for asset in assets] # default descending, newest to oldest. descending_dates = sorted(dates)[::-1] assert descending_dates == dates def test_get_assets_pagination(auth_mock, requests_mock): """ Mock result holds 2 pages, each with 50 results. """ json_assets_paginated = { "data": { "content": [JSON_ASSET["data"]] * 50, "pageable": { "sort": {"sorted": True, "unsorted": False, "empty": False}, "pageNumber": 0, "pageSize": 50, "offset": 0, "paged": True, "unpaged": False, }, "totalPages": 2, "totalElements": 100, "last": True, "sort": {"sorted": True, "unsorted": False, "empty": False}, "numberOfElements": 100, "first": True, "size": 50, "number": 0, "empty": False, }, "error": None, } # assets pages url_storage_assets_paginated = ( f"{auth_mock._endpoint()}/workspaces/{auth_mock.workspace_id}/" f"assets?format=paginated&sort=createdAt,asc&size=50" ) requests_mock.get(url=url_storage_assets_paginated, json=json_assets_paginated) storage = Storage(auth=auth_mock) assets = storage.get_assets(limit=74, sortby="createdAt", descending=False) assert len(assets) == 74 assert isinstance(assets[0], Asset) assert assets[0].asset_id == ASSET_ID def test_get_assets_raises_with_illegal_sorting_criteria(storage_mock): with pytest.raises(ValueError): storage_mock.get_assets(sortby="notavailable") def test_get_orders(storage_mock): orders = storage_mock.get_orders() assert len(orders) == 1 assert isinstance(orders[0], Order) assert orders[0].order_id == ORDER_ID @pytest.mark.live def test_get_orders_live(storage_live): """ SDK test account holds too few results to query multiple pages via pagination, needs to be mocked. """ orders = storage_live.get_orders() assert len(orders) >= 1 dates = [order.info["createdAt"] for order in orders] # default descending, newest to oldest. descending_dates = sorted(dates)[::-1] assert descending_dates == dates def test_get_orders_raises_with_illegal_sorting_criteria(storage_mock): with pytest.raises(ValueError): storage_mock.get_orders(sortby="notavailable") def test_get_orders_pagination(auth_mock, requests_mock): """ Mock result holds 2 pages, each with 50 results. """ json_orders_paginated = { "data": { "content": [JSON_ORDER["data"]] * 50, "pageable": { "sort": {"sorted": True, "unsorted": False, "empty": False}, "pageNumber": 0, "pageSize": 50, "offset": 0, "paged": True, "unpaged": False, }, "totalPages": 2, "totalElements": 100, "last": True, "sort": {"sorted": True, "unsorted": False, "empty": False}, "numberOfElements": 100, "first": True, "size": 50, "number": 0, "empty": False, }, "error": None, } # assets pages url_storage_orders_paginated = ( f"{auth_mock._endpoint()}/workspaces/{auth_mock.workspace_id}/" f"orders?format=paginated&sort=createdAt,asc&size=50" ) requests_mock.get(url=url_storage_orders_paginated, json=json_orders_paginated) storage = Storage(auth=auth_mock) orders = storage.get_orders(limit=74, sortby="createdAt", descending=False) assert len(orders) == 74 assert isinstance(orders[0], Order) assert orders[0].order_id == ORDER_ID
2,216
0
184
ea4268c8ca3f837d893737284413554e35d72642
902
py
Python
ansible/venv/lib/python2.7/site-packages/ansible/plugins/doc_fragments/azure_tags.py
gvashchenkolineate/gvashchenkolineate_infra_trytravis
0fb18850afe0d8609693ba4b23f29c7cda17d97f
[ "MIT" ]
17
2017-06-07T23:15:01.000Z
2021-08-30T14:32:36.000Z
ansible/ansible/plugins/doc_fragments/azure_tags.py
SergeyCherepanov/ansible
875711cd2fd6b783c812241c2ed7a954bf6f670f
[ "MIT" ]
9
2017-06-25T03:31:52.000Z
2021-05-17T23:43:12.000Z
ansible/ansible/plugins/doc_fragments/azure_tags.py
SergeyCherepanov/ansible
875711cd2fd6b783c812241c2ed7a954bf6f670f
[ "MIT" ]
3
2018-05-26T21:31:22.000Z
2019-09-28T17:00:45.000Z
# -*- coding: utf-8 -*- # Copyright: (c) 2016, Matt Davis, <mdavis@ansible.com> # Copyright: (c) 2016, Chris Houseknecht, <house@redhat.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
34.692308
114
0.648559
# -*- coding: utf-8 -*- # Copyright: (c) 2016, Matt Davis, <mdavis@ansible.com> # Copyright: (c) 2016, Chris Houseknecht, <house@redhat.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) class ModuleDocFragment(object): # Azure doc fragment DOCUMENTATION = r''' options: tags: description: - Dictionary of string:string pairs to assign as metadata to the object. - Metadata tags on the object will be updated with any provided values. - To remove tags set append_tags option to false. type: dict append_tags: description: - Use to control if tags field is canonical or just appends to existing tags. - When canonical, any tags not found in the tags parameter will be removed from the object's metadata. type: bool default: yes '''
0
643
23
41925108c67ac2d0b73b532a142be61a3e5d52da
1,595
py
Python
cupy/testing/array.py
ytoyama/yans_chainer_hackathon
744e7a5a67da8dec2869879f0adfae2d43eaf75c
[ "MIT" ]
null
null
null
cupy/testing/array.py
ytoyama/yans_chainer_hackathon
744e7a5a67da8dec2869879f0adfae2d43eaf75c
[ "MIT" ]
1
2016-11-09T06:32:32.000Z
2016-11-09T10:20:04.000Z
cupy/testing/array.py
ytoyama/yans_chainer_hackathon
744e7a5a67da8dec2869879f0adfae2d43eaf75c
[ "MIT" ]
1
2018-11-18T00:36:51.000Z
2018-11-18T00:36:51.000Z
import numpy.testing import cupy # NumPy-like assertion functions that accept both NumPy and CuPy arrays
31.9
73
0.692163
import numpy.testing import cupy # NumPy-like assertion functions that accept both NumPy and CuPy arrays def assert_allclose(actual, desired, rtol=1e-7, atol=0, err_msg='', verbose=True): numpy.testing.assert_allclose( cupy.asnumpy(actual), cupy.asnumpy(desired), rtol=rtol, atol=atol, err_msg=err_msg, verbose=verbose) def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True): numpy.testing.assert_array_almost_equal( cupy.asnumpy(x), cupy.asnumpy(y), decimal=decimal, err_msg=err_msg, verbose=verbose) def assert_arrays_almost_equal_nulp(x, y, nulp=1): numpy.testing.assert_arrays_almost_equal_nulp( cupy.asnumpy(x), cupy.asnumpy(y), nulp=nulp) def assert_array_max_ulp(a, b, maxulp=1, dtype=None): numpy.testing.assert_array_max_ulp( cupy.asnumpy(a), cupy.asnumpy(b), maxulp=maxulp, dtype=dtype) def assert_array_equal(x, y, err_msg='', verbose=True): numpy.testing.assert_array_equal( cupy.asnumpy(x), cupy.asnumpy(y), err_msg=err_msg, verbose=verbose) def assert_array_list_equal(xlist, ylist, err_msg='', verbose=True): if len(xlist) != len(ylist): raise AssertionError('List size is different') for x, y in zip(xlist, ylist): numpy.testing.assert_array_equal( cupy.asnumpy(x), cupy.asnumpy(y), err_msg=err_msg, verbose=verbose) def assert_array_less(x, y, err_msg='', verbose=True): numpy.testing.assert_array_less( cupy.asnumpy(x), cupy.asnumpy(y), err_msg=err_msg, verbose=verbose)
1,320
0
161
64dea9b660d7caa189b81fae885d7a2ec1877248
1,870
py
Python
Models/lpa.py
zyhhhhhhh/social-and-info-networks
d1dd45fc50f55cb2ac1e1cd7cf03cdbb32c5a144
[ "MIT" ]
null
null
null
Models/lpa.py
zyhhhhhhh/social-and-info-networks
d1dd45fc50f55cb2ac1e1cd7cf03cdbb32c5a144
[ "MIT" ]
null
null
null
Models/lpa.py
zyhhhhhhh/social-and-info-networks
d1dd45fc50f55cb2ac1e1cd7cf03cdbb32c5a144
[ "MIT" ]
null
null
null
from collections import Counter import random class LPA: """ Louvain community detection """ def train(self,networks): """ No training actually takes place in this class. :param networks: list of egonet objects :return: Predictions on training networks """ # Normally some training would take place here... return self.predict(networks) def predict(self,networks): """ Randomly constract valid circles given initialized hyper parameters :param networks: :return: """ predictions = [] for egonet in networks: n = egonet.G # Initially each node is labeled by themselves label = dict(zip(n.nodes(),n.nodes())) isConverged = False while not isConverged: isConverged = True for node in n.nodes(): c = Counter(label[_] for _ in n.edge[node]) most = max(c.values()) # When the label of the node is not among the most of its neighbors' labels if c[label[node]] != max(c.values()): # Update the label to be one of the most choosed label of its beighborhood label[node] = random.choice([_ for _ in c if c[_] == most]) isConverged = False predicted_circles = {} for node in n.nodes(): if label[node] not in predicted_circles: predicted_circles[label[node]] = [node] else: predicted_circles[label[node]].append(node) predictions.append(predicted_circles) print("circles") print(predicted_circles) return predictions
30.16129
98
0.535829
from collections import Counter import random class LPA: """ Louvain community detection """ def __init__(self): pass def train(self,networks): """ No training actually takes place in this class. :param networks: list of egonet objects :return: Predictions on training networks """ # Normally some training would take place here... return self.predict(networks) def predict(self,networks): """ Randomly constract valid circles given initialized hyper parameters :param networks: :return: """ predictions = [] for egonet in networks: n = egonet.G # Initially each node is labeled by themselves label = dict(zip(n.nodes(),n.nodes())) isConverged = False while not isConverged: isConverged = True for node in n.nodes(): c = Counter(label[_] for _ in n.edge[node]) most = max(c.values()) # When the label of the node is not among the most of its neighbors' labels if c[label[node]] != max(c.values()): # Update the label to be one of the most choosed label of its beighborhood label[node] = random.choice([_ for _ in c if c[_] == most]) isConverged = False predicted_circles = {} for node in n.nodes(): if label[node] not in predicted_circles: predicted_circles[label[node]] = [node] else: predicted_circles[label[node]].append(node) predictions.append(predicted_circles) print("circles") print(predicted_circles) return predictions
11
0
27
e5453407a0260d2fa672531e2b6a6e9895a78b85
6,821
py
Python
code_for_figures/suppFig1_annualmean/cmip6_plot_annualmean_change.py
Timh37/SeasonalDSLC_NWES
9cbc155448dbd0ba07a5b95c5ce49dc3cb4a4187
[ "MIT" ]
null
null
null
code_for_figures/suppFig1_annualmean/cmip6_plot_annualmean_change.py
Timh37/SeasonalDSLC_NWES
9cbc155448dbd0ba07a5b95c5ce49dc3cb4a4187
[ "MIT" ]
null
null
null
code_for_figures/suppFig1_annualmean/cmip6_plot_annualmean_change.py
Timh37/SeasonalDSLC_NWES
9cbc155448dbd0ba07a5b95c5ce49dc3cb4a4187
[ "MIT" ]
1
2021-11-19T13:30:04.000Z
2021-11-19T13:30:04.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ #plot maps of ensemble mean annual mean dslc and wind stress change @author: thermans """ import xarray as xr import matplotlib.pyplot as plt import os import numpy as np import fnmatch import cmocean import cartopy.crs as ccrs import matplotlib import matplotlib.gridspec as gridspec from seasonal_deviations_from_monthly_means import seasonal_deviations_from_monthly_means plt.close('all') ssp = 'ssp585' in_dir = '/Volumes/Naamloos/PhD_Data/CMIP6/ensemble_netcdfs/' #input directory ensemble data out_dir = '/Users/thermans/Documents/PhD/Phase4_seasonal/Figures' #where to store the figure model_list = list(np.genfromtxt('/Users/thermans/Documents/PhD/Phase4_seasonal/Analysis/compiling_ensembles/ens_model_list_'+ssp+'.txt',dtype='str')) baseyears = np.arange(1995,2015) #reference periods futyears = np.arange(2081,2101) #load variant averaged ensemble for NWES (1x1) nwes_ds = xr.open_dataset(os.path.join(in_dir,fnmatch.filter(os.listdir(in_dir), "zos_CMIP6_ssp585_n38_nwes_variant_averaged.nc")[0])) nwes_ds = nwes_ds.sel(model=model_list) nwes_ds = nwes_ds.isel(time=np.arange(11,3011)) #start in December end in November bathy = xr.open_dataset('/Users/thermans/Documents/Modeling/ROMS/preprocessing/bathymetry/etopo1_bedrock_bigNorthSea1.nc') #get seasonal anomalies ens_djf_mean_anom, ens_jja_mean_anom, ens_mam_mean_anom, ens_son_mean_anom, ens_dec2nov_mean = seasonal_deviations_from_monthly_means(nwes_ds.zos) ens_dec2nov_mean_d = ens_dec2nov_mean - ens_dec2nov_mean.sel(year=baseyears).mean(dim='year')#change relative to base period #prepare data for plotting numfin = np.sum(np.isfinite(ens_dec2nov_mean_d.isel(year=0)),axis=0) #get number of models with ocean value for each grid point min_num = 5 a = ens_dec2nov_mean_d #winter a = a.where(np.isfinite(ens_dec2nov_mean_d.sel(year=futyears).mean(dim='year').mean(dim='model',skipna=True) )) #mask where slc masked a = a.where(numfin>min_num-1) #mask where minimum number of models with ocean value not exceeded #load wind stress taux_ds = xr.open_dataset(os.path.join(in_dir,fnmatch.filter(os.listdir(in_dir), "tauu_CMIP6_ssp585_n33_nwes_variant_averaged.nc")[0])) taux_ds = taux_ds.isel(time=np.arange(11+124*12,3011)) taux_ds = taux_ds.sel(model=model_list) taux_ds = taux_ds.where(numfin>min_num-1) #apply mask from zos taux_ds.coords['lon'] = ((taux_ds.coords['lon'] + 180) % 360) - 180 #wrap around 0 taux_ds = taux_ds.reindex({ 'lon' : np.sort(taux_ds['lon'])}) modi = np.where(np.isin(taux_ds.model.values,['CIESM', 'CMCC-CM2-SR5', 'CMCC-ESM2', 'CAS-ESM2-0', 'FIO-ESM-2-0']))[0] #defined positive westward taux_ds['tauu'][modi,...] = -1*taux_ds['tauu'][modi,...] #change sign taux_djf_mean_anom, taux_jja_mean_anom, taux_mam_mean_anom, taux_son_mean_anom, taux_dec2nov_mean = seasonal_deviations_from_monthly_means(taux_ds.tauu) #open ensemble dataset wind stress y tauy_ds = xr.open_dataset(os.path.join(in_dir,fnmatch.filter(os.listdir(in_dir), "tauv_CMIP6_ssp585_n33_nwes_variant_averaged.nc")[0])) tauy_ds = tauy_ds.isel(time=np.arange(11+124*12,3011)) tauy_ds = tauy_ds.sel(model=model_list) tauy_ds = tauy_ds.where(numfin>min_num-1) #apply mask from zos tauy_ds.coords['lon'] = ((tauy_ds.coords['lon'] + 180) % 360) - 180 #wrap around 0 tauy_ds = tauy_ds.reindex({ 'lon' : np.sort(tauy_ds['lon'])}) modi = np.where(np.isin(tauy_ds.model.values,['CIESM', 'CMCC-CM2-SR5', 'CMCC-ESM2', 'CAS-ESM2-0', 'FIO-ESM-2-0']))[0] tauy_ds['tauv'][modi,...] = -1*tauy_ds['tauv'][modi,...] tauy_djf_mean_anom, tauy_jja_mean_anom, tauy_mam_mean_anom, tauy_son_mean_anom, tauy_dec2nov_mean = seasonal_deviations_from_monthly_means(tauy_ds.tauv) #calculate change future relative to baseline taux_dec2nov_mean_d = taux_dec2nov_mean.sel(year=futyears).mean(dim='year') - taux_dec2nov_mean.sel(year=baseyears).mean(dim='year') tauy_dec2nov_mean_d = tauy_dec2nov_mean.sel(year=futyears).mean(dim='year') - tauy_dec2nov_mean.sel(year=baseyears).mean(dim='year') ####plotting my_cmap = cmocean.cm.balance #continuous colormap my_cmap.set_bad('grey') fig=plt.figure(figsize=(8,5)) gs = fig.add_gridspec(1,2) gs.update(hspace = 0.75,wspace=0.3,right=.84,top=.95,bottom=.05) #annual mean slc ax3 = plt.subplot(gs[0,0], projection=ccrs.Orthographic(0, 50)) #maps p=(100*a).sel(year=futyears).mean(dim='year').mean(dim='model').plot(transform=ccrs.PlateCarree(),ax=ax3,vmin=-25,vmax=25,cmap=my_cmap,add_colorbar=False) p.set_edgecolor('face') #avoid white lines in pdf rendering bathy.Band1.plot.contour(transform=ccrs.PlateCarree(),ax=ax3,levels=[-200],colors=['white'],add_colorbar=False) #shelf break ax3.coastlines(resolution='50m',color='black',linewidth=1) gl = ax3.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,linewidth=1, color='lightgrey', alpha=0, linestyle='-') gl.top_labels = gl.right_labels = False #don't label top and right axes gl.xlabel_style = {'color': 'black','rotation':0} gl.ylabel_style = {'color': 'black','rotation':0} ax3.set_extent([-9.5,9,45,60]) #set longitude & latitude extent ax3.set_title('(a)') #subplot title cax = fig.add_axes([0.125, .15, .312, .02]) fig.colorbar(p, cax=cax,orientation='horizontal',label='SLC [cm]') #annual mean wind-stress change my_cmap = cmocean.cm.tempo my_cmap.set_bad('grey') abs_d = np.sqrt(taux_dec2nov_mean_d.mean(dim='model')**2+tauy_dec2nov_mean_d.mean(dim='model')**2) #absolute change ax1 = plt.subplot(gs[0,1], projection=ccrs.Orthographic(0, 50)) #maps im = abs_d.plot(transform=ccrs.PlateCarree(),ax=ax1,vmin=0,vmax=.03,cmap=my_cmap,add_colorbar=False) bathy.Band1.plot.contour(transform=ccrs.PlateCarree(),ax=ax1,levels=[-200],colors=['white'],add_colorbar=False) im.set_edgecolor('face') #avoid whitespace between grid cells when rendering x=taux_djf_mean_anom.lon.values #quivers y=taux_djf_mean_anom.lat.values u = taux_dec2nov_mean_d.mean(dim='model').values v = tauy_dec2nov_mean_d.mean(dim='model').values q=ax1.quiver(x,y,u,v,transform=ccrs.PlateCarree(),scale=.2,color='black',width=.007,edgecolors='k',zorder=5) qk = ax1.quiverkey(q, 0.73, 0.239, 0.02, label='0.02 N/m'r'$^{2}$', labelpos='E', coordinates='figure') #quiver key on scale ax1.coastlines(resolution='50m',color='black') ax1.set_extent([-9.5,9,45,60]) ax1.set_title('(b)') gl = ax1.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,linewidth=1, color='lightgrey', alpha=0, linestyle='-') gl.top_labels = gl.right_labels = gl.left_labels = False #don't label top and right axes gl.xlabel_style = {'color': 'black','rotation':0} gl.ylabel_style = {'color': 'black','rotation':0} cax = fig.add_axes([0.529, .15, .312, .02]) fig.colorbar(im, cax=cax,orientation='horizontal',label='Wind-stress change [N/m'r'$^{2}$'']') #fig.savefig(os.path.join(out_dir,'suppFigure1_annualmean_change_ssp585.pdf'),dpi=300)
50.525926
154
0.756341
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ #plot maps of ensemble mean annual mean dslc and wind stress change @author: thermans """ import xarray as xr import matplotlib.pyplot as plt import os import numpy as np import fnmatch import cmocean import cartopy.crs as ccrs import matplotlib import matplotlib.gridspec as gridspec from seasonal_deviations_from_monthly_means import seasonal_deviations_from_monthly_means plt.close('all') ssp = 'ssp585' in_dir = '/Volumes/Naamloos/PhD_Data/CMIP6/ensemble_netcdfs/' #input directory ensemble data out_dir = '/Users/thermans/Documents/PhD/Phase4_seasonal/Figures' #where to store the figure model_list = list(np.genfromtxt('/Users/thermans/Documents/PhD/Phase4_seasonal/Analysis/compiling_ensembles/ens_model_list_'+ssp+'.txt',dtype='str')) baseyears = np.arange(1995,2015) #reference periods futyears = np.arange(2081,2101) #load variant averaged ensemble for NWES (1x1) nwes_ds = xr.open_dataset(os.path.join(in_dir,fnmatch.filter(os.listdir(in_dir), "zos_CMIP6_ssp585_n38_nwes_variant_averaged.nc")[0])) nwes_ds = nwes_ds.sel(model=model_list) nwes_ds = nwes_ds.isel(time=np.arange(11,3011)) #start in December end in November bathy = xr.open_dataset('/Users/thermans/Documents/Modeling/ROMS/preprocessing/bathymetry/etopo1_bedrock_bigNorthSea1.nc') #get seasonal anomalies ens_djf_mean_anom, ens_jja_mean_anom, ens_mam_mean_anom, ens_son_mean_anom, ens_dec2nov_mean = seasonal_deviations_from_monthly_means(nwes_ds.zos) ens_dec2nov_mean_d = ens_dec2nov_mean - ens_dec2nov_mean.sel(year=baseyears).mean(dim='year')#change relative to base period #prepare data for plotting numfin = np.sum(np.isfinite(ens_dec2nov_mean_d.isel(year=0)),axis=0) #get number of models with ocean value for each grid point min_num = 5 a = ens_dec2nov_mean_d #winter a = a.where(np.isfinite(ens_dec2nov_mean_d.sel(year=futyears).mean(dim='year').mean(dim='model',skipna=True) )) #mask where slc masked a = a.where(numfin>min_num-1) #mask where minimum number of models with ocean value not exceeded #load wind stress taux_ds = xr.open_dataset(os.path.join(in_dir,fnmatch.filter(os.listdir(in_dir), "tauu_CMIP6_ssp585_n33_nwes_variant_averaged.nc")[0])) taux_ds = taux_ds.isel(time=np.arange(11+124*12,3011)) taux_ds = taux_ds.sel(model=model_list) taux_ds = taux_ds.where(numfin>min_num-1) #apply mask from zos taux_ds.coords['lon'] = ((taux_ds.coords['lon'] + 180) % 360) - 180 #wrap around 0 taux_ds = taux_ds.reindex({ 'lon' : np.sort(taux_ds['lon'])}) modi = np.where(np.isin(taux_ds.model.values,['CIESM', 'CMCC-CM2-SR5', 'CMCC-ESM2', 'CAS-ESM2-0', 'FIO-ESM-2-0']))[0] #defined positive westward taux_ds['tauu'][modi,...] = -1*taux_ds['tauu'][modi,...] #change sign taux_djf_mean_anom, taux_jja_mean_anom, taux_mam_mean_anom, taux_son_mean_anom, taux_dec2nov_mean = seasonal_deviations_from_monthly_means(taux_ds.tauu) #open ensemble dataset wind stress y tauy_ds = xr.open_dataset(os.path.join(in_dir,fnmatch.filter(os.listdir(in_dir), "tauv_CMIP6_ssp585_n33_nwes_variant_averaged.nc")[0])) tauy_ds = tauy_ds.isel(time=np.arange(11+124*12,3011)) tauy_ds = tauy_ds.sel(model=model_list) tauy_ds = tauy_ds.where(numfin>min_num-1) #apply mask from zos tauy_ds.coords['lon'] = ((tauy_ds.coords['lon'] + 180) % 360) - 180 #wrap around 0 tauy_ds = tauy_ds.reindex({ 'lon' : np.sort(tauy_ds['lon'])}) modi = np.where(np.isin(tauy_ds.model.values,['CIESM', 'CMCC-CM2-SR5', 'CMCC-ESM2', 'CAS-ESM2-0', 'FIO-ESM-2-0']))[0] tauy_ds['tauv'][modi,...] = -1*tauy_ds['tauv'][modi,...] tauy_djf_mean_anom, tauy_jja_mean_anom, tauy_mam_mean_anom, tauy_son_mean_anom, tauy_dec2nov_mean = seasonal_deviations_from_monthly_means(tauy_ds.tauv) #calculate change future relative to baseline taux_dec2nov_mean_d = taux_dec2nov_mean.sel(year=futyears).mean(dim='year') - taux_dec2nov_mean.sel(year=baseyears).mean(dim='year') tauy_dec2nov_mean_d = tauy_dec2nov_mean.sel(year=futyears).mean(dim='year') - tauy_dec2nov_mean.sel(year=baseyears).mean(dim='year') ####plotting my_cmap = cmocean.cm.balance #continuous colormap my_cmap.set_bad('grey') fig=plt.figure(figsize=(8,5)) gs = fig.add_gridspec(1,2) gs.update(hspace = 0.75,wspace=0.3,right=.84,top=.95,bottom=.05) #annual mean slc ax3 = plt.subplot(gs[0,0], projection=ccrs.Orthographic(0, 50)) #maps p=(100*a).sel(year=futyears).mean(dim='year').mean(dim='model').plot(transform=ccrs.PlateCarree(),ax=ax3,vmin=-25,vmax=25,cmap=my_cmap,add_colorbar=False) p.set_edgecolor('face') #avoid white lines in pdf rendering bathy.Band1.plot.contour(transform=ccrs.PlateCarree(),ax=ax3,levels=[-200],colors=['white'],add_colorbar=False) #shelf break ax3.coastlines(resolution='50m',color='black',linewidth=1) gl = ax3.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,linewidth=1, color='lightgrey', alpha=0, linestyle='-') gl.top_labels = gl.right_labels = False #don't label top and right axes gl.xlabel_style = {'color': 'black','rotation':0} gl.ylabel_style = {'color': 'black','rotation':0} ax3.set_extent([-9.5,9,45,60]) #set longitude & latitude extent ax3.set_title('(a)') #subplot title cax = fig.add_axes([0.125, .15, .312, .02]) fig.colorbar(p, cax=cax,orientation='horizontal',label='SLC [cm]') #annual mean wind-stress change my_cmap = cmocean.cm.tempo my_cmap.set_bad('grey') abs_d = np.sqrt(taux_dec2nov_mean_d.mean(dim='model')**2+tauy_dec2nov_mean_d.mean(dim='model')**2) #absolute change ax1 = plt.subplot(gs[0,1], projection=ccrs.Orthographic(0, 50)) #maps im = abs_d.plot(transform=ccrs.PlateCarree(),ax=ax1,vmin=0,vmax=.03,cmap=my_cmap,add_colorbar=False) bathy.Band1.plot.contour(transform=ccrs.PlateCarree(),ax=ax1,levels=[-200],colors=['white'],add_colorbar=False) im.set_edgecolor('face') #avoid whitespace between grid cells when rendering x=taux_djf_mean_anom.lon.values #quivers y=taux_djf_mean_anom.lat.values u = taux_dec2nov_mean_d.mean(dim='model').values v = tauy_dec2nov_mean_d.mean(dim='model').values q=ax1.quiver(x,y,u,v,transform=ccrs.PlateCarree(),scale=.2,color='black',width=.007,edgecolors='k',zorder=5) qk = ax1.quiverkey(q, 0.73, 0.239, 0.02, label='0.02 N/m'r'$^{2}$', labelpos='E', coordinates='figure') #quiver key on scale ax1.coastlines(resolution='50m',color='black') ax1.set_extent([-9.5,9,45,60]) ax1.set_title('(b)') gl = ax1.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,linewidth=1, color='lightgrey', alpha=0, linestyle='-') gl.top_labels = gl.right_labels = gl.left_labels = False #don't label top and right axes gl.xlabel_style = {'color': 'black','rotation':0} gl.ylabel_style = {'color': 'black','rotation':0} cax = fig.add_axes([0.529, .15, .312, .02]) fig.colorbar(im, cax=cax,orientation='horizontal',label='Wind-stress change [N/m'r'$^{2}$'']') #fig.savefig(os.path.join(out_dir,'suppFigure1_annualmean_change_ssp585.pdf'),dpi=300)
0
0
0
58ba3579f30090af3cb25a5fd67c18fa1d8dbd8b
613
py
Python
tests/conanbuilder/test_signature.py
arnaudgelas/mumoco
f38db5bdccc93473e2b8bfeb8e7f2884063fd9de
[ "MIT" ]
null
null
null
tests/conanbuilder/test_signature.py
arnaudgelas/mumoco
f38db5bdccc93473e2b8bfeb8e7f2884063fd9de
[ "MIT" ]
null
null
null
tests/conanbuilder/test_signature.py
arnaudgelas/mumoco
f38db5bdccc93473e2b8bfeb8e7f2884063fd9de
[ "MIT" ]
null
null
null
import pytest from src.conanbuilder.signature import Signature @pytest.fixture
17.514286
48
0.725938
import pytest from src.conanbuilder.signature import Signature @pytest.fixture def signature(): return Signature() def test_version(signature): assert not signature.version def test_version_set(signature): signature.version = "1.0.0" assert signature.version == "1.0.0" def test_channel(signature): assert not signature.channel def test_channel_set(signature): signature.channel = "dev" assert signature.channel == "dev" def test_user(signature): assert not signature.user def test_user_set(signature): signature.user = "user" assert signature.user == "user"
366
0
160
0e1d8979796434fec6803abf366ff204854a1441
2,148
py
Python
models/embedder.py
hanq0212/Few_Shot-Neural_Talking_Head
a5d2b4e745531e39d4d4c31a94557c0bd5e6072e
[ "MIT" ]
null
null
null
models/embedder.py
hanq0212/Few_Shot-Neural_Talking_Head
a5d2b4e745531e39d4d4c31a94557c0bd5e6072e
[ "MIT" ]
null
null
null
models/embedder.py
hanq0212/Few_Shot-Neural_Talking_Head
a5d2b4e745531e39d4d4c31a94557c0bd5e6072e
[ "MIT" ]
null
null
null
import torch import torch.nn from models.blocks import *
45.702128
88
0.474395
import torch import torch.nn from models.blocks import * class Embedder(nn.Module): def __init__(self,curr_size=224, ideal_size=256, pool_mode = "sum"): super(Embedder, self).__init__() self.init_padding= Padding(curr_size=curr_size, ideal=ideal_size) # downsample # input: B, 6, 256, 256 if pool_mode != "sum": self.emb = nn.Sequential( Residual_Downsample(6, 64), #output: B, 64, 128, 128 Residual_Downsample(64, 128), #output: B, 128, 64, 64 Residual_Downsample(128, 256), #output: B, 256, 32, 32 Self_Attention(256), #output: B, 256, 32, 32 Residual_Downsample(256, 512), #output: B, 512, 16, 16 Residual_Downsample(512, 512), #output: B, 512, 8, 8 Residual_Downsample(512, 512), #output: B, 512, 4, 4 nn.AdaptiveMaxPool2d((1,1)), nn.ReLU() ) else: self.emb = nn.Sequential( Residual_Downsample(6, 64), #output: B, 64, 128, 128 Residual_Downsample(64, 128), #output: B, 128, 64, 64 Residual_Downsample(128, 256), #output: B, 256, 32, 32 Self_Attention(256), #output: B, 256, 32, 32 Residual_Downsample(256, 512), #output: B, 512, 16, 16 Residual_Downsample(512, 512), #output: B, 512, 8, 8 Residual_Downsample(512, 512), #output: B, 512, 4, 4 nn.LPPool2d(norm_type=1, kernel_size = 4), nn.ReLU() ) def forward(self, img, landmark): new_input = torch.cat((img, landmark), dim = 1) new_input = self.init_padding(new_input) # print(new_input.size()) out = self.emb(new_input) out = out.view(out.size(0), 512, 1) return out
1,996
5
77
2e0ef5edb1fb4a280d5ae05b33226aeb2148eed9
4,059
py
Python
tests/test_parser.py
hirnimeshrampuresoftware/python-tcod
c82d60eaaf12e50b405d55df1026c1d00dd283b6
[ "BSD-2-Clause" ]
231
2018-06-28T10:07:41.000Z
2022-03-20T16:17:19.000Z
tests/test_parser.py
hanok2/python-tcod
807fdca464389e3febd8c86991bd4564d091f48d
[ "BSD-2-Clause" ]
66
2018-06-27T19:04:25.000Z
2022-03-30T21:15:15.000Z
tests/test_parser.py
hanok2/python-tcod
807fdca464389e3febd8c86991bd4564d091f48d
[ "BSD-2-Clause" ]
31
2018-09-12T00:35:42.000Z
2022-03-20T16:17:22.000Z
#!/usr/bin/env python import os from typing import Any import pytest import tcod as libtcod @pytest.mark.filterwarnings("ignore") if __name__ == "__main__": test_parser()
50.7375
114
0.698694
#!/usr/bin/env python import os from typing import Any import pytest import tcod as libtcod @pytest.mark.filterwarnings("ignore") def test_parser() -> None: print("***** File Parser test *****") parser = libtcod.parser_new() struct = libtcod.parser_new_struct(parser, "myStruct") libtcod.struct_add_property(struct, "bool_field", libtcod.TYPE_BOOL, True) libtcod.struct_add_property(struct, "char_field", libtcod.TYPE_CHAR, True) libtcod.struct_add_property(struct, "int_field", libtcod.TYPE_INT, True) libtcod.struct_add_property(struct, "float_field", libtcod.TYPE_FLOAT, True) libtcod.struct_add_property(struct, "color_field", libtcod.TYPE_COLOR, True) libtcod.struct_add_property(struct, "dice_field", libtcod.TYPE_DICE, True) libtcod.struct_add_property(struct, "string_field", libtcod.TYPE_STRING, True) libtcod.struct_add_list_property(struct, "bool_list", libtcod.TYPE_BOOL, True) libtcod.struct_add_list_property(struct, "char_list", libtcod.TYPE_CHAR, True) libtcod.struct_add_list_property(struct, "integer_list", libtcod.TYPE_INT, True) libtcod.struct_add_list_property(struct, "float_list", libtcod.TYPE_FLOAT, True) libtcod.struct_add_list_property(struct, "string_list", libtcod.TYPE_STRING, True) libtcod.struct_add_list_property(struct, "color_list", libtcod.TYPE_COLOR, True) # default listener print("***** Default listener *****") libtcod.parser_run(parser, os.path.join("libtcod", "data", "cfg", "sample.cfg")) print("bool_field : ", libtcod.parser_get_bool_property(parser, "myStruct.bool_field")) print("char_field : ", libtcod.parser_get_char_property(parser, "myStruct.char_field")) print("int_field : ", libtcod.parser_get_int_property(parser, "myStruct.int_field")) print("float_field : ", libtcod.parser_get_float_property(parser, "myStruct.float_field")) print("color_field : ", libtcod.parser_get_color_property(parser, "myStruct.color_field")) print("dice_field : ", libtcod.parser_get_dice_property(parser, "myStruct.dice_field")) print("string_field : ", libtcod.parser_get_string_property(parser, "myStruct.string_field")) print("bool_list : ", libtcod.parser_get_list_property(parser, "myStruct.bool_list", libtcod.TYPE_BOOL)) print("char_list : ", libtcod.parser_get_list_property(parser, "myStruct.char_list", libtcod.TYPE_CHAR)) print("integer_list : ", libtcod.parser_get_list_property(parser, "myStruct.integer_list", libtcod.TYPE_INT)) print("float_list : ", libtcod.parser_get_list_property(parser, "myStruct.float_list", libtcod.TYPE_FLOAT)) print("string_list : ", libtcod.parser_get_list_property(parser, "myStruct.string_list", libtcod.TYPE_STRING)) print("color_list : ", libtcod.parser_get_list_property(parser, "myStruct.color_list", libtcod.TYPE_COLOR)) # custom listener print("***** Custom listener *****") class MyListener: def new_struct(self, struct: Any, name: str) -> bool: print("new structure type", libtcod.struct_get_name(struct), " named ", name) return True def new_flag(self, name: str) -> bool: print("new flag named ", name) return True def new_property(self, name: str, typ: int, value: Any) -> bool: type_names = ["NONE", "BOOL", "CHAR", "INT", "FLOAT", "STRING", "COLOR", "DICE"] type_name = type_names[typ & 0xFF] if typ & libtcod.TYPE_LIST: type_name = "LIST<%s>" % type_name print("new property named ", name, " type ", type_name, " value ", value) return True def end_struct(self, struct: Any, name: str) -> bool: print("end structure type", libtcod.struct_get_name(struct), " named ", name) return True def error(self, msg: str) -> bool: print("error : ", msg) return True libtcod.parser_run(parser, os.path.join("libtcod", "data", "cfg", "sample.cfg"), MyListener()) if __name__ == "__main__": test_parser()
3,855
0
22
f13c36c38565a5f00a1c93b2baf699d1fcfd7720
7,009
py
Python
utils.py
UKPLab/EACL21-personalized-conversational-system
ff4949f11928b82f5bea06fa62b091cc337f56cc
[ "MIT" ]
9
2021-01-27T22:10:45.000Z
2021-11-09T23:47:46.000Z
utils.py
UKPLab/EACL21-personalized-conversational-system
ff4949f11928b82f5bea06fa62b091cc337f56cc
[ "MIT" ]
3
2021-03-11T06:04:15.000Z
2021-08-31T15:44:42.000Z
utils.py
UKPLab/EACL21-personalized-conversational-system
ff4949f11928b82f5bea06fa62b091cc337f56cc
[ "MIT" ]
1
2021-05-10T07:35:01.000Z
2021-05-10T07:35:01.000Z
# Copyright (c) 2019-present, HuggingFace Inc. # All rights reserved. This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import json import logging import os import tarfile import tempfile import torch from pytorch_pretrained_bert import cached_path from collections import defaultdict PERSONACHAT_URL = "https://s3.amazonaws.com/datasets.huggingface.co/personachat/personachat_self_original.json" HF_FINETUNED_MODEL = "https://s3.amazonaws.com/models.huggingface.co/transfer-learning-chatbot/finetuned_chatbot_gpt.tar.gz" logger = logging.getLogger(__file__) SPECIAL_TOKENS = ["<bos>", "<eos>", "<speaker1>", "<speaker2>", "<pad>"] QN_WORDS = ['who', 'what', 'where', 'why', 'when', 'how', 'which', 'whom', 'whose', '?'] lm_special_tokens = ['_start_', '_delimiter_', '_classify_'] def download_pretrained_model(): """ Download and extract finetuned model from S3 """ resolved_archive_file = cached_path(HF_FINETUNED_MODEL,cache_dir='./cache/') tempdir = tempfile.mkdtemp() logger.info("extracting archive file {} to temp dir {}".format(resolved_archive_file, tempdir)) with tarfile.open(resolved_archive_file, 'r:gz') as archive: archive.extractall(tempdir) return tempdir def get_dataset(tokenizer, dataset_path, dataset_cache=None): """ Get PERSONACHAT from S3 """ dataset_path = dataset_path or PERSONACHAT_URL dataset_cache = dataset_cache + '_' + type(tokenizer).__name__ # Do avoid using GPT cache for GPT-2 and vice-versa if dataset_cache and os.path.isfile(dataset_cache): logger.info("Load tokenized dataset from cache at %s", dataset_cache) dataset = torch.load(dataset_cache) else: logger.info("Download dataset from %s", dataset_path) personachat_file = cached_path(dataset_path,cache_dir='./cache/') # personachat_file = cached_path(dataset_path, cache_dir='../../.pytorch_pretrained_bert') with open(personachat_file, "r", encoding="utf-8") as f: dataset = json.loads(f.read()) logger.info("Tokenize and encode the dataset") dataset = tokenize(dataset) if dataset_cache: torch.save(dataset, dataset_cache) # FIXME: only for testing, delete later: ''' dataset['train'] = dataset['train'][:1] while len(dataset['train'][0]['utterances']) != 1: dataset['train'][0]['utterances'].pop() # dataset['valid'] = dataset['valid'][:1] dataset['valid'] = dataset['train'] ''' dataset['train'] = dataset['train'][:int(len(dataset['train'])*0.9)] # dataset['train'] = dataset['train'][:int(len(dataset['train']) * 0.1)] # train_len = int(len(dataset['train']) * 0.9) # dataset['train'] = dataset['train'][int(len(dataset['train']) * 0.9):] # dataset['train'] = dataset['train'][: 1] dataset['valid'] = dataset['valid'][: 1] # 这里不要乱改啊!!! # dataset['train'] = dataset['train'][:int(len(dataset['train'])*0.9)] # dataset['dev'] = dataset['train'][int(len(dataset['train']) * 0.9):] personachat_file = cached_path(dataset_path,cache_dir='./cache/') # personachat_file = cached_path(dataset_path, cache_dir='../../.pytorch_pretrained_bert') with open(personachat_file, "r", encoding="utf-8") as f: org_dataset = json.loads(f.read()) # org_dataset_tmp = org_dataset['train'][train_len:] # personas = defaultdict(list) for dataset_name in org_dataset: for i, dialogue in enumerate(org_dataset[dataset_name]): if i >= len(dataset[dataset_name]): break dataset[dataset_name][i]['persona_org'] = dialogue['personality'].copy() ''' for _ in range(len(dialogue['utterances'])): personas[dataset_name].append(dialogue['personality']) ''' return dataset def get_dataset_personalities(tokenizer, dataset_path, dataset_cache=None): """ Get personalities from PERSONACHAT """ dataset_path = dataset_path or PERSONACHAT_URL dataset_cache = dataset_cache + '_' + type(tokenizer).__name__ # Do avoid using GPT cache for GPT-2 and vice-versa if os.path.isfile(dataset_cache): logger.info("Load tokenized dataset from cache at %s", dataset_cache) personachat = torch.load(dataset_cache) else: logger.info("Download PERSONACHAT dataset from %s", dataset_path) personachat_file = cached_path(dataset_path,cache_dir='./cache/') with open(personachat_file, "r", encoding="utf-8") as f: personachat = json.loads(f.read()) print(personachat) logger.info("Tokenize and encode the dataset") personachat = tokenize(personachat) torch.save(personachat, dataset_cache) logger.info("Filter personalities") personalities = [] for dataset in personachat.values(): for dialog in dataset: personalities.append(dialog["personality"]) logger.info("Gathered {} personalities".format(len(personalities))) return personalities def build_input_from_segments(persona, history, reply, tokenizer, lm_labels=False, with_eos=True): """ Build a sequence of input from 3 segments: persona, history and last reply """ bos, eos, speaker1, speaker2 = tokenizer.convert_tokens_to_ids(SPECIAL_TOKENS[:-1]) # YW: speaker1 is user instance = {} sequence = [[bos] + list(chain(*persona))] + history + [reply + ([eos] if with_eos else [])] sequence = [sequence[0]] + [[speaker2 if (len(sequence)-i) % 2 else speaker1] + s for i, s in enumerate(sequence[1:])] # YW: add speaker infomation instance["input_ids"] = list(chain(*sequence)) # YW: concat all the context instance["token_type_ids"] = [speaker2 if i % 2 else speaker1 for i, s in enumerate(sequence) for _ in s] # YW: TODO: persona is speaker1? instance["mc_token_ids"] = len(instance["input_ids"]) - 1 instance["lm_labels"] = [-1] * len(instance["input_ids"]) # YW: all -1 (mask?) -> because it's not the right candidate(label)! if lm_labels: # YW: if it's label instance["lm_labels"] = ([-1] * sum(len(s) for s in sequence[:-1])) + [-1] + sequence[-1][1:] return instance, sequence
46.726667
153
0.659153
# Copyright (c) 2019-present, HuggingFace Inc. # All rights reserved. This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import json import logging import os import tarfile import tempfile import torch from pytorch_pretrained_bert import cached_path from collections import defaultdict PERSONACHAT_URL = "https://s3.amazonaws.com/datasets.huggingface.co/personachat/personachat_self_original.json" HF_FINETUNED_MODEL = "https://s3.amazonaws.com/models.huggingface.co/transfer-learning-chatbot/finetuned_chatbot_gpt.tar.gz" logger = logging.getLogger(__file__) SPECIAL_TOKENS = ["<bos>", "<eos>", "<speaker1>", "<speaker2>", "<pad>"] QN_WORDS = ['who', 'what', 'where', 'why', 'when', 'how', 'which', 'whom', 'whose', '?'] lm_special_tokens = ['_start_', '_delimiter_', '_classify_'] def download_pretrained_model(): """ Download and extract finetuned model from S3 """ resolved_archive_file = cached_path(HF_FINETUNED_MODEL,cache_dir='./cache/') tempdir = tempfile.mkdtemp() logger.info("extracting archive file {} to temp dir {}".format(resolved_archive_file, tempdir)) with tarfile.open(resolved_archive_file, 'r:gz') as archive: archive.extractall(tempdir) return tempdir def get_dataset(tokenizer, dataset_path, dataset_cache=None): """ Get PERSONACHAT from S3 """ dataset_path = dataset_path or PERSONACHAT_URL dataset_cache = dataset_cache + '_' + type(tokenizer).__name__ # Do avoid using GPT cache for GPT-2 and vice-versa if dataset_cache and os.path.isfile(dataset_cache): logger.info("Load tokenized dataset from cache at %s", dataset_cache) dataset = torch.load(dataset_cache) else: logger.info("Download dataset from %s", dataset_path) personachat_file = cached_path(dataset_path,cache_dir='./cache/') # personachat_file = cached_path(dataset_path, cache_dir='../../.pytorch_pretrained_bert') with open(personachat_file, "r", encoding="utf-8") as f: dataset = json.loads(f.read()) logger.info("Tokenize and encode the dataset") def tokenize(obj): if isinstance(obj, str): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(obj)) if isinstance(obj, dict): return dict((n, tokenize(o)) for n, o in obj.items()) return list(tokenize(o) for o in obj) dataset = tokenize(dataset) if dataset_cache: torch.save(dataset, dataset_cache) # FIXME: only for testing, delete later: ''' dataset['train'] = dataset['train'][:1] while len(dataset['train'][0]['utterances']) != 1: dataset['train'][0]['utterances'].pop() # dataset['valid'] = dataset['valid'][:1] dataset['valid'] = dataset['train'] ''' dataset['train'] = dataset['train'][:int(len(dataset['train'])*0.9)] # dataset['train'] = dataset['train'][:int(len(dataset['train']) * 0.1)] # train_len = int(len(dataset['train']) * 0.9) # dataset['train'] = dataset['train'][int(len(dataset['train']) * 0.9):] # dataset['train'] = dataset['train'][: 1] dataset['valid'] = dataset['valid'][: 1] # 这里不要乱改啊!!! # dataset['train'] = dataset['train'][:int(len(dataset['train'])*0.9)] # dataset['dev'] = dataset['train'][int(len(dataset['train']) * 0.9):] personachat_file = cached_path(dataset_path,cache_dir='./cache/') # personachat_file = cached_path(dataset_path, cache_dir='../../.pytorch_pretrained_bert') with open(personachat_file, "r", encoding="utf-8") as f: org_dataset = json.loads(f.read()) # org_dataset_tmp = org_dataset['train'][train_len:] # personas = defaultdict(list) for dataset_name in org_dataset: for i, dialogue in enumerate(org_dataset[dataset_name]): if i >= len(dataset[dataset_name]): break dataset[dataset_name][i]['persona_org'] = dialogue['personality'].copy() ''' for _ in range(len(dialogue['utterances'])): personas[dataset_name].append(dialogue['personality']) ''' return dataset def get_dataset_personalities(tokenizer, dataset_path, dataset_cache=None): """ Get personalities from PERSONACHAT """ dataset_path = dataset_path or PERSONACHAT_URL dataset_cache = dataset_cache + '_' + type(tokenizer).__name__ # Do avoid using GPT cache for GPT-2 and vice-versa if os.path.isfile(dataset_cache): logger.info("Load tokenized dataset from cache at %s", dataset_cache) personachat = torch.load(dataset_cache) else: logger.info("Download PERSONACHAT dataset from %s", dataset_path) personachat_file = cached_path(dataset_path,cache_dir='./cache/') with open(personachat_file, "r", encoding="utf-8") as f: personachat = json.loads(f.read()) print(personachat) logger.info("Tokenize and encode the dataset") def tokenize(obj): if isinstance(obj, str): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(obj)) if isinstance(obj, dict): return dict((n, tokenize(o)) for n, o in obj.items()) return list(tokenize(o) for o in obj) personachat = tokenize(personachat) torch.save(personachat, dataset_cache) logger.info("Filter personalities") personalities = [] for dataset in personachat.values(): for dialog in dataset: personalities.append(dialog["personality"]) logger.info("Gathered {} personalities".format(len(personalities))) return personalities class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self def build_input_from_segments(persona, history, reply, tokenizer, lm_labels=False, with_eos=True): """ Build a sequence of input from 3 segments: persona, history and last reply """ bos, eos, speaker1, speaker2 = tokenizer.convert_tokens_to_ids(SPECIAL_TOKENS[:-1]) # YW: speaker1 is user instance = {} sequence = [[bos] + list(chain(*persona))] + history + [reply + ([eos] if with_eos else [])] sequence = [sequence[0]] + [[speaker2 if (len(sequence)-i) % 2 else speaker1] + s for i, s in enumerate(sequence[1:])] # YW: add speaker infomation instance["input_ids"] = list(chain(*sequence)) # YW: concat all the context instance["token_type_ids"] = [speaker2 if i % 2 else speaker1 for i, s in enumerate(sequence) for _ in s] # YW: TODO: persona is speaker1? instance["mc_token_ids"] = len(instance["input_ids"]) - 1 instance["lm_labels"] = [-1] * len(instance["input_ids"]) # YW: all -1 (mask?) -> because it's not the right candidate(label)! if lm_labels: # YW: if it's label instance["lm_labels"] = ([-1] * sum(len(s) for s in sequence[:-1])) + [-1] + sequence[-1][1:] return instance, sequence
644
0
109
6b90888722e66e986dd59cf3304d14be7e22c8b2
4,255
py
Python
lib/roi_data/minibatch.py
GothicAi/AugMask
1547de027ddac29cc92ec6f98c837f32301fcd67
[ "MIT" ]
null
null
null
lib/roi_data/minibatch.py
GothicAi/AugMask
1547de027ddac29cc92ec6f98c837f32301fcd67
[ "MIT" ]
null
null
null
lib/roi_data/minibatch.py
GothicAi/AugMask
1547de027ddac29cc92ec6f98c837f32301fcd67
[ "MIT" ]
1
2020-03-31T22:37:29.000Z
2020-03-31T22:37:29.000Z
import numpy as np import cv2 from core.config import cfg import utils.blob as blob_utils import roi_data.rpn def get_minibatch_blob_names(is_training=True): """Return blob names in the order in which they are read by the data loader. """ # data blob: holds a batch of N images, each with 3 channels blob_names = ['data'] if cfg.RPN.RPN_ON: # RPN-only or end-to-end Faster R-CNN blob_names += roi_data.rpn.get_rpn_blob_names(is_training=is_training) elif cfg.RETINANET.RETINANET_ON: raise NotImplementedError else: # Fast R-CNN like models trained on precomputed proposals blob_names += roi_data.fast_rcnn.get_fast_rcnn_blob_names( is_training=is_training ) return blob_names def get_minibatch(roidb, coco): """Given a roidb, construct a minibatch sampled from it.""" # We collect blobs from each image onto a list and then concat them into a # single tensor, hence we initialize each blob to an empty list blobs = {k: [] for k in get_minibatch_blob_names()} # Get the input image blob im_blob, im_scales, roidb = _get_image_blob(roidb, coco) blobs['data'] = im_blob if cfg.RPN.RPN_ON: # RPN-only or end-to-end Faster/Mask R-CNN valid = roi_data.rpn.add_rpn_blobs(blobs, im_scales, roidb) elif cfg.RETINANET.RETINANET_ON: raise NotImplementedError else: # Fast R-CNN like models trained on precomputed proposals valid = roi_data.fast_rcnn.add_fast_rcnn_blobs(blobs, im_scales, roidb) return blobs, valid def _get_image_blob(roidb, coco): """Builds an input blob from the images in the roidb at the specified scales. """ num_images = len(roidb) # Sample random scales to use for each image in this batch scale_inds = np.random.randint( 0, high=len(cfg.TRAIN.SCALES), size=num_images) processed_ims = [] im_scales = [] for i in range(num_images): im = cv2.imread(roidb[i]['image']) assert im is not None, \ 'Failed to read image \'{}\''.format(roidb[i]['image']) # AUG BEGIN-------------------------------- backupim = im backuproidb = roidb[i] try: from AugSeg.get_instance_group import extract from AugSeg.affine_transform import transform_image, transform_annotation img_id = roidb[i]['id'] ann_ids = coco.getAnnIds(imgIds=img_id) anns = coco.loadAnns(ann_ids) background, instances_list, transforms_list, groupbnds_list, groupidx_list = extract(anns, im) new_img = transform_image(background, instances_list, transforms_list) new_ann = transform_annotation(anns, transforms_list, groupbnds_list, groupidx_list, background.shape[1], background.shape[0]) im = new_img from datasetsAug.roidb import combined_roidb_for_training new_roidb, ratio_list, ratio_index = combined_roidb_for_training( \ ('coco_2017_train',), cfg.TRAIN.PROPOSAL_FILES, \ img_id, new_ann, coco ) if roidb[i]['flipped']: roidb[i] = new_roidb[1] else: roidb[i] = new_roidb[0] except: roidb[i] = backuproidb im = backupim # AUG END---------------------------------- # If NOT using opencv to read in images, uncomment following lines # if len(im.shape) == 2: # im = im[:, :, np.newaxis] # im = np.concatenate((im, im, im), axis=2) # # flip the channel, since the original one using cv2 # # rgb -> bgr # im = im[:, :, ::-1] if roidb[i]['flipped']: im = im[:, ::-1, :] target_size = cfg.TRAIN.SCALES[scale_inds[i]] im, im_scale = blob_utils.prep_im_for_blob( im, cfg.PIXEL_MEANS, [target_size], cfg.TRAIN.MAX_SIZE) im_scales.append(im_scale[0]) processed_ims.append(im[0]) # Create a blob to hold the input images [n, c, h, w] blob = blob_utils.im_list_to_blob(processed_ims) return blob, im_scales, roidb
38.681818
106
0.610811
import numpy as np import cv2 from core.config import cfg import utils.blob as blob_utils import roi_data.rpn def get_minibatch_blob_names(is_training=True): """Return blob names in the order in which they are read by the data loader. """ # data blob: holds a batch of N images, each with 3 channels blob_names = ['data'] if cfg.RPN.RPN_ON: # RPN-only or end-to-end Faster R-CNN blob_names += roi_data.rpn.get_rpn_blob_names(is_training=is_training) elif cfg.RETINANET.RETINANET_ON: raise NotImplementedError else: # Fast R-CNN like models trained on precomputed proposals blob_names += roi_data.fast_rcnn.get_fast_rcnn_blob_names( is_training=is_training ) return blob_names def get_minibatch(roidb, coco): """Given a roidb, construct a minibatch sampled from it.""" # We collect blobs from each image onto a list and then concat them into a # single tensor, hence we initialize each blob to an empty list blobs = {k: [] for k in get_minibatch_blob_names()} # Get the input image blob im_blob, im_scales, roidb = _get_image_blob(roidb, coco) blobs['data'] = im_blob if cfg.RPN.RPN_ON: # RPN-only or end-to-end Faster/Mask R-CNN valid = roi_data.rpn.add_rpn_blobs(blobs, im_scales, roidb) elif cfg.RETINANET.RETINANET_ON: raise NotImplementedError else: # Fast R-CNN like models trained on precomputed proposals valid = roi_data.fast_rcnn.add_fast_rcnn_blobs(blobs, im_scales, roidb) return blobs, valid def _get_image_blob(roidb, coco): """Builds an input blob from the images in the roidb at the specified scales. """ num_images = len(roidb) # Sample random scales to use for each image in this batch scale_inds = np.random.randint( 0, high=len(cfg.TRAIN.SCALES), size=num_images) processed_ims = [] im_scales = [] for i in range(num_images): im = cv2.imread(roidb[i]['image']) assert im is not None, \ 'Failed to read image \'{}\''.format(roidb[i]['image']) # AUG BEGIN-------------------------------- backupim = im backuproidb = roidb[i] try: from AugSeg.get_instance_group import extract from AugSeg.affine_transform import transform_image, transform_annotation img_id = roidb[i]['id'] ann_ids = coco.getAnnIds(imgIds=img_id) anns = coco.loadAnns(ann_ids) background, instances_list, transforms_list, groupbnds_list, groupidx_list = extract(anns, im) new_img = transform_image(background, instances_list, transforms_list) new_ann = transform_annotation(anns, transforms_list, groupbnds_list, groupidx_list, background.shape[1], background.shape[0]) im = new_img from datasetsAug.roidb import combined_roidb_for_training new_roidb, ratio_list, ratio_index = combined_roidb_for_training( \ ('coco_2017_train',), cfg.TRAIN.PROPOSAL_FILES, \ img_id, new_ann, coco ) if roidb[i]['flipped']: roidb[i] = new_roidb[1] else: roidb[i] = new_roidb[0] except: roidb[i] = backuproidb im = backupim # AUG END---------------------------------- # If NOT using opencv to read in images, uncomment following lines # if len(im.shape) == 2: # im = im[:, :, np.newaxis] # im = np.concatenate((im, im, im), axis=2) # # flip the channel, since the original one using cv2 # # rgb -> bgr # im = im[:, :, ::-1] if roidb[i]['flipped']: im = im[:, ::-1, :] target_size = cfg.TRAIN.SCALES[scale_inds[i]] im, im_scale = blob_utils.prep_im_for_blob( im, cfg.PIXEL_MEANS, [target_size], cfg.TRAIN.MAX_SIZE) im_scales.append(im_scale[0]) processed_ims.append(im[0]) # Create a blob to hold the input images [n, c, h, w] blob = blob_utils.im_list_to_blob(processed_ims) return blob, im_scales, roidb
0
0
0
e2103516eeb997f257f194053521245582f812a4
2,141
py
Python
extract.py
josh-austin/color-extractor
d43f350a2340005da9d086aa1e797588c1125270
[ "MIT" ]
2
2015-01-11T00:00:25.000Z
2020-06-30T19:39:51.000Z
extract.py
josh-austin/color-extractor
d43f350a2340005da9d086aa1e797588c1125270
[ "MIT" ]
null
null
null
extract.py
josh-austin/color-extractor
d43f350a2340005da9d086aa1e797588c1125270
[ "MIT" ]
null
null
null
import sys, os class Extractor: ''' Returns the variable name if a variable with the value <value> is found. ''' ''' Scans a list of <lines> containing CSS and returns a list of strings containing the rendered LESS version. ''' ''' Returns the output for the variables.less file as a list of strings ''' if __name__ == '__main__': if len(sys.argv) > 1: for path in sys.argv[1:]: name = '.'.join(path.split('.')[:-1]) extractor = Extractor(name) read = open(path) write = open(name + '.less', 'w') variables = open(name + '_variables.less', 'w') try: for line in extractor.scan(read.readlines()): write.write(line) for line in extractor.get_variables(): variables.write(line + os.linesep) finally: variables.close() write.close() read.close() else: print('usage: python extract.py [file]')
31.955224
83
0.502102
import sys, os class Extractor: def __init__(self, prefix=''): self.variables = {} self.prefix = os.path.basename(prefix) ''' Returns the variable name if a variable with the value <value> is found. ''' def find_variable_name(self, value): for var, val in self.variables.items(): if value == val: return var ''' Scans a list of <lines> containing CSS and returns a list of strings containing the rendered LESS version. ''' def scan(self, lines): yield "@import '%s_variables.less'\n\n" %self.prefix for line in lines: found_prop = False for prop in ('background-color', 'background', 'color'): if prop in line: found_prop = True value = line.split(':')[1].strip().replace('}', '') if not (value in self.variables.values()): self.variables['@var%i' %(len(self.variables) + 1)] = value yield line.replace(value, self.find_variable_name(value) + ';') if not found_prop: yield line ''' Returns the output for the variables.less file as a list of strings ''' def get_variables(self): for var, val in self.variables.items(): yield var + ': ' + val if __name__ == '__main__': if len(sys.argv) > 1: for path in sys.argv[1:]: name = '.'.join(path.split('.')[:-1]) extractor = Extractor(name) read = open(path) write = open(name + '.less', 'w') variables = open(name + '_variables.less', 'w') try: for line in extractor.scan(read.readlines()): write.write(line) for line in extractor.get_variables(): variables.write(line + os.linesep) finally: variables.close() write.close() read.close() else: print('usage: python extract.py [file]')
910
0
105
da14e30138a8a6095f020cff0406d675dbf3d07c
12,557
py
Python
scripts/auv_models_test.py
michoy/system_identification
13e2b249e111e00e290461ab392f0e2ad562246d
[ "MIT" ]
null
null
null
scripts/auv_models_test.py
michoy/system_identification
13e2b249e111e00e290461ab392f0e2ad562246d
[ "MIT" ]
null
null
null
scripts/auv_models_test.py
michoy/system_identification
13e2b249e111e00e290461ab392f0e2ad562246d
[ "MIT" ]
null
null
null
import unittest import numpy as np from auv_models import linear_surge, diagonal_slow_without_g from helper import degrees_to_quat_rotation if __name__ == "__main__": unittest.main()
31.951654
74
0.525285
import unittest import numpy as np from auv_models import linear_surge, diagonal_slow_without_g from helper import degrees_to_quat_rotation class SimplifiedSurgeAUVTest(unittest.TestCase): def test_auv_1DOF(self): x = 0 u = 0.1 tau = 1 m = 10 d = 20 state = np.array([x, u]) thrust = np.array([tau]) parameters = np.array([m, d]) result = linear_surge(state, thrust, parameters) self.assertTrue(np.allclose(result, np.array([0.1, -0.1]))) class SlowDiagonalModelTests(unittest.TestCase): def test_dimensions_and_type(self): eta = [0, 0, 0, 1, 0, 0, 0] nu = [0, 0, 0, 0, 0, 0] M = [10, 10, 10, 10, 10, 10] D = [10, 10, 10, 10, 10, 10] W = [0] B = [0] COG = [0, 0, 0] COB = [0, 0, 0] state = np.array(eta + nu, dtype=np.float64) parameters = np.array(M + D + W + B + COG + COB, dtype=np.float64) thrust = np.array([0, 0, 0, 0, 0, 0], dtype=np.float64) x_dot = diagonal_slow_without_g(state, thrust, parameters) self.assertEqual(type(x_dot), np.ndarray) self.assertEqual(len(x_dot), 13) def test_zeros_result(self): eta = [0, 0, 0, 1, 0, 0, 0] nu = [0, 0, 0, 0, 0, 0] M = [10, 10, 10, 10, 10, 10] D = [10, 10, 10, 10, 10, 10] W = [0] B = [0] COG = [0, 0, 0] COB = [0, 0, 0] x_dot_expected = np.zeros(13) state = np.array(eta + nu, dtype=np.float64) parameters = np.array(M + D + W + B + COG + COB, dtype=np.float64) thrust = np.array([0, 0, 0, 0, 0, 0], dtype=np.float64) x_dot = diagonal_slow_without_g(state, thrust, parameters) for a, b in zip(x_dot, x_dot_expected): self.assertAlmostEqual(a, b) def test_restoring_sinking_linear(self): M = [10, 10, 10, 10, 10, 10] D = [10, 10, 10, 10, 10, 10] W = [10] B = [0] COG = [0, 0, 0] COB = [0, 0, 0] # input position = [0, 0, 0] roll, pitch, yaw = [0, 0, 0] nu = [0, 0, 0, 0, 0, 0] tau = [0, 0, 0, 0, 0, 0] # expected eta_dot = [0, 0, 0, 0, 0, 0, 0] linear_acc = [0, 0, 1] angular_acc = [0, 0, 0] x_dot_expected = np.array(eta_dot + linear_acc + angular_acc) orientation = degrees_to_quat_rotation(roll, pitch, yaw).tolist() eta = position + orientation state = np.array(eta + nu, dtype=np.float64) parameters = np.array(M + D + W + B + COG + COB, dtype=np.float64) thrust = np.array(tau, dtype=np.float64) x_dot = diagonal_slow_without_g(state, thrust, parameters) for a, b in zip(x_dot, x_dot_expected): self.assertAlmostEqual(a, b) def test_restoring_angular_y(self): M = [10, 10, 10, 10, 10, 10] D = [10, 10, 10, 10, 10, 10] W = [10] B = [10] COG = [0, 0, 0] COB = [0, 1, 0] # input position = [0, 0, 0] roll, pitch, yaw = [0, 0, 0] nu = [0, 0, 0, 0, 0, 0] tau = [0, 0, 0, 0, 0, 0] # expected eta_dot = [0, 0, 0, 0, 0, 0, 0] linear_acc = [0, 0, 0] angular_acc = [-1, 0, 0] x_dot_expected = np.array(eta_dot + linear_acc + angular_acc) orientation = degrees_to_quat_rotation(roll, pitch, yaw).tolist() eta = position + orientation state = np.array(eta + nu, dtype=np.float64) parameters = np.array(M + D + W + B + COG + COB, dtype=np.float64) thrust = np.array(tau, dtype=np.float64) x_dot = diagonal_slow_without_g(state, thrust, parameters) for a, b in zip(x_dot, x_dot_expected): self.assertAlmostEqual(a, b) def test_restoring_angular_x(self): M = [10, 10, 10, 10, 10, 10] D = [10, 10, 10, 10, 10, 10] W = [10] B = [10] COG = [0, 0, 0] COB = [1, 0, 0] # input position = [0, 0, 0] roll, pitch, yaw = [0, 0, 0] nu = [0, 0, 0, 0, 0, 0] tau = [0, 0, 0, 0, 0, 0] # expected eta_dot = [0, 0, 0, 0, 0, 0, 0] linear_acc = [0, 0, 0] angular_acc = [0, 1, 0] x_dot_expected = np.array(eta_dot + linear_acc + angular_acc) orientation = degrees_to_quat_rotation(roll, pitch, yaw).tolist() eta = position + orientation state = np.array(eta + nu, dtype=np.float64) parameters = np.array(M + D + W + B + COG + COB, dtype=np.float64) thrust = np.array(tau, dtype=np.float64) x_dot = diagonal_slow_without_g(state, thrust, parameters) for a, b in zip(x_dot, x_dot_expected): self.assertAlmostEqual(a, b) def test_restoring_x_rotated_roll(self): M = [10, 10, 10, 10, 10, 10] D = [10, 10, 10, 10, 10, 10] W = [10] B = [10] COG = [0, 0, 0] COB = [1, 0, 0] # input position = [0, 0, 0] roll, pitch, yaw = [90, 0, 0] nu = [0, 0, 0, 0, 0, 0] tau = [0, 0, 0, 0, 0, 0] # expected pos_dot_expected = [0, 0, 0] quat_dot_expected = [0, 0, 0, 0] linear_acc = [0, 0, 0] angular_acc = [0, 0, -1] eta_dot_expected = pos_dot_expected + quat_dot_expected nu_dot_expected = linear_acc + angular_acc x_dot_expected = np.array(eta_dot_expected + nu_dot_expected) orientation = degrees_to_quat_rotation(roll, pitch, yaw).tolist() eta = position + orientation state = np.array(eta + nu, dtype=np.float64) parameters = np.array(M + D + W + B + COG + COB, dtype=np.float64) thrust = np.array(tau, dtype=np.float64) x_dot = diagonal_slow_without_g(state, thrust, parameters) eta_dot = x_dot[0:7] nu_dot = x_dot[7:13] for a, b in zip(x_dot, x_dot_expected): self.assertAlmostEqual(a, b) def test_restoring_x_rotated_pitch(self): M = [10, 10, 10, 10, 10, 10] D = [10, 10, 10, 10, 10, 10] W = [0] B = [10] COG = [0, 0, 0] COB = [1, 0, 0] # input position = [0, 0, 0] roll, pitch, yaw = [0, 90, 0] nu = [0, 0, 0, 0, 0, 0] tau = [0, 0, 0, 0, 0, 0] # expected pos_dot_expected = [0, 0, 0] quat_dot_expected = [0, 0, 0, 0] linear_acc = [1, 0, 0] angular_acc = [0, 0, 0] eta_dot_expected = pos_dot_expected + quat_dot_expected nu_dot_expected = linear_acc + angular_acc x_dot_expected = np.array(eta_dot_expected + nu_dot_expected) orientation = degrees_to_quat_rotation(roll, pitch, yaw).tolist() eta = position + orientation state = np.array(eta + nu, dtype=np.float64) parameters = np.array(M + D + W + B + COG + COB, dtype=np.float64) thrust = np.array(tau, dtype=np.float64) x_dot = diagonal_slow_without_g(state, thrust, parameters) eta_dot = x_dot[0:7] nu_dot = x_dot[7:13] for a, b in zip(x_dot, x_dot_expected): self.assertAlmostEqual(a, b) def test_restoring_z_rotated_roll(self): M = [10, 10, 10, 10, 10, 10] D = [10, 10, 10, 10, 10, 10] W = [10] B = [10] COG = [0, 0, 0] COB = [0, 0, 1] # input position = [0, 0, 0] roll, pitch, yaw = [90, 0, 0] nu = [0, 0, 0, 0, 0, 0] tau = [0, 0, 0, 0, 0, 0] # expected pos_dot_expected = [0, 0, 0] quat_dot_expected = [0, 0, 0, 0] linear_acc = [0, 0, 0] angular_acc = [1, 0, 0] eta_dot_expected = pos_dot_expected + quat_dot_expected nu_dot_expected = linear_acc + angular_acc x_dot_expected = np.array(eta_dot_expected + nu_dot_expected) orientation = degrees_to_quat_rotation(roll, pitch, yaw).tolist() eta = position + orientation state = np.array(eta + nu, dtype=np.float64) parameters = np.array(M + D + W + B + COG + COB, dtype=np.float64) thrust = np.array(tau, dtype=np.float64) x_dot = diagonal_slow_without_g(state, thrust, parameters) eta_dot = x_dot[0:7] nu_dot = x_dot[7:13] for a, b in zip(x_dot, x_dot_expected): self.assertAlmostEqual(a, b) def test_tau_sway(self): M = [10, 10, 10, 10, 10, 10] D = [10, 10, 10, 10, 10, 10] W = [10] B = [10] COG = [0, 0, 0] COB = [0, 0, 0] # input position = [0, 0, 0] roll, pitch, yaw = [0, 0, 0] nu = [0, 0, 0, 0, 0, 0] tau = [0, 10, 0, 0, 0, 0] # expected pos_dot_expected = [0, 0, 0] quat_dot_expected = [0, 0, 0, 0] linear_acc = [0, 1, 0] angular_acc = [0, 0, 0] eta_dot_expected = pos_dot_expected + quat_dot_expected nu_dot_expected = linear_acc + angular_acc x_dot_expected = np.array(eta_dot_expected + nu_dot_expected) orientation = degrees_to_quat_rotation(roll, pitch, yaw).tolist() eta = position + orientation state = np.array(eta + nu, dtype=np.float64) parameters = np.array(M + D + W + B + COG + COB, dtype=np.float64) thrust = np.array(tau, dtype=np.float64) x_dot = diagonal_slow_without_g(state, thrust, parameters) eta_dot = x_dot[0:7] nu_dot = x_dot[7:13] for a, b in zip(x_dot, x_dot_expected): self.assertAlmostEqual(a, b) def test_tau_heave(self): M = [10, 10, 10, 10, 10, 10] D = [10, 10, 10, 10, 10, 10] W = [10] B = [10] COG = [0, 0, 0] COB = [0, 0, 0] # input position = [0, 0, 0] roll, pitch, yaw = [0, 0, 0] nu = [0, 0, 0, 0, 0, 0] tau = [0, 0, 10, 0, 0, 0] # expected pos_dot_expected = [0, 0, 0] quat_dot_expected = [0, 0, 0, 0] linear_acc = [0, 0, 1] angular_acc = [0, 0, 0] eta_dot_expected = pos_dot_expected + quat_dot_expected nu_dot_expected = linear_acc + angular_acc x_dot_expected = np.array(eta_dot_expected + nu_dot_expected) orientation = degrees_to_quat_rotation(roll, pitch, yaw).tolist() eta = position + orientation state = np.array(eta + nu, dtype=np.float64) parameters = np.array(M + D + W + B + COG + COB, dtype=np.float64) thrust = np.array(tau, dtype=np.float64) x_dot = diagonal_slow_without_g(state, thrust, parameters) eta_dot = x_dot[0:7] nu_dot = x_dot[7:13] for a, b in zip(x_dot, x_dot_expected): self.assertAlmostEqual(a, b) def test_restoring_rotated(self): M = [10, 10, 10, 10, 10, 10] D = [10, 10, 10, 10, 10, 10] W = [0] B = [10] COG = [0, 0, 0] COB = [1, 0, 0] # input position = [0, 0, 0] roll, pitch, yaw = [90, 0, 0] nu = [0, 0, 0, 0, 0, 0] tau = [0, 0, 0, 0, 0, 0] # expected eta_dot = [0, 0, 0, 0, 0, 0, 0] linear_acc = [0, -1, 0] angular_acc = [0, 0, -1] x_dot_expected = np.array(eta_dot + linear_acc + angular_acc) orientation = degrees_to_quat_rotation(roll, pitch, yaw).tolist() eta = position + orientation state = np.array(eta + nu, dtype=np.float64) parameters = np.array(M + D + W + B + COG + COB, dtype=np.float64) thrust = np.array(tau, dtype=np.float64) x_dot = diagonal_slow_without_g(state, thrust, parameters) for a, b in zip(x_dot, x_dot_expected): self.assertAlmostEqual(a, b) def test_non_invertible_M(self): M = [10, 10, 0, 10, 10, 10] D = [10, 10, 10, 10, 10, 10] W = [0] B = [10] COG = [0, 0, 0] COB = [1, 0, 0] # input position = [0, 0, 0] roll, pitch, yaw = [90, 0, 0] nu = [0, 0, 0, 0, 0, 0] tau = [0, 0, 0, 0, 0, 0] orientation = degrees_to_quat_rotation(roll, pitch, yaw).tolist() eta = position + orientation state = np.array(eta + nu, dtype=np.float64) parameters = np.array(M + D + W + B + COG + COB, dtype=np.float64) thrust = np.array(tau, dtype=np.float64) x_dot = diagonal_slow_without_g(state, thrust, parameters) self.assertTrue(np.isnan(x_dot).all()) if __name__ == "__main__": unittest.main()
11,915
54
395
83871a80758a183a877a1739b65f003ef563b450
5,998
py
Python
zdf_downloader.py
leaffan/downloading
c917c394f7519772b8c195e6e922ba40a372dce2
[ "MIT" ]
1
2017-02-01T15:37:31.000Z
2017-02-01T15:37:31.000Z
zdf_downloader.py
leaffan/downloading
c917c394f7519772b8c195e6e922ba40a372dce2
[ "MIT" ]
null
null
null
zdf_downloader.py
leaffan/downloading
c917c394f7519772b8c195e6e922ba40a372dce2
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import argparse import requests import json from dateutil.parser import parse from lxml import html if __name__ == '__main__': arg_parser = argparse.ArgumentParser( description='Download videos from ZDF media library.') arg_parser.add_argument( '-d', '--directory', dest='tgt_dir', metavar='target_directory', required=True, help='Target directory for video downloads.') arg_parser.add_argument( '-q', '--quality', dest='quality', metavar='video quality', required=False, choices=['veryhigh', 'high', 'low'], default='high', help='Quality of downloaded videos') arg_parser.add_argument( 'urls', metavar='video_urls', help='Comma-separated list of video urls.') args = arg_parser.parse_args() dl = ZdfDownloader(args.tgt_dir, args.urls, quality=args.quality) dl.download_all()
37.72327
79
0.603701
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import argparse import requests import json from dateutil.parser import parse from lxml import html class ZdfDownloader(): QUALITY_KEYS = ['veryhigh', 'high', 'low'] BROADCAST_BASE_URL = ( "https://api.zdf.de/tmd/2/ngplayer_2_3/vod/ptmd/mediathek/") TGT_MIME_TYPE = 'video/mp4' DOWNLOAD_CHUNK_SIZE = 524288 def __init__(self, tgt_dir, urls, quality='high'): # setting target directory self.tgt_dir = tgt_dir # setting urls for videos to be downloaded self.urls = [url.strip() for url in urls.split(",")] # setting video quality to be downloaded if quality.lower() in self.QUALITY_KEYS: self.quality = quality.lower() else: self.quality = 'high' def download_all(self): """ Downloads videos for all specified urls. """ for url in self.urls: self.retrieve_content_json_url(url) self.retrieve_broadcast_id() self.retrieve_video_url() file_name = self.build_file_name() self.retrieve_video(self.vid_url, file_name) def create_auth_headers(self): self.auth_headers = {'Api-Auth': " ".join( ("Bearer", self.auth_api_token))} def retrieve_content_json_url(self, url): """ Retrieves url to json page with video meta data. Additionally retrieves authorization token to be applied when accessing urls further on. """ req = requests.get(url) doc = html.fromstring(req.text) # authorization api token and url to json page are contained by a # json structure inside a div tag attribute value raw_broadcast_info = doc.xpath( "//article[@class='b-video-module']/descendant::div" + "[@class='b-playerbox b-ratiobox js-rb-live']/@data-zdfplayer-jsb") raw_broadcast_info = raw_broadcast_info.pop(0).strip() raw_broadcast_info = json.loads(raw_broadcast_info) # retrieving actual json page url and authorization api token self.content_json_url = raw_broadcast_info['content'] self.auth_api_token = raw_broadcast_info['apiToken'] # setting up authorization headers self.create_auth_headers() def retrieve_broadcast_id(self): """ Retrieves broadcast id for video to be downloaded. """ req = requests.get(self.content_json_url, headers=self.auth_headers) jdata = req.json() # best way to retrieve broadcast is via tracking attributes for video # to be downloaded self.broadcast_id = jdata['tracking']['nielsen']['content']['uurl'] # broadcast date self.broadcast_date = parse(jdata['editorialDate']) def retrieve_video_url(self): """ Retrieves url to actual video file to be downloaded """ # setting url to json page containing actual stream information url = "".join((self.BROADCAST_BASE_URL, self.broadcast_id)) req = requests.get(url, headers=self.auth_headers) jdata = req.json() for variant in jdata['priorityList']: # multiple video formats are available for vid_format in variant['formitaeten']: # choosing target video format if vid_format['mimeType'] == self.TGT_MIME_TYPE: # multiple qualities are available for quality in vid_format['qualities']: # choosing target video quality if quality['quality'] == self.quality: self.vid_url = quality['audio']['tracks'][0]['uri'] break def build_file_name(self): """ Builds target file name. """ # setting up a file name containing broadcast date and id basename = "_".join(( self.broadcast_date.strftime("%Y-%m-%d"), self.broadcast_id)) return ".".join((basename, 'mp4')) def retrieve_video(self, vid_url, file_name): """ Retrieves actual video data and downloads it to specified file name in class-wide target directory. """ # connecting to video url req = requests.get(vid_url, stream=True) tgt_bytes = int(req.headers['content-length']) tgt_path = os.path.join(self.tgt_dir, file_name) # downloading video data with open(tgt_path, 'wb') as handle: sum_bytes = 0 print("+ Downloading %d kB to %s" % (tgt_bytes / 1024, tgt_path)) for block in req.iter_content(self.DOWNLOAD_CHUNK_SIZE): if not block: # or sum_bytes > 5000000: break handle.write(block) sum_bytes += self.DOWNLOAD_CHUNK_SIZE if sum_bytes > tgt_bytes: sum_bytes = tgt_bytes pctg = float(sum_bytes) / tgt_bytes * 100. sys.stdout.write( "%d kB downloaded: %.1f%%\r" % (sum_bytes / 1024, pctg)) sys.stdout.flush() else: print() if __name__ == '__main__': arg_parser = argparse.ArgumentParser( description='Download videos from ZDF media library.') arg_parser.add_argument( '-d', '--directory', dest='tgt_dir', metavar='target_directory', required=True, help='Target directory for video downloads.') arg_parser.add_argument( '-q', '--quality', dest='quality', metavar='video quality', required=False, choices=['veryhigh', 'high', 'low'], default='high', help='Quality of downloaded videos') arg_parser.add_argument( 'urls', metavar='video_urls', help='Comma-separated list of video urls.') args = arg_parser.parse_args() dl = ZdfDownloader(args.tgt_dir, args.urls, quality=args.quality) dl.download_all()
502
4,530
23
1a245c6ec7443114f7802b71a77b0421f9982bb1
11,707
py
Python
tests/test_aztp_os_selector.py
jeremyschulman/aeon-ztps
45f649f9453a56da1cc16df183c6292505c33762
[ "Apache-2.0" ]
null
null
null
tests/test_aztp_os_selector.py
jeremyschulman/aeon-ztps
45f649f9453a56da1cc16df183c6292505c33762
[ "Apache-2.0" ]
null
null
null
tests/test_aztp_os_selector.py
jeremyschulman/aeon-ztps
45f649f9453a56da1cc16df183c6292505c33762
[ "Apache-2.0" ]
1
2021-07-07T18:10:15.000Z
2021-07-07T18:10:15.000Z
import os import yaml import tempfile import json import sys import copy from collections import namedtuple import pytest from mock import patch from aeon_ztp.bin import aztp_os_selector dev_data = { 'os_name': 'cumulus-vx', 'vendor': 'cumulus', 'hw_part_number': '1234', 'hostname': 'cumulus', 'fqdn': 'cumulus.localhost', 'virtual': True, 'service_tag': '1234', 'os_version': '3.1.1', 'hw_version': '1234', 'mac_address': '0123456789012', 'serial_number': '09786554', 'hw_model': 'cvx1000' } cfg_data = { 'default': { 'regex_match': '3\.1\.[12]', 'image': 'CumulusLinux-3.1.2-amd64.bin' }, 'group_a': { 'regex_match': '3\.1\.[12]', 'image': 'CumulusLinux-3.1.2-amd64.bin', 'matches': { 'hw_model': ['cvx1000'], 'mac_address': ['0123456789012', '2109876543210'] } } } @pytest.fixture() def os_sel_file(contents=None): """ Used to create a temporary os-selector file :param contents: python dictionary that will be converted to yaml :return: returns a temporary file string """ if not contents: contents = cfg_data os_sel = tempfile.NamedTemporaryFile(mode='w+t') os_sel.file.write(yaml.dump(contents, default_flow_style=False)) os_sel.file.flush() return os_sel @patch('aeon_ztp.bin.aztp_os_selector.exit_results', side_effect=SystemExit) @patch('aeon_ztp.bin.aztp_os_selector.json.loads') @patch('aeon_ztp.bin.aztp_os_selector.load_cfg', return_value=cfg_data) @patch('aeon_ztp.bin.aztp_os_selector.cli_parse') @patch('aeon_ztp.bin.aztp_os_selector.exit_results', side_effect=SystemExit) @patch('aeon_ztp.bin.aztp_os_selector.cli_parse') @patch('aeon_ztp.bin.aztp_os_selector.match_hw_model', side_effect=aztp_os_selector.HwNoMatchError) @patch('aeon_ztp.bin.aztp_os_selector.exit_results', side_effect=SystemExit) @patch('aeon_ztp.bin.aztp_os_selector.json.loads') @patch('aeon_ztp.bin.aztp_os_selector.load_cfg', return_value=cfg_data) @patch('aeon_ztp.bin.aztp_os_selector.cli_parse') @patch('aeon_ztp.bin.aztp_os_selector.match_hw_model', side_effect=aztp_os_selector.HwMultiMatchError) @patch('aeon_ztp.bin.aztp_os_selector.exit_results', side_effect=SystemExit) @patch('aeon_ztp.bin.aztp_os_selector.json.loads') @patch('aeon_ztp.bin.aztp_os_selector.load_cfg', return_value=cfg_data) @patch('aeon_ztp.bin.aztp_os_selector.cli_parse') @patch('aeon_ztp.bin.aztp_os_selector.match_os_version') @patch('aeon_ztp.bin.aztp_os_selector.match_hw_model') @patch('aeon_ztp.bin.aztp_os_selector.exit_results', side_effect=SystemExit) @patch('aeon_ztp.bin.aztp_os_selector.json.loads') @patch('aeon_ztp.bin.aztp_os_selector.load_cfg', return_value=cfg_data) @patch('aeon_ztp.bin.aztp_os_selector.cli_parse') @patch('aeon_ztp.bin.aztp_os_selector.match_os_version') @patch('aeon_ztp.bin.aztp_os_selector.match_hw_model') @patch('aeon_ztp.bin.aztp_os_selector.exit_results', side_effect=SystemExit) @patch('aeon_ztp.bin.aztp_os_selector.json.loads') @patch('aeon_ztp.bin.aztp_os_selector.load_cfg', return_value=cfg_data) @patch('aeon_ztp.bin.aztp_os_selector.cli_parse')
36.357143
124
0.679252
import os import yaml import tempfile import json import sys import copy from collections import namedtuple import pytest from mock import patch from aeon_ztp.bin import aztp_os_selector dev_data = { 'os_name': 'cumulus-vx', 'vendor': 'cumulus', 'hw_part_number': '1234', 'hostname': 'cumulus', 'fqdn': 'cumulus.localhost', 'virtual': True, 'service_tag': '1234', 'os_version': '3.1.1', 'hw_version': '1234', 'mac_address': '0123456789012', 'serial_number': '09786554', 'hw_model': 'cvx1000' } cfg_data = { 'default': { 'regex_match': '3\.1\.[12]', 'image': 'CumulusLinux-3.1.2-amd64.bin' }, 'group_a': { 'regex_match': '3\.1\.[12]', 'image': 'CumulusLinux-3.1.2-amd64.bin', 'matches': { 'hw_model': ['cvx1000'], 'mac_address': ['0123456789012', '2109876543210'] } } } @pytest.fixture() def cli_args(): parse = aztp_os_selector.cli_parse(['--json', json.dumps(dev_data), '--config', 'os-selector.cfg']) return parse def os_sel_file(contents=None): """ Used to create a temporary os-selector file :param contents: python dictionary that will be converted to yaml :return: returns a temporary file string """ if not contents: contents = cfg_data os_sel = tempfile.NamedTemporaryFile(mode='w+t') os_sel.file.write(yaml.dump(contents, default_flow_style=False)) os_sel.file.flush() return os_sel def test_cli_parse(): osf = os_sel_file() parse = aztp_os_selector.cli_parse(['-j', '{"test_key": "test_value"}', '-c', str(osf)]) assert json.loads(parse.json)['test_key'] == 'test_value' assert parse.config_file == str(osf) def test_cli_parse_parsererror(): osf = os_sel_file() with pytest.raises(aztp_os_selector.ArgumentParser.ParserError) as e: aztp_os_selector.cli_parse(['-c', osf.name]) assert 'ParserError' in str(e) def test_exit_results(): results = json.loads('{"ok": "True"}') # Supress stdout from exit_results old_stdout = sys.stdout sys.stdout = open(os.devnull, "w") try: aztp_os_selector.exit_results(results) except SystemExit as e: pass finally: # resume stdout sys.stdout.close() sys.stdout = old_stdout assert str(e) == '0' def test_load_cfg(): contents = {'default': { 'regex_match': '3\.1\.[12]', 'image': 'CumulusLinux-3.1.2-amd64.bin'}} osf = os_sel_file(contents=contents) cfg = aztp_os_selector.load_cfg(osf.name) assert cfg == contents def test_load_nonexistent_cfg(): # Supress stdout from exit_results old_stdout = sys.stdout sys.stdout = open(os.devnull, "w") try: aztp_os_selector.load_cfg('filename_that_does_not_exist') except SystemExit as e: pass finally: # resume stdout sys.stdout.close() sys.stdout = old_stdout assert str(e) == '1' def test_load_cfg_bad_syntax(): bad_yaml = '%%%%%%%%' os_sel = tempfile.NamedTemporaryFile(mode='w+b') os_sel.file.write(bad_yaml) os_sel.file.flush() # Supress stdout from exit_results old_stdout = sys.stdout sys.stdout = open(os.devnull, "w") try: aztp_os_selector.load_cfg(os_sel.name) except SystemExit as e: pass finally: # resume stdout sys.stdout.close() sys.stdout = old_stdout assert str(e) == '1' def test_match_hw_model(): match = aztp_os_selector.match_hw_model(dev_data, cfg_data) assert match[0] == 'group_a' assert match[1] == cfg_data['group_a'] def test_match_hw_model_no_match(): new_dev_data = copy.deepcopy(dev_data) new_dev_data['hw_model'] = 'cvx2000' match = aztp_os_selector.match_hw_model(new_dev_data, cfg_data) assert match[0] == 'default' assert match[1] == cfg_data['default'] def test_match_hw_model_no_default(): new_dev_data = copy.deepcopy(dev_data) new_dev_data['hw_model'] = 'cvx2000' new_cfg_data = copy.deepcopy(cfg_data) new_cfg_data.pop('default') try: aztp_os_selector.match_hw_model(new_dev_data, new_cfg_data) except aztp_os_selector.HwNoMatchError as e: pass assert isinstance(e, aztp_os_selector.HwNoMatchError) def test_match_hw_model_multi_match(): new_cfg_data = copy.deepcopy(cfg_data) new_cfg_data['group_b'] = { 'regex_match': '3\.1\.[12]', 'image': 'CumulusLinux-3.1.2-amd64.bin', 'matches': { 'hw_model': ['cvx1000'], 'mac_address': ['0123456789012', '2109876543210'] } } try: aztp_os_selector.match_hw_model(dev_data, new_cfg_data) except aztp_os_selector.HwMultiMatchError as e: pass assert isinstance(e, aztp_os_selector.HwMultiMatchError) def test_match_os_version_regex_no_upgrade(): item_match = namedtuple('item_match', ['hw_match', 'data']) hw_match = item_match('group_a', cfg_data['group_a']) upgrade = aztp_os_selector.match_os_version(dev_data, hw_match.data) assert not upgrade def test_match_os_version_exact_match_no_upgrade(): new_cfg_data = copy.deepcopy(cfg_data) new_cfg_data['group_a'].pop('regex_match') new_cfg_data['group_a']['exact_match'] = '3.1.1' item_match = namedtuple('item_match', ['hw_match', 'data']) hw_match = item_match('group_a', new_cfg_data['group_a']) upgrade = aztp_os_selector.match_os_version(dev_data, hw_match.data) assert not upgrade def test_match_os_version_regex_upgrade(): new_cfg_data = copy.deepcopy(cfg_data) new_cfg_data['group_a']['regex_match'] = '3\.1\.[23]' item_match = namedtuple('item_match', ['hw_match', 'data']) hw_match = item_match('group_a', new_cfg_data['group_a']) upgrade = aztp_os_selector.match_os_version(dev_data, hw_match.data) assert upgrade == new_cfg_data['group_a']['image'] def test_match_os_version_exact_match_upgrade(): new_cfg_data = copy.deepcopy(cfg_data) new_cfg_data['group_a'].pop('regex_match') new_cfg_data['group_a']['exact_match'] = '3.1.0' item_match = namedtuple('item_match', ['hw_match', 'data']) hw_match = item_match('group_a', new_cfg_data['group_a']) upgrade = aztp_os_selector.match_os_version(dev_data, hw_match.data) assert upgrade == new_cfg_data['group_a']['image'] def test_match_os_version_cfgerror(): with pytest.raises(aztp_os_selector.CfgError): dev_data = {'os_version': '1.A'} hw_match = [] aztp_os_selector.match_os_version(dev_data, hw_match) @patch('aeon_ztp.bin.aztp_os_selector.exit_results', side_effect=SystemExit) @patch('aeon_ztp.bin.aztp_os_selector.json.loads') @patch('aeon_ztp.bin.aztp_os_selector.load_cfg', return_value=cfg_data) @patch('aeon_ztp.bin.aztp_os_selector.cli_parse') def test_main_json_error(mock_cli_parse, mock_load_cfg, mock_json_load, mock_exit_results, cli_args): mock_json_load.side_effect = ValueError() mock_cli_parse.return_value = cli_args with pytest.raises(SystemExit): aztp_os_selector.main() mock_exit_results.assert_called_with({'ok': False, 'error_type': 'args', 'error_message': 'JSON argument formatted incorrectly.'}) @patch('aeon_ztp.bin.aztp_os_selector.exit_results', side_effect=SystemExit) @patch('aeon_ztp.bin.aztp_os_selector.cli_parse') def test_main_argparse_error(mock_cli_parse, mock_exit_results, cli_args): errmsg = 'test parse error' mock_cli_parse.side_effect = aztp_os_selector.ArgumentParser.ParserError(errmsg) with pytest.raises(SystemExit): aztp_os_selector.main() mock_exit_results.assert_called_with({'ok': False, 'error_type': 'args', 'error_message': errmsg}) @patch('aeon_ztp.bin.aztp_os_selector.match_hw_model', side_effect=aztp_os_selector.HwNoMatchError) @patch('aeon_ztp.bin.aztp_os_selector.exit_results', side_effect=SystemExit) @patch('aeon_ztp.bin.aztp_os_selector.json.loads') @patch('aeon_ztp.bin.aztp_os_selector.load_cfg', return_value=cfg_data) @patch('aeon_ztp.bin.aztp_os_selector.cli_parse') def test_main_hwnomatch_error(mock_cli_parse, mock_load_cfg, mock_json_load, mock_exit_results, mock_hw_match, cli_args): errmsg = 'no matching hw_model value' mock_cli_parse.return_value = cli_args with pytest.raises(SystemExit): aztp_os_selector.main() mock_exit_results.assert_called_with({'ok': False, 'error_type': 'hw_match', 'error_message': errmsg}) @patch('aeon_ztp.bin.aztp_os_selector.match_hw_model', side_effect=aztp_os_selector.HwMultiMatchError) @patch('aeon_ztp.bin.aztp_os_selector.exit_results', side_effect=SystemExit) @patch('aeon_ztp.bin.aztp_os_selector.json.loads') @patch('aeon_ztp.bin.aztp_os_selector.load_cfg', return_value=cfg_data) @patch('aeon_ztp.bin.aztp_os_selector.cli_parse') def test_main_hwmultimatch_error(mock_cli_parse, mock_load_cfg, mock_json_load, mock_exit_results, mock_hw_match, cli_args): errmsg = 'matches multiple os-selector groups' mock_hw_match.side_effect = aztp_os_selector.HwMultiMatchError(errmsg) mock_cli_parse.return_value = cli_args with pytest.raises(SystemExit): aztp_os_selector.main() mock_exit_results.assert_called_with({'ok': False, 'error_type': 'hw_match', 'error_message': errmsg}) @patch('aeon_ztp.bin.aztp_os_selector.match_os_version') @patch('aeon_ztp.bin.aztp_os_selector.match_hw_model') @patch('aeon_ztp.bin.aztp_os_selector.exit_results', side_effect=SystemExit) @patch('aeon_ztp.bin.aztp_os_selector.json.loads') @patch('aeon_ztp.bin.aztp_os_selector.load_cfg', return_value=cfg_data) @patch('aeon_ztp.bin.aztp_os_selector.cli_parse') def test_main_cfgerror(mock_cli_parse, mock_load_cfg, mock_json_load, mock_exit_results, mock_hw_match, mock_os_match, cli_args): errmsg = 'Expecting one of' mock_os_match.side_effect = aztp_os_selector.CfgError(errmsg) mock_cli_parse.return_value = cli_args with pytest.raises(SystemExit): aztp_os_selector.main() mock_exit_results.assert_called_with({'ok': False, 'error_type': 'cfg_error', 'error_message': errmsg}) @patch('aeon_ztp.bin.aztp_os_selector.match_os_version') @patch('aeon_ztp.bin.aztp_os_selector.match_hw_model') @patch('aeon_ztp.bin.aztp_os_selector.exit_results', side_effect=SystemExit) @patch('aeon_ztp.bin.aztp_os_selector.json.loads') @patch('aeon_ztp.bin.aztp_os_selector.load_cfg', return_value=cfg_data) @patch('aeon_ztp.bin.aztp_os_selector.cli_parse') def test_main(mock_cli_parse, mock_load_cfg, mock_json_load, mock_exit_results, mock_hw_match, mock_os_match, cli_args): sw_match = '1.0.0' item_match = namedtuple('item_match', ['hw_match', 'data']) hw_match = item_match(hw_match='default', data={'image': '1.0.1b', 'exact_match': '4.16.6M', 'finally': 'finally'}) mock_hw_match.return_value = hw_match mock_os_match.return_value = sw_match mock_cli_parse.return_value = cli_args with pytest.raises(SystemExit): aztp_os_selector.main() mock_exit_results.assert_called_with({'ok': True, 'image_name': sw_match, 'finally': hw_match.data['finally']})
8,022
0
499
f475c91d05ddbf6f7564e71bed827fc0d1f9127b
1,065
py
Python
lymph/tests/monitoring/test_aggregator.py
torte/lymph
1dc726dfa931c91a0068ddd81401d3321367f470
[ "Apache-2.0" ]
null
null
null
lymph/tests/monitoring/test_aggregator.py
torte/lymph
1dc726dfa931c91a0068ddd81401d3321367f470
[ "Apache-2.0" ]
null
null
null
lymph/tests/monitoring/test_aggregator.py
torte/lymph
1dc726dfa931c91a0068ddd81401d3321367f470
[ "Apache-2.0" ]
null
null
null
import unittest from lymph.core.monitoring.metrics import RawMetric from lymph.core.monitoring.aggregator import Aggregator
31.323529
121
0.676995
import unittest from lymph.core.monitoring.metrics import RawMetric from lymph.core.monitoring.aggregator import Aggregator def _get_metrics_one(): yield RawMetric('dummy', 'one') def _get_metrics_two(): yield RawMetric('dummy', 'two') class AggregatorTestCase(unittest.TestCase): def test_aggregator_one_component(self): aggr = Aggregator(_get_metrics_one, name='test') self.assertIn(('dummy', 'one', {'name': 'test'}), list(aggr.get_metrics())) def test_aggregator_multiple_components(self): aggr = Aggregator(_get_metrics_one, _get_metrics_two, name='test') self.assertIn(('dummy', 'one', {'name': 'test'}), list(aggr.get_metrics())) self.assertIn(('dummy', 'two', {'name': 'test'}), list(aggr.get_metrics())) def test_aggregator_add_multiple_tags(self): aggr = Aggregator(_get_metrics_one, name='test') aggr.add_tags(origin='localhost', time='now') self.assertIn(('dummy', 'one', {'name': 'test', 'origin': 'localhost', 'time': 'now'}), list(aggr.get_metrics()))
764
23
150
e2c2e185e25912314724f45aa243c157fc190970
4,322
py
Python
Compare_simple_warehouse/without_GA/param.py
liuyandong1988/Warehouse_GA
3dd6f07ae03c3b1a7eb1a961ed03e88a245a4455
[ "MIT" ]
1
2019-07-30T09:41:53.000Z
2019-07-30T09:41:53.000Z
Compare_simple_warehouse/without_GA/param.py
liuyandong1988/Warehouse_GA
3dd6f07ae03c3b1a7eb1a961ed03e88a245a4455
[ "MIT" ]
null
null
null
Compare_simple_warehouse/without_GA/param.py
liuyandong1988/Warehouse_GA
3dd6f07ae03c3b1a7eb1a961ed03e88a245a4455
[ "MIT" ]
null
null
null
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2017 eelium <eelium@eez008> # # Distributed under terms of the MIT license. import random """ parameters """ # The window refresh rate REFRESH_INTERVAL = 50 # the ground size margin_left = 100 margin_right = 100 margin_top = 100 margin_bottom = 100 L = 50 # unit value in pixel; as scalar # the window size world_height = 16 * L + margin_top + margin_bottom world_width = 22 * L + margin_left + margin_right # robot numbers NUM_AGENTS = 8 # agent speed agent_speed = 40 # TODO: parameterize this magic number TIME_RATE = 2 FRAME_PER_SECOND = 20.0 # # collision allows the angle # th_close_angle = 45 all_finish_mark = 0 # good position letter (forward,backward) ROW1_LEFT = [ ('B1', 'A1') , ('A2', 'B2') , ('B3', 'A3') , ('A4', 'B4') , ('B5', 'A5') , ('A6', 'B6') , ('B7', 'A7') ] ROW1_RIGHT = [ ('A2', 'B2') , ('B3', 'A3') , ('A4', 'B4') , ('B5', 'A5') , ('A6', 'B6') , ('B7', 'A7') , ('A8', 'B8')] ROW2_LEFT = [ ('C1', 'B1') , ('B2', 'C2') , ('C3', 'B3') , ('B4', 'C4') , ('C5', 'B5') , ('B6', 'C6') , ('C7', 'B7') ] ROW2_RIGHT = [ ('B2', 'C2') , ('C3', 'B3') , ('B4', 'C4') , ('C5', 'B5') , ('B6', 'C6') , ('C7', 'B7') , ('B8', 'C8') ] ROW3_LEFT = [ ('D1', 'C1') , ('C2', 'D2') , ('D3', 'C3') , ('C4', 'D4') , ('D5', 'C5') , ('C6', 'D6') , ('D7', 'C7') ] ROW3_RIGHT = [ ('C2', 'D2') , ('D3', 'C3') , ('C4', 'D4') , ('D5', 'C5') , ('C6', 'D6') , ('D7', 'C7') , ('C8', 'D8') ] # #Class goods # CLASS_GOODS_DIC = { # 0: [0, 1, 2, 3, 4, 5, 6, 7], # 1: [8, 9, 10, 11, 12, 13, 14, 15], # 2: [16, 17, 18, 19, 20, 21, 22, 23], # 3: [24, 25, 26, 27, 28, 29, 30, 31], # 4: [32, 33, 34, 35, 36, 37, 38, 39], # 5: [40, 41, 42, 43, 44, 45, 46, 47], # 6: [48, 49, 50, 51, 52, 53, 54, 55], # 7: [56, 57, 58, 59, 60, 61, 62, 63], # 8: [64, 65, 66, 67, 68, 69, 70, 71], # 9: [72, 73, 74, 75, 76, 77, 78, 79], # 10: [80, 81, 82, 83, 84, 85, 86, 87], # 11: [88, 89, 90, 91, 92, 93, 94, 95], # 12: [96, 97, 98, 99, 100, 101, 102, 103], # 13: [104, 105, 106, 107, 108, 109, 110, 111], # 14: [112, 113, 114, 115, 116, 117, 118, 119], # 15: [120, 121, 122, 123, 124, 125, 126, 127], # 16: [128, 129, 130, 131, 132, 133, 134, 135], # 17: [136, 137, 138, 139, 140, 141, 142, 143], # 18: [144, 145, 146, 147, 148, 149, 150, 151], # 19: [152, 153, 154, 155, 156, 157, 158, 159], # 20: [160, 161, 162, 163, 164, 165, 166, 167]} # charging park CHARGING_PARK = ['Y1', 'Y2', 'Y3', 'Y4', 'Y5', 'Y6', 'Y7', 'Y8'] # order points UNLOADING_POSITION = ['Z1', 'Z5'] #goods colour SHELVES_COLOR = {0:'BLUE', 1:'SLATE BLUE', 2:'GREEN', 3:'SPRING GREEN', 4:'CYAN', 5:'NAVY', 6:'STEEL BLUE', 7:'FOREST GREEN', 8:'SEA GREEN', 9:'SEA GREEN', 10:'MIDNIGHT BLUE', 11:'DARK GREEN', 12:'DARK SLATE GREY', 13:'MEDIUM BLUE', 14:'SKY BLUE', 15:'LIME GREEN', 16:'MEDIUM AQUAMARINE', 17:'CORNFLOWER BLUE', 18:'MEDIUM SEA GREEN', 19:'INDIAN RED', 20:'VIOLET', 21:'DARK OLIVE GREEN'} # goods = 0 # #total goods # for i in xrange(ORDER_NUM): # goods += len(GOODS_ORDER[i]) # TOTAL_GOODS = goods # goods order # GOODS_ORDER = {0:[790, 160, 1210, 1010, 130, 220, 590, 980, 1400, 1020, 1040, 370], # 1:[650, 1170, 950, 1100, 540, 1650, 60, 470, 1500, 210, 890, 830, 990]} #1 # GOODS_ORDER = {0:[1150, 1340, 350, 110, 600, 670, 120, 1160, 1490, 790, 730, 1540], # 1:[1210, 520, 1050, 400, 1140, 190, 210, 90, 870, 1560, 1130, 1640, 690]} #2 # GOODS_ORDER = {0:[40, 860, 150, 400, 690, 1570, 1630, 760, 1370, 1420, 320, 230], # 1:[480, 1670, 1320, 1430, 1300, 1610, 280, 570, 920, 530, 910, 200, 260]} #3 # GOODS_ORDER = {0:[140, 450, 1250, 1230, 150, 1350, 970, 350, 120, 1430, 1550, 300], # 1:[1100, 570, 1640, 160, 1070, 790, 770, 130, 1010, 830, 90, 550, 890]} #4 GOODS_ORDER = {0:[950, 1130, 1510, 550, 1200, 890, 1370, 1240, 990, 450, 1170, 440], 1:[1180, 1640, 1290, 60, 480, 230, 370, 140, 740, 1310, 1480, 150, 870]} #5 # # # goods order # GOODS_ORDER = {0:[790, 160, 1210, 1010, 130], # 1:[650, 1170, 950]} #order number ORDER_NUM = len(GOODS_ORDER)
34.576
113
0.512031
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2017 eelium <eelium@eez008> # # Distributed under terms of the MIT license. import random """ parameters """ # The window refresh rate REFRESH_INTERVAL = 50 # the ground size margin_left = 100 margin_right = 100 margin_top = 100 margin_bottom = 100 L = 50 # unit value in pixel; as scalar # the window size world_height = 16 * L + margin_top + margin_bottom world_width = 22 * L + margin_left + margin_right # robot numbers NUM_AGENTS = 8 # agent speed agent_speed = 40 # TODO: parameterize this magic number TIME_RATE = 2 FRAME_PER_SECOND = 20.0 # # collision allows the angle # th_close_angle = 45 all_finish_mark = 0 # good position letter (forward,backward) ROW1_LEFT = [ ('B1', 'A1') , ('A2', 'B2') , ('B3', 'A3') , ('A4', 'B4') , ('B5', 'A5') , ('A6', 'B6') , ('B7', 'A7') ] ROW1_RIGHT = [ ('A2', 'B2') , ('B3', 'A3') , ('A4', 'B4') , ('B5', 'A5') , ('A6', 'B6') , ('B7', 'A7') , ('A8', 'B8')] ROW2_LEFT = [ ('C1', 'B1') , ('B2', 'C2') , ('C3', 'B3') , ('B4', 'C4') , ('C5', 'B5') , ('B6', 'C6') , ('C7', 'B7') ] ROW2_RIGHT = [ ('B2', 'C2') , ('C3', 'B3') , ('B4', 'C4') , ('C5', 'B5') , ('B6', 'C6') , ('C7', 'B7') , ('B8', 'C8') ] ROW3_LEFT = [ ('D1', 'C1') , ('C2', 'D2') , ('D3', 'C3') , ('C4', 'D4') , ('D5', 'C5') , ('C6', 'D6') , ('D7', 'C7') ] ROW3_RIGHT = [ ('C2', 'D2') , ('D3', 'C3') , ('C4', 'D4') , ('D5', 'C5') , ('C6', 'D6') , ('D7', 'C7') , ('C8', 'D8') ] # #Class goods # CLASS_GOODS_DIC = { # 0: [0, 1, 2, 3, 4, 5, 6, 7], # 1: [8, 9, 10, 11, 12, 13, 14, 15], # 2: [16, 17, 18, 19, 20, 21, 22, 23], # 3: [24, 25, 26, 27, 28, 29, 30, 31], # 4: [32, 33, 34, 35, 36, 37, 38, 39], # 5: [40, 41, 42, 43, 44, 45, 46, 47], # 6: [48, 49, 50, 51, 52, 53, 54, 55], # 7: [56, 57, 58, 59, 60, 61, 62, 63], # 8: [64, 65, 66, 67, 68, 69, 70, 71], # 9: [72, 73, 74, 75, 76, 77, 78, 79], # 10: [80, 81, 82, 83, 84, 85, 86, 87], # 11: [88, 89, 90, 91, 92, 93, 94, 95], # 12: [96, 97, 98, 99, 100, 101, 102, 103], # 13: [104, 105, 106, 107, 108, 109, 110, 111], # 14: [112, 113, 114, 115, 116, 117, 118, 119], # 15: [120, 121, 122, 123, 124, 125, 126, 127], # 16: [128, 129, 130, 131, 132, 133, 134, 135], # 17: [136, 137, 138, 139, 140, 141, 142, 143], # 18: [144, 145, 146, 147, 148, 149, 150, 151], # 19: [152, 153, 154, 155, 156, 157, 158, 159], # 20: [160, 161, 162, 163, 164, 165, 166, 167]} # charging park CHARGING_PARK = ['Y1', 'Y2', 'Y3', 'Y4', 'Y5', 'Y6', 'Y7', 'Y8'] # order points UNLOADING_POSITION = ['Z1', 'Z5'] #goods colour SHELVES_COLOR = {0:'BLUE', 1:'SLATE BLUE', 2:'GREEN', 3:'SPRING GREEN', 4:'CYAN', 5:'NAVY', 6:'STEEL BLUE', 7:'FOREST GREEN', 8:'SEA GREEN', 9:'SEA GREEN', 10:'MIDNIGHT BLUE', 11:'DARK GREEN', 12:'DARK SLATE GREY', 13:'MEDIUM BLUE', 14:'SKY BLUE', 15:'LIME GREEN', 16:'MEDIUM AQUAMARINE', 17:'CORNFLOWER BLUE', 18:'MEDIUM SEA GREEN', 19:'INDIAN RED', 20:'VIOLET', 21:'DARK OLIVE GREEN'} # goods = 0 # #total goods # for i in xrange(ORDER_NUM): # goods += len(GOODS_ORDER[i]) # TOTAL_GOODS = goods # goods order # GOODS_ORDER = {0:[790, 160, 1210, 1010, 130, 220, 590, 980, 1400, 1020, 1040, 370], # 1:[650, 1170, 950, 1100, 540, 1650, 60, 470, 1500, 210, 890, 830, 990]} #1 # GOODS_ORDER = {0:[1150, 1340, 350, 110, 600, 670, 120, 1160, 1490, 790, 730, 1540], # 1:[1210, 520, 1050, 400, 1140, 190, 210, 90, 870, 1560, 1130, 1640, 690]} #2 # GOODS_ORDER = {0:[40, 860, 150, 400, 690, 1570, 1630, 760, 1370, 1420, 320, 230], # 1:[480, 1670, 1320, 1430, 1300, 1610, 280, 570, 920, 530, 910, 200, 260]} #3 # GOODS_ORDER = {0:[140, 450, 1250, 1230, 150, 1350, 970, 350, 120, 1430, 1550, 300], # 1:[1100, 570, 1640, 160, 1070, 790, 770, 130, 1010, 830, 90, 550, 890]} #4 GOODS_ORDER = {0:[950, 1130, 1510, 550, 1200, 890, 1370, 1240, 990, 450, 1170, 440], 1:[1180, 1640, 1290, 60, 480, 230, 370, 140, 740, 1310, 1480, 150, 870]} #5 # # # goods order # GOODS_ORDER = {0:[790, 160, 1210, 1010, 130], # 1:[650, 1170, 950]} #order number ORDER_NUM = len(GOODS_ORDER)
0
0
0
5016217d66d62951ba236ae324a5ee4c82ba7fd0
59,821
py
Python
Seth/importer/views.py
Inf1n1te/Seth
4ccfcba6226f3d284fd955cd0a81316402e8d043
[ "BSD-3-Clause" ]
1
2020-08-09T01:26:31.000Z
2020-08-09T01:26:31.000Z
Seth/importer/views.py
Inf1n1te/Seth
4ccfcba6226f3d284fd955cd0a81316402e8d043
[ "BSD-3-Clause" ]
17
2017-11-15T10:06:02.000Z
2019-02-13T15:32:41.000Z
Seth/importer/views.py
Inf1n1te/Seth
4ccfcba6226f3d284fd955cd0a81316402e8d043
[ "BSD-3-Clause" ]
null
null
null
from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied, SuspiciousOperation from django.db import transaction from django.db.utils import IntegrityError from django.http.response import HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponse, \ Http404 from django.shortcuts import render, redirect, get_object_or_404 from django.utils.decorators import method_decorator from django.views import generic, View from django.utils import timezone from django.db.models import Q import django_excel as excel from django.views.decorators.http import require_http_methods, require_GET from django.views.generic import TemplateView, FormView from permission_utils import * from dashboard.views import bad_request import re from Grades.exceptions import GradeException from Grades.models import ModuleEdition, Grade, Test, Person, ModulePart, Studying, Module, Study from importer.forms import GradeUploadForm, TestGradeUploadForm, ImportStudentForm, ImportStudentModule, \ ImportModuleEditionStructureForm, COLUMN_TITLE_ROW, ImportModuleForm # Create your views here. class ImporterIndexView(LoginRequiredMixin, View): """Index view of the importer module. Serves both Module Coordinators and Teachers. Module coordinators are presented with an overview of the module editions they are a coordinator of, for which they can perform administrative actions. They can add students to a module edition, and download and upload a form that contains grades for the tests which are in the module. This can be done for the whole module, or per test individually. Teachers receive a list of module parts that are a teacher of, with their tests. They can, like module coordinators, download and upload an excel sheet that contains grades. This can be done per test individually. """ model = ModuleEdition @login_required @require_http_methods(["GET", "POST"]) @transaction.atomic def import_module(request, pk): """Module import. Use an .xlsx file to submit grades to a module edition On GET the user is presented with a file upload form. On POST, the submitted .xlsx file is processed by the system, registering Grade object for each grade in the excel file. It dynamically detects the tests that are submitted (by exact name match or database ID), and omits extra columns silently. Also, lines that do not have a filled in student number are ignored. Students that are not declared as part of the module (def:import_student_to_module) raise an import error. :param request: Django request :param pk: Module that grades should be submitted to :return: A redirect to the Grades module's module view on success. Otherwise a 404 (module does not exist), 403 (no permissions) or 400 (bad excel file or other import error) """ person = Person.objects.filter(user=request.user).first() module_edition = get_object_or_404(ModuleEdition, pk=pk) if not is_coordinator_or_assistant_of_module(person, module_edition): raise PermissionDenied('You are not the module coordinator for this course') if request.method == "POST": form = GradeUploadForm(request.POST, request.FILES) if form.is_valid(): title_row = form.cleaned_data.get('title_row') - 1 # Check if /any/ tests and/or grades are imported. any_tests = False # List of all tests that are imported. all_tests = [] sheet = request.FILES['file'].get_book_dict() for table in sheet: # Check if the sheet has enough rows if title_row >= len(sheet[table]) : return bad_request(request, {'message': 'The file that was uploaded was not recognised as a grade ' 'excel file. Are you sure the file is an .xlsx file, and ' 'that all fields are present? Otherwise, download a new ' 'gradesheet and try using that instead.'}) test_rows = dict() university_number_field = None # Detect university_number and test columns for title_index in range(0, len(sheet[table][title_row])): # This is the university number column if ('number' in str(sheet[table][title_row][title_index]).lower()) or \ ('nummer' in str(sheet[table][title_row][title_index]).lower()): university_number_field = title_index else: # Attempt to find a Test # search by ID try: test = Test.objects.filter( pk=sheet[table][title_row][title_index]) if test and test.filter(module_part__module_edition=module_edition): test_rows[title_index] = sheet[table][title_row][title_index] # pk of Test any_tests = True except (ValueError, TypeError): # search by name if Test.objects.filter( name=sheet[table][title_row][title_index] ).filter(module_part__module_edition=pk): test_rows[title_index] = Test.objects.filter( name=sheet[table][title_row][title_index] ).filter(module_part__module_edition=pk)[0].pk # pk of Test any_tests = True # Else not a test, continue... if university_number_field is None: continue # Ignore this sheet if len(test_rows.keys()) == 0: continue # Ignore this sheet # The current user's Person is the corrector of the grades. teacher = Person.objects.filter(user=request.user).first() grades = [] # Retrieve Test object beforehand to validate permissions on tests and speed up Grade creation tests = dict() test_prefetch = Test.objects.prefetch_related('module_part__module_edition__module') for test_column in test_rows.keys(): tests[test_column] = test_prefetch.get(pk=test_rows[test_column]) [all_tests.append(test) for test in tests.values() if test] # Check excel file for invalid students invalid_students = [] for row in sheet[table][(title_row + 1):]: if not Studying.objects.filter(person__university_number__contains=row[university_number_field]).filter( module_edition=pk): invalid_students.append(row[university_number_field]) # Check for invalid student numbers in the university_number column, but ignore empty fields. if [student for student in invalid_students if student is not '']: return bad_request(request, {'message': 'Students {} are not enrolled in this module. ' 'Enroll these students first before retrying.' .format(invalid_students)}) # Make Grades for row in sheet[table][(title_row + 1):]: # Walk horizontally over table student = Person.objects.filter(university_number__contains=row[university_number_field]).first() # check if this is not an empty line, else continue. if student: for test_column in test_rows.keys(): try: grades.append(make_grade( student=student, corrector=teacher, test=tests[test_column], grade=row[test_column] )) except GradeException as e: # Called for either: bad grade, grade out of bounds return HttpResponseBadRequest(e) save_grades(grades) # Bulk-save grades. Also prevents a partial import of the sheet. # Check if anything was imported. if not any_tests: return bad_request(request, {'message': 'There were no tests recognized to import.'}) return render(request=request, template_name='importer/successfully_imported.html', context={'tests': all_tests}) else: return bad_request(request, {'message': 'The file that was uploaded was not recognised as a grade excel ' 'file. Are you sure the file is an .xlsx file? Otherwise, download ' 'a new gradesheet and try using that instead.'}) else: # GET request form = GradeUploadForm() return render(request, 'importer/importmodule.html', {'form': form, 'pk': pk}) @login_required @require_http_methods(["GET", "POST"]) @transaction.atomic def import_module_part(request, pk): """Module part import. Use an .xlsx file to submit grades to a module part On GET the user is presented with a file upload form. On POST, the submitted .xlsx file is processed by the system, registering Grade object for each grade in the excel file. It dynamically detects the tests that are submitted (by exact name match or database ID), and omits extra columns silently. Also, lines that do not have a filled in student number are ignored. Students that are not declared as part of the module (def:import_student_to_module) raise an import error. :param request: Django request :param pk: Module part that grades should be submitted to :return: A redirect to the Grades course view on success. Otherwise a 404 (module does not exist), 403 (no permissions) or 400 (bad excel file or other import error) """ module_part = get_object_or_404(ModulePart, pk=pk) module_edition = get_object_or_404(ModuleEdition, modulepart=module_part) person = Person.objects.filter(user=request.user).filter( Q(coordinator__module_edition__modulepart=module_part) | Q(teacher__module_part=module_part) ).first() if not ModuleEdition.objects.filter(modulepart=module_part): raise Http404('Module does not exist.') if not (is_coordinator_or_assistant_of_module(person, module_edition) or is_coordinator_or_teacher_of_module_part(person, module_part)): raise PermissionDenied('You are not allowed to do this.') if request.method == "POST": form = GradeUploadForm(request.POST, request.FILES) if form.is_valid(): title_row = form.cleaned_data.get('title_row') - 1 # Check if /any/ tests and/or grades are imported. any_tests = False # List of all tests that are imported. all_tests = [] sheet = request.FILES['file'].get_book_dict() for table in sheet: # Check if the sheet has enough rows if title_row >= len(sheet[table]): return bad_request(request, {'message': 'The file that was uploaded was not recognised as a grade' ' excel file. Are you sure the file is an .xlsx file, and' ' that all fields are present? Otherwise, download a new' ' gradesheet and try using that instead.'}) test_rows = dict() university_number_field = None # Detect university_number and test columns for title_index in range(0, len(sheet[table][title_row])): # This is the university number column if ('number' in str(sheet[table][title_row][title_index]).lower()) or \ ('nummer' in str(sheet[table][title_row][title_index]).lower()): university_number_field = title_index else: # Attempt to find a Test # search by ID try: test = Test.objects.filter( pk=sheet[table][title_row][title_index]) if test and test.filter(module_part=module_part): test_rows[title_index] = sheet[table][title_row][title_index] # pk of Test any_tests = True except (ValueError, TypeError): pass # Not an int. # search by name if Test.objects.filter(module_part=module_part).filter( name=sheet[table][title_row][title_index]): test_rows[title_index] = Test.objects.filter( name=sheet[table][title_row][title_index] ).filter(module_part=module_part)[0].pk # pk of Test any_tests = True # Attempt to ignore test altogether. else: pass if university_number_field is None: continue # Ignore this sheet if len(test_rows.keys()) == 0: continue # Ignore this sheet # The current user's Person is the corrector of the grades. teacher = Person.objects.filter(user=request.user).first() grades = [] # Retrieve Test object beforehand to validate permissions on tests and speed up Grade creation tests = dict() for test_column in test_rows.keys(): tests[test_column] = Test.objects.get(pk=test_rows[test_column]) [all_tests.append(test) for test in tests.values() if test] # Check excel file for invalid students invalid_students = [] for row in sheet[table][(title_row + 1):]: if not Studying.objects.filter(person__university_number__contains=row[university_number_field]).filter( module_edition=module_edition): invalid_students.append(row[university_number_field]) # Check for invalid student numbers in the university_number column, but ignore empty fields. if [student for student in invalid_students if student is not '']: return bad_request(request, {'message': 'Students {} are not enrolled in this module.\n ' 'Enroll these students first before retrying' .format(invalid_students)}) # Make Grades for row in sheet[table][(title_row + 1):]: # Walk horizontally over table student = Person.objects.filter(university_number__contains=row[university_number_field]).first() # check if this is not an empty line, else continue. if student: for test_column in test_rows.keys(): try: grades.append(make_grade( student=student, corrector=teacher, test=tests[test_column], grade=row[test_column] )) except GradeException as e: # Called for either: bad grade, grade out of bounds return bad_request(request, {'message': e}) save_grades(grades) # Bulk-save grades. Also prevents a partial import of the sheet. # Check if anything was imported. if not any_tests: return bad_request(request, {'message': 'There were no tests recognized to import.'}) return render(request=request, template_name='importer/successfully_imported.html', context={'tests': all_tests}) else: return bad_request(request, {'message': 'The file uploaded was not recognised as a grade excel file.' ' Are you sure the file is an .xlsx file? Otherwise, download a new' ' gradesheet and try using that instead'}) else: # GET request form = GradeUploadForm() return render(request, 'importer/importmodulepart.html', {'form': form, 'pk': pk, 'module_part': module_part}) @login_required @require_http_methods(["GET", "POST"]) @transaction.atomic def import_test(request, pk): """ Test import. Use an .xlsx file to submit grades to a test On GET the user is presented with a file upload form. On POST, the submitted .xlsx file is processed by the system, registering Grade object for each grade in the excel file. Lines that do not have a filled in student number are ignored. Students that are not declared as part of the module (def:import_student_to_module) the test is in raise an import error. :param request: Django request :param pk: Test that grades should be submitted to :return: A redirect to the Grades module's Test view on success. Otherwise a 404 (module does not exist), 403 (no permissions) or 400 (bad excel file or other import error) """ # Check if user is either the module coordinator or teacher of this test. test = get_object_or_404(Test, pk=pk) person = Person.objects.filter(user=request.user).first() if not is_coordinator_or_teacher_of_test(person, test): raise PermissionDenied('You are not a module coordinator or teacher of this test. Please refer to the' 'module coordinator of this test if you think this is in error.') if request.method == "POST": form = TestGradeUploadForm(request.POST, request.FILES) if form.is_valid(): title_row = form.cleaned_data.get('title_row') - 1 sheet = request.FILES['file'].get_book_dict() for table in sheet: # Check dimensions if not len(sheet[table]) > title_row and len(sheet[table][0]) == 3: return bad_request(request, {'message': 'The file that was uploaded was not recognised as a grade ' 'excel file. Are you sure all columns are present? ' 'Otherwise, download a new gradesheet and try using that ' 'instead.'}) # Identify columns try: student_id_field = sheet[table][title_row].index('university_number') grade_field = sheet[table][title_row].index('grade') description_field = sheet[table][title_row].index('description') except ValueError: return bad_request(request, {'message': 'One of the required field [student_id, grade, description]' ' could not be found.'}) # The current user's Person is the corrector of the grades. teacher = Person.objects.filter(user=request.user).first() # Check excel file for invalid students invalid_students = [] for row in sheet[table][(title_row + 1):]: if not Studying.objects.filter(person__university_number=row[0]).filter( module_edition=test.module_part.module_edition_id): invalid_students.append(row[0]) # Check for invalid student numbers in the university_number column, but ignore empty fields. if [student for student in invalid_students if student is not '']: return bad_request(request, {'message': 'Students {} are not enrolled in this module. ' 'Enroll these students first before retrying.' .format(invalid_students)}) elif invalid_students: return bad_request(request, {'message': 'There are grades or description fields in this excel sheet' ' that do not have a student number filled in. Please' ' check the contents of your excel file for stale values' ' in rows.'}) grades = [] for row in sheet[table][(title_row + 1):]: try: student = Person.objects.get(university_number=row[student_id_field]) # check if this is not an empty line, else continue. if student: grades.append(make_grade( student=student, corrector=teacher, test=test, grade=row[grade_field], description=row[description_field] )) except GradeException as e: # Called for either: bad grade, grade out of bounds return bad_request(request, {'message': e}) save_grades(grades) # Bulk-save grades. Also prevents a partial import of the sheet. return redirect('grades:test', pk) else: return bad_request(request, {'message': 'Bad POST'}) else: if Test.objects.filter(pk=pk): form = TestGradeUploadForm() return render(request, 'importer/importtest.html', {'test': Test.objects.get(pk=pk), 'form': form, 'pk': pk}) else: return bad_request(request, {'message', 'Test does not exists'}) @login_required() @require_http_methods(["GET"]) def export_module(request, pk): """ Creates an excel sheet that contains all tests against all students in the module. This sheet is compatible with def:import_module. :param request: Django request :param pk: Module ID :return: A file response containing an .xlsx file. """ module_edition = get_object_or_404(ModuleEdition, pk=pk) person = Person.objects.filter(user=request.user).first() # Check if user is a module coordinator. if not is_coordinator_or_assistant_of_module(person, module_edition): raise PermissionDenied('You are not the module coordinator for this course.') students = Person.objects.filter(studying__module_edition=module_edition).values('university_number', 'name') tests = Test.objects.filter(module_part__module_edition=module_edition) # Pre-fill first few columns. table = [ ['Module:', str(module_edition)]+['' for _ in range(len(tests))], ] + [['' for _ in range(len(tests) + 2)] for _ in range(COLUMN_TITLE_ROW - 4)] # Add the module part name and test name for each test if there is enough header room. if COLUMN_TITLE_ROW > 2: table.append(['', 'Module part >'] + [test.module_part.name for test in tests]) if COLUMN_TITLE_ROW > 1: table.append(['', 'Test name >'] + [test.name for test in tests]) if COLUMN_TITLE_ROW > 0: table.append(['', 'Grade between >'] + ['{} - {}'.format(test.minimum_grade, test.maximum_grade) for test in tests]) # Add machine-readable header row. table.append(['university_number', 'name'] + [test.name for test in tests]) # pre-fill student numbers for student in students: table.append([student['university_number'], student['name']] + [None for _ in range(len(tests))]) return excel.make_response_from_array(table, file_name='Module Grades {} {}-{}.xlsx'.format(module_edition.module.name, module_edition.year, module_edition.block), file_type='xlsx') @login_required() @require_http_methods(["GET"]) def export_module_part(request, pk): """ Creates an excel sheet that contains all tests that are in a course. Used mainly to download sign off excel sheets. :param request: Django request :param pk: Module part ID :return: A file response containing an .xlsx file. """ module_part = get_object_or_404(ModulePart, pk=pk) module_edition = ModuleEdition.objects.get(modulepart=module_part) person = Person.objects.filter(user=request.user).first() # Check if user is a module coordinator. if not is_coordinator_or_teacher_of_module_part(person, module_part): raise PermissionDenied('You are not the module coordinator for this course.') students = Person.objects.filter(studying__module_edition=module_edition).values('university_number', 'name') tests = Test.objects.filter(module_part=module_part).values('pk', 'name', 'minimum_grade', 'maximum_grade') # Pre-fill first few columns. table = [['' for _ in range(len(tests) + 2)] for _ in range(COLUMN_TITLE_ROW - 2)] # Add the module part name and test name for each test if there is enough header room. if COLUMN_TITLE_ROW > 1: table.append(['', 'Test name >'] + [test['name'] for test in tests]) if COLUMN_TITLE_ROW > 0: table.append(['', 'Grade between >'] + ['{} - {}'.format(test['minimum_grade'], test['maximum_grade']) for test in tests]) # Add machine-readable header row. table.append(['university_number', 'name'] + [test['name'] for test in tests]) # pre-fill student numbers for student in students: table.append([student['university_number'], student['name']] + [None for _ in range(len(tests))]) return excel.make_response_from_array(table, file_name='Sign-off sheet {} {}-{}.xlsx'.format(module_edition.module.name, module_edition.year, module_edition.block), file_type='xlsx') @login_required() @require_http_methods(["GET"]) def export_module_part_signoff(request, pk): """ Creates an excel sheet that contains all tests that are in a course. Used mainly to download sign off excel sheets. :param request: Django request :param pk: Module part ID :return: A file response containing an .xlsx file. """ module_part = get_object_or_404(ModulePart, pk=pk) module_edition = ModuleEdition.objects.get(modulepart=module_part) person = Person.objects.filter(user=request.user).first() # Check if user is a module coordinator. if not is_coordinator_or_teacher_of_module_part(person, module_part): raise PermissionDenied('You are not the module coordinator for this course.') students = Person.objects.filter(studying__module_edition=module_edition).values('university_number', 'name') tests = Test.objects.filter(module_part=module_part, type='A').values('pk', 'name', 'minimum_grade', 'maximum_grade') # Pre-fill first few columns. table = [['' for _ in range(len(tests) + 2)] for _ in range(COLUMN_TITLE_ROW - 2)] # Add the module part name and test name for each test if there is enough header room. if COLUMN_TITLE_ROW > 1: table.append(['', 'Test name >'] + [test['name'] for test in tests]) if COLUMN_TITLE_ROW > 0: table.append(['', 'Grade between >'] + ['{} - {}'.format(test['minimum_grade'], test['maximum_grade']) for test in tests]) # Add machine-readable header row. table.append(['university_number', 'name'] + [test['name'] for test in tests]) # pre-fill student numbers for student in students: table.append([student['university_number'], student['name']] + [None for _ in range(len(tests))]) return excel.make_response_from_array(table, file_name='Sign-off sheet {} {}-{}.xlsx'.format(module_edition.module.name, module_edition.year, module_edition.block), file_type='xlsx') @login_required() @require_http_methods(["GET"]) def export_test(request, pk): """ Creates an excel sheet that contains all students that may take the test. This sheet is compatible with def:import_test. It contains a description row, which can be used to submit feedback through. :param request: Django request :param pk: Test ID :return: A file response containing an .xlsx file. """ test = get_object_or_404(Test, pk=pk) person = Person.objects.filter(user=request.user).first() # Check if user is either the module coordinator or teacher of this test. if not is_coordinator_or_teacher_of_test(person, test): raise PermissionDenied('Not allowed to export test.') students = Person.objects.filter(studying__module_edition__modulepart=test.module_part).values('university_number', 'name') # Insert padding table = [ [test.name, "", "grade between:", '{} - {}'.format(test.minimum_grade, test.maximum_grade)] ] + [['', '', '', ''] for _ in range(COLUMN_TITLE_ROW - 1)] # Insert title row table.append(['university_number', 'name', 'grade', 'description']) # Insert student numbers for student in students: table.append([student['university_number'], student['name'], '', '']) return excel.make_response_from_array(table, file_name='Test Grades {} {}-{}.xlsx' .format(test.name, test.module_part.module_edition.year, test.module_part.module_edition.block), file_type='xlsx') def make_grade(student: Person, corrector: Person, test: Test, grade, description: str = ''): """ Helper function that makes Grade objects so they can be inserted in bulk with def:save_grades. :param student: Person object of the student. :param corrector: Person object of the corrector. :param test: Test object. :param grade: A float that is the grade. :param description: An optional description. :return: A grade object, or None (:param grade is empty). """ interpreted_grade = 0 if grade == '': return # Field is empty, assume it does not need to be imported. try: interpreted_grade = float(grade) except (ValueError, TypeError): if test.type == 'A': interpreted_grade = 1 else: raise GradeException('\'{}\' is not a valid input for a grade (found at {}\'s grade for {}.)' .format(grade, student.name, test)) # Probably a typo, give an error. if test.minimum_grade > interpreted_grade or interpreted_grade > test.maximum_grade: raise GradeException( 'Cannot register {}\'s ({}) grade for test {} because it\'s grade ({}) is outside the defined bounds ' '({}-{}).'.format(student.name, student.university_number, test.name, grade, test.minimum_grade, test.maximum_grade)) # try: grade_obj = Grade( student=student, teacher=corrector, test=test, grade=interpreted_grade, time=timezone.now(), description=description ) # except Exception as e: # raise GradeException(e) return grade_obj def save_grades(grades): """ Helper function that saves all grades to the database. :param grades: List of Grade objects, which may contain None values. These are ignored. :return: Nothing. :raises: GradeException if a grade object is malformed. No grades are saved when this happens. """ try: Grade.objects.bulk_create([grade for grade in grades if grade is not None]) except Exception as e: raise GradeException('Error when saving grades to te database.' + str(e)) @login_required def workbook_student_to_module(request, pk): """ Creates an excel sheet that may be filled in to register students to a module. This sheet is compatible with def:import_student_to_module. :param request: Django request :param pk: Test ID :return: A file response containing an .xlsx file. """ # Check if user is a module coordinator. module_edition = get_object_or_404(ModuleEdition, pk=pk) person = Person.objects.filter(user=request.user).first() if not is_coordinator_or_assistant_of_module(person, module_edition): raise PermissionDenied('You are not the module coordinator for this course.') # Insert column titles table = [['university_number', 'name', 'email', 'role']] return excel.make_response_from_array(table, file_name='Module import Sheet.xlsx', file_type='xlsx') @login_required @require_http_methods(["GET", "POST"]) @transaction.atomic def import_student_to_module(request, pk): """ Take .xlsx file, as produced by def:export_student_import_format and retrieve all students and metainformation from it. Case 1 - Known User - Add the user to the active module edition with the right study and role by making a new Studying object Case 2 - Unknown User - Add the student to the database by making a new Person object and proceed like Case 1 Case 3 - Already Added User - Ignore row The function returns a view in which all newly added users, all users that are now added to the module edition and all users that were already in the module are shown. :param request: Django request :param pk: The module edition id :return: /students-module-imported.html redirect in which all fails, successes and addeds are given :raises: Permission denied if the user is not the Module Coordinator :raises: SuspiciousOperation in case of faulty file input """ # Check if user is a module coordinator. module_edition = get_object_or_404(ModuleEdition, pk=pk) person = Person.objects.filter(user=request.user).first() if not is_coordinator_or_assistant_of_module(person, module_edition): raise PermissionDenied('Not allowed to upload students to module.') if request.method == "POST": student_form = ImportStudentForm(request.POST, request.FILES) if student_form.is_valid(): file = request.FILES['file'] dict = file.get_book_dict() # Select first page students_to_module = dict[list(dict.keys())[0]] key_rows = {} emailpattern = re.compile('e[-]?mail*') for i in range(0,len(students_to_module[0])): if 'number' in students_to_module[0][i].lower(): key_rows['number'] = i elif 'name' in students_to_module[0][i].lower(): key_rows['name'] = i elif emailpattern.match(students_to_module[0][i].lower()): key_rows['email'] = i elif 'role' in students_to_module[0][i].lower(): key_rows['role'] = i # Check dimensions if not (len(students_to_module) > 1 and len(key_rows) == 4): return bad_request(request, {'message': 'Not all required columns [university_number, name, email, ' 'role] are in the excel sheet, or no rows to import.'}) context = {'created': [], 'studying': [], 'failed': []} for i in range(1, len(students_to_module)): # Sanitize number input try: if str(students_to_module[i][key_rows['number']])[0] == 's' and int(students_to_module[i][key_rows['number']][1:]) > 0: username = str(students_to_module[i][key_rows['number']]) elif str(students_to_module[i][key_rows['number']])[0] == 'm' and int(students_to_module[i][key_rows['number']][1:]) > 0: return HttpResponseBadRequest('Trying to add an employee as a student to a module.') elif int(students_to_module[i][key_rows['number']]) > 0: username = 's{}'.format(str(students_to_module[i][key_rows['number']])) else: raise ValueError except ValueError: return bad_request(request, {'message': '{} is not a student number.' .format(students_to_module[i][key_rows['number']])}) user, created = User.objects.get_or_create( username=username, defaults={ 'email': students_to_module[i][key_rows['email']] } ) student, created = Person.objects.get_or_create( university_number=username, defaults={ 'user': user, 'name': students_to_module[i][key_rows['name']], 'email': students_to_module[i][key_rows['email']], } ) # Update name and email student.name = students_to_module[i][key_rows['name']] student.email = students_to_module[i][key_rows['email']] student.save() if created: context['created'].append([student.name, student.full_id]) studying, created = Studying.objects.get_or_create( person=student, module_edition=ModuleEdition.objects.get(pk=pk), defaults={ 'role': students_to_module[i][key_rows['role']], } ) if created: module_ed = ModuleEdition.objects.get(id=studying.module_edition.pk) module = Module.objects.get(moduleedition=module_ed) context['studying'].append( [student.name, student.full_id, module.name, module_ed.code]) # studying.study]) else: module_ed = ModuleEdition.objects.get(id=studying.module_edition.pk) module = Module.objects.get(moduleedition=module_ed) context['failed'].append( [student.name, student.full_id, module.name, module_ed.code]) # studying.study]) context['studying'].append( [student.name, student.full_id, module.name, module_ed.code]) # studying.study]) return render(request, 'importer/students-module-imported.html', context={'context': context}) else: raise SuspiciousOperation('Bad POST') else: # if Module_ed.objects.filter(pk=pk): student_form = ImportStudentModule() return render(request, 'importer/import-module-student.html', {'form': student_form, 'pk': pk, 'module_edition': ModuleEdition.objects.get(pk=pk)}) class SuccessfullyImportedView(LoginRequiredMixin, TemplateView): """Show a message that summarizes the imported data and warns of extra steps to be taken """ template_name = 'importer/successfully_imported.html' tests = [] class ModuleStructureImporter(LoginRequiredMixin, View): """Import to bulk-create Module parts and Tests for a module. """ @transaction.atomic def export_module_structure(request, pk): """ Returns an excel sheet which can be used to upload the module structure. :param request: Django request :param pk: Module edition primary key :return: Excel worksheet as response. """ # Check if user is a module coordinator. module_edition = get_object_or_404(ModuleEdition, pk=pk) person = Person.objects.filter(user=request.user).first() if not is_coordinator_or_assistant_of_module(person, module_edition): raise PermissionDenied('You are not the module coordinator for this course.') # Insert column titles table = [ ['Module part:', '<<example>>', '', '(Duplicate this page for each module part)'], ['Test:', '<<example test>>', '<<example signoff>>', ''], ['Min. grade', '1', '0', ''], ['Max. grade', '10', '1', ''] ] return excel.make_response_from_array(table, file_name='Module Structure {}.xlsx'.format(module_edition), file_type='xlsx')
50.567202
172
0.567109
from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied, SuspiciousOperation from django.db import transaction from django.db.utils import IntegrityError from django.http.response import HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponse, \ Http404 from django.shortcuts import render, redirect, get_object_or_404 from django.utils.decorators import method_decorator from django.views import generic, View from django.utils import timezone from django.db.models import Q import django_excel as excel from django.views.decorators.http import require_http_methods, require_GET from django.views.generic import TemplateView, FormView from permission_utils import * from dashboard.views import bad_request import re from Grades.exceptions import GradeException from Grades.models import ModuleEdition, Grade, Test, Person, ModulePart, Studying, Module, Study from importer.forms import GradeUploadForm, TestGradeUploadForm, ImportStudentForm, ImportStudentModule, \ ImportModuleEditionStructureForm, COLUMN_TITLE_ROW, ImportModuleForm # Create your views here. class ImporterIndexView(LoginRequiredMixin, View): """Index view of the importer module. Serves both Module Coordinators and Teachers. Module coordinators are presented with an overview of the module editions they are a coordinator of, for which they can perform administrative actions. They can add students to a module edition, and download and upload a form that contains grades for the tests which are in the module. This can be done for the whole module, or per test individually. Teachers receive a list of module parts that are a teacher of, with their tests. They can, like module coordinators, download and upload an excel sheet that contains grades. This can be done per test individually. """ model = ModuleEdition def get(self, request, *args, **kwargs): context = dict() # context['is_module_coordinator'] = False # context['is_teacher'] = False coordinator_or_teacher = False if ModuleEdition.objects.filter(coordinators__user=self.request.user): # context['is_module_coordinator'] = True context['module_editions_list'] = self.make_modules_context() coordinator_or_teacher = True if ModulePart.objects.filter(teacher__person__user=self.request.user): # context['is_teacher'] = True context['module_parts_list'] = self.make_module_parts_context() coordinator_or_teacher = True if not coordinator_or_teacher: raise PermissionDenied('Only module coordinators or teachers can view this page.') return render(request, 'importer/mcindex2.html', context) def make_modules_context(self): module_editions = ModuleEdition.objects.filter(coordinator__person__user=self.request.user).prefetch_related( 'modulepart_set__test_set') context = dict() context['module_editions'] = [] for module_edition in module_editions: edition = {'name': module_edition, 'pk': module_edition.pk, 'module_parts': []} for module_part in module_edition.modulepart_set.all(): part = {'name': module_part.name, 'pk': module_part.pk, 'tests': []} sign_off_assignments = [] for test in module_part.test_set.all(): if test.type is 'A': sign_off_assignments.append(test) continue test_item = {'name': test.name, 'pk': test.pk, 'signoff': False} part['tests'].append(test_item) if sign_off_assignments: soa_line = {'module_part_pk': module_part.pk, 'signoff': True} if len(sign_off_assignments) > 1: soa_line['name'] = 'S/O assignments {} to {}'.format(sign_off_assignments[0].name, sign_off_assignments[-1].name) else: soa_line['name'] = 'S/O assignment {}'.format(sign_off_assignments[0].name) part['tests'].append(soa_line) edition['module_parts'].append(part) context['module_editions'].append(edition) return context def make_module_parts_context(self): module_parts = ModulePart.objects.filter(teacher__person__user=self.request.user).prefetch_related( 'test_set') context = dict() context['module_parts'] = [] for module_part in module_parts: part = {'name': module_part.name, 'pk': module_part.pk, 'module_edition': module_part.module_edition, 'tests': []} sign_off_assignments = [] for test in module_part.test_set.all(): if test.type is 'A': sign_off_assignments.append(test) continue test_item = {'name': test.name, 'pk': test.pk, 'signoff': False} part['tests'].append(test_item) if sign_off_assignments: soa_line = {'module_part_pk': module_part.pk, 'signoff': True} if len(sign_off_assignments) > 1: soa_line['name'] = 'S/O assignments {} to {}'.format(sign_off_assignments[0].name, sign_off_assignments[-1].name) else: soa_line['name'] = 'S/O assignment {}'.format(sign_off_assignments[0].name) part['tests'].append(soa_line) context['module_parts'].append(part) return context class ImportModuleView(LoginRequiredMixin, FormView): template_name = 'importer/importmoduleclass.html' form_class = ImportModuleForm def get(self, request, *args, **kwargs): self.module_edition = get_object_or_404(ModuleEdition, pk=kwargs['pk']) if not is_coordinator_or_assistant_of_module( Person.objects.filter(user=self.request.user).first(), self.module_edition): raise PermissionDenied("You are not the module coordinator of this module.") return render(request, self.template_name, self.get_context_data()) def get_context_data(self, **kwargs): return {'pk': self.kwargs['pk'], 'form': self.get_form(ImportModuleForm)} # # def dispatch(self, request, *args, **kwargs): # self.module_edition = get_object_or_404(ModuleEdition, pk=kwargs['pk']) # if is_coordinator_or_assistant_of_module( # Person.objects.filter(user=self.request.user).first(), # self.module_edition): # return super(ImportModuleView, self).dispatch(request, *args, **kwargs) # else: # raise PermissionDenied("You are not the module coordinator of this module.") @transaction.atomic def form_valid(self, form): self.module_edition = get_object_or_404(ModuleEdition, pk=self.kwargs['pk']) if not is_coordinator_or_assistant_of_module( Person.objects.filter(user=self.request.user).first(), self.module_edition): raise PermissionDenied("You are not the module coordinator of this module.") title_row = form.cleaned_data.get('title_row') - 1 # List of all tests that are imported. imported_tests = [] sheet = form.files['file'].get_book_dict() all_tests = dict() if not any([len(table) > title_row for table in sheet]): return bad_request(self.request, { 'message': 'The file that was uploaded was not recognised as a grade ' 'excel file. Are you sure the file is an .xlsx file, and ' 'that all fields are present? Otherwise, download a new ' 'gradesheet and try using that instead.'}) for table in sheet: # Skip tables in sheet that are too small if title_row >= len(sheet[table]): continue tests = dict() university_number_field = None # Detect university_number and test columns for title_index in range(0, len(sheet[table][title_row])): # This is the university number column if ('number' in str(sheet[table][title_row][title_index]).lower()) or \ ('nummer' in str(sheet[table][title_row][title_index]).lower()): university_number_field = title_index else: # Attempt to find a Test # search by ID try: test = Test.objects.filter( pk=sheet[table][title_row][title_index], module_part__module_edition=self.module_edition).first() if test: tests[test] = { 'index':title_index, 'test': test, 'description': -1 } # pk of Test except (ValueError, TypeError): # search by name name = sheet[table][title_row][title_index] if name.lower().endswith("_description"): # 12 characters test = Test.objects.filter(name=name[:-12]).filter(module_part__module_edition=self.module_edition).first() if test: if test in tests: tests[test]['description'] = title_index else: tests[test] = { 'index': -1, 'test': test, 'description': title_index } # Else we have a description field without a test..? else: test = Test.objects.filter(name=sheet[table][title_row][title_index]).filter(module_part__module_edition=self.module_edition).first() if test: if test in tests: tests[test]['index'] = title_index else: tests[test] = { 'index': title_index, 'test': test, 'description': -1 } # Else not a test, continue... if university_number_field is None: # No student number column continue # Ignore this sheet if len(tests.keys()) == 0: # No tests continue # Ignore this sheet # Check if there are descriptions that have no grade associated tests_without_index = [test for test in tests if tests[test]['index'] == -1] if len(tests_without_index) > 0: raise bad_request(self.request, {'message': 'The following tests have a descriotion field in the sheet, but not a grade:\n {}'.format(tests_without_index)}) # The current user's Person is the corrector of the grades. teacher = Person.objects.filter(user=self.request.user).first() grades = [] # Check excel file for invalid students invalid_students = [] for row in sheet[table][(title_row + 1):]: if not Studying.objects.filter(person__university_number__contains=row[university_number_field]).filter( module_edition=self.module_edition): invalid_students.append(row[university_number_field]) # Check for invalid student numbers in the university_number column, but ignore empty fields. if [student for student in invalid_students if student is not '']: return bad_request(self.request, {'message': 'Students {} are not enrolled in this module.\n ' 'Enroll these students first before retrying' .format(invalid_students)}) # Make Grades for row in sheet[table][(title_row + 1):]: # Walk horizontally over table student = Person.objects.filter(university_number__contains=row[university_number_field]).first() # check if this is not an empty line, else continue. if student: for test in tests.keys(): try: if tests[test]['description'] > 0: grades.append(make_grade( student=student, corrector=teacher, test=test, grade=row[tests[test]['index']], description=row[tests[test]['description']] )) else: grades.append(make_grade( student=student, corrector=teacher, test=test, grade=row[tests[test]['index']] )) except GradeException as e: # Called for either: bad grade, grade out of bounds return HttpResponseBadRequest(e) save_grades(grades) # Bulk-save grades. Also prevents a partial import of the sheet. all_tests.update(tests) any_tests = len(all_tests.keys()) > 0 # Check if anything was imported. if not any_tests: return bad_request(self.request, {'message': 'There were no tests recognized to import.'}) return render(request=self.request, template_name='importer/successfully_imported.html', context={'tests': [(key, all_tests[key]['description'] >= 0) for key in all_tests]}) def form_invalid(self, form): return bad_request(self.request, {'message': 'The file that was uploaded was not recognised as a grade excel ' 'file. Are you sure the file is an .xlsx file? Otherwise, download ' 'a new gradesheet and try using that instead.'}) @login_required @require_http_methods(["GET", "POST"]) @transaction.atomic def import_module(request, pk): """Module import. Use an .xlsx file to submit grades to a module edition On GET the user is presented with a file upload form. On POST, the submitted .xlsx file is processed by the system, registering Grade object for each grade in the excel file. It dynamically detects the tests that are submitted (by exact name match or database ID), and omits extra columns silently. Also, lines that do not have a filled in student number are ignored. Students that are not declared as part of the module (def:import_student_to_module) raise an import error. :param request: Django request :param pk: Module that grades should be submitted to :return: A redirect to the Grades module's module view on success. Otherwise a 404 (module does not exist), 403 (no permissions) or 400 (bad excel file or other import error) """ person = Person.objects.filter(user=request.user).first() module_edition = get_object_or_404(ModuleEdition, pk=pk) if not is_coordinator_or_assistant_of_module(person, module_edition): raise PermissionDenied('You are not the module coordinator for this course') if request.method == "POST": form = GradeUploadForm(request.POST, request.FILES) if form.is_valid(): title_row = form.cleaned_data.get('title_row') - 1 # Check if /any/ tests and/or grades are imported. any_tests = False # List of all tests that are imported. all_tests = [] sheet = request.FILES['file'].get_book_dict() for table in sheet: # Check if the sheet has enough rows if title_row >= len(sheet[table]) : return bad_request(request, {'message': 'The file that was uploaded was not recognised as a grade ' 'excel file. Are you sure the file is an .xlsx file, and ' 'that all fields are present? Otherwise, download a new ' 'gradesheet and try using that instead.'}) test_rows = dict() university_number_field = None # Detect university_number and test columns for title_index in range(0, len(sheet[table][title_row])): # This is the university number column if ('number' in str(sheet[table][title_row][title_index]).lower()) or \ ('nummer' in str(sheet[table][title_row][title_index]).lower()): university_number_field = title_index else: # Attempt to find a Test # search by ID try: test = Test.objects.filter( pk=sheet[table][title_row][title_index]) if test and test.filter(module_part__module_edition=module_edition): test_rows[title_index] = sheet[table][title_row][title_index] # pk of Test any_tests = True except (ValueError, TypeError): # search by name if Test.objects.filter( name=sheet[table][title_row][title_index] ).filter(module_part__module_edition=pk): test_rows[title_index] = Test.objects.filter( name=sheet[table][title_row][title_index] ).filter(module_part__module_edition=pk)[0].pk # pk of Test any_tests = True # Else not a test, continue... if university_number_field is None: continue # Ignore this sheet if len(test_rows.keys()) == 0: continue # Ignore this sheet # The current user's Person is the corrector of the grades. teacher = Person.objects.filter(user=request.user).first() grades = [] # Retrieve Test object beforehand to validate permissions on tests and speed up Grade creation tests = dict() test_prefetch = Test.objects.prefetch_related('module_part__module_edition__module') for test_column in test_rows.keys(): tests[test_column] = test_prefetch.get(pk=test_rows[test_column]) [all_tests.append(test) for test in tests.values() if test] # Check excel file for invalid students invalid_students = [] for row in sheet[table][(title_row + 1):]: if not Studying.objects.filter(person__university_number__contains=row[university_number_field]).filter( module_edition=pk): invalid_students.append(row[university_number_field]) # Check for invalid student numbers in the university_number column, but ignore empty fields. if [student for student in invalid_students if student is not '']: return bad_request(request, {'message': 'Students {} are not enrolled in this module. ' 'Enroll these students first before retrying.' .format(invalid_students)}) # Make Grades for row in sheet[table][(title_row + 1):]: # Walk horizontally over table student = Person.objects.filter(university_number__contains=row[university_number_field]).first() # check if this is not an empty line, else continue. if student: for test_column in test_rows.keys(): try: grades.append(make_grade( student=student, corrector=teacher, test=tests[test_column], grade=row[test_column] )) except GradeException as e: # Called for either: bad grade, grade out of bounds return HttpResponseBadRequest(e) save_grades(grades) # Bulk-save grades. Also prevents a partial import of the sheet. # Check if anything was imported. if not any_tests: return bad_request(request, {'message': 'There were no tests recognized to import.'}) return render(request=request, template_name='importer/successfully_imported.html', context={'tests': all_tests}) else: return bad_request(request, {'message': 'The file that was uploaded was not recognised as a grade excel ' 'file. Are you sure the file is an .xlsx file? Otherwise, download ' 'a new gradesheet and try using that instead.'}) else: # GET request form = GradeUploadForm() return render(request, 'importer/importmodule.html', {'form': form, 'pk': pk}) @login_required @require_http_methods(["GET", "POST"]) @transaction.atomic def import_module_part(request, pk): """Module part import. Use an .xlsx file to submit grades to a module part On GET the user is presented with a file upload form. On POST, the submitted .xlsx file is processed by the system, registering Grade object for each grade in the excel file. It dynamically detects the tests that are submitted (by exact name match or database ID), and omits extra columns silently. Also, lines that do not have a filled in student number are ignored. Students that are not declared as part of the module (def:import_student_to_module) raise an import error. :param request: Django request :param pk: Module part that grades should be submitted to :return: A redirect to the Grades course view on success. Otherwise a 404 (module does not exist), 403 (no permissions) or 400 (bad excel file or other import error) """ module_part = get_object_or_404(ModulePart, pk=pk) module_edition = get_object_or_404(ModuleEdition, modulepart=module_part) person = Person.objects.filter(user=request.user).filter( Q(coordinator__module_edition__modulepart=module_part) | Q(teacher__module_part=module_part) ).first() if not ModuleEdition.objects.filter(modulepart=module_part): raise Http404('Module does not exist.') if not (is_coordinator_or_assistant_of_module(person, module_edition) or is_coordinator_or_teacher_of_module_part(person, module_part)): raise PermissionDenied('You are not allowed to do this.') if request.method == "POST": form = GradeUploadForm(request.POST, request.FILES) if form.is_valid(): title_row = form.cleaned_data.get('title_row') - 1 # Check if /any/ tests and/or grades are imported. any_tests = False # List of all tests that are imported. all_tests = [] sheet = request.FILES['file'].get_book_dict() for table in sheet: # Check if the sheet has enough rows if title_row >= len(sheet[table]): return bad_request(request, {'message': 'The file that was uploaded was not recognised as a grade' ' excel file. Are you sure the file is an .xlsx file, and' ' that all fields are present? Otherwise, download a new' ' gradesheet and try using that instead.'}) test_rows = dict() university_number_field = None # Detect university_number and test columns for title_index in range(0, len(sheet[table][title_row])): # This is the university number column if ('number' in str(sheet[table][title_row][title_index]).lower()) or \ ('nummer' in str(sheet[table][title_row][title_index]).lower()): university_number_field = title_index else: # Attempt to find a Test # search by ID try: test = Test.objects.filter( pk=sheet[table][title_row][title_index]) if test and test.filter(module_part=module_part): test_rows[title_index] = sheet[table][title_row][title_index] # pk of Test any_tests = True except (ValueError, TypeError): pass # Not an int. # search by name if Test.objects.filter(module_part=module_part).filter( name=sheet[table][title_row][title_index]): test_rows[title_index] = Test.objects.filter( name=sheet[table][title_row][title_index] ).filter(module_part=module_part)[0].pk # pk of Test any_tests = True # Attempt to ignore test altogether. else: pass if university_number_field is None: continue # Ignore this sheet if len(test_rows.keys()) == 0: continue # Ignore this sheet # The current user's Person is the corrector of the grades. teacher = Person.objects.filter(user=request.user).first() grades = [] # Retrieve Test object beforehand to validate permissions on tests and speed up Grade creation tests = dict() for test_column in test_rows.keys(): tests[test_column] = Test.objects.get(pk=test_rows[test_column]) [all_tests.append(test) for test in tests.values() if test] # Check excel file for invalid students invalid_students = [] for row in sheet[table][(title_row + 1):]: if not Studying.objects.filter(person__university_number__contains=row[university_number_field]).filter( module_edition=module_edition): invalid_students.append(row[university_number_field]) # Check for invalid student numbers in the university_number column, but ignore empty fields. if [student for student in invalid_students if student is not '']: return bad_request(request, {'message': 'Students {} are not enrolled in this module.\n ' 'Enroll these students first before retrying' .format(invalid_students)}) # Make Grades for row in sheet[table][(title_row + 1):]: # Walk horizontally over table student = Person.objects.filter(university_number__contains=row[university_number_field]).first() # check if this is not an empty line, else continue. if student: for test_column in test_rows.keys(): try: grades.append(make_grade( student=student, corrector=teacher, test=tests[test_column], grade=row[test_column] )) except GradeException as e: # Called for either: bad grade, grade out of bounds return bad_request(request, {'message': e}) save_grades(grades) # Bulk-save grades. Also prevents a partial import of the sheet. # Check if anything was imported. if not any_tests: return bad_request(request, {'message': 'There were no tests recognized to import.'}) return render(request=request, template_name='importer/successfully_imported.html', context={'tests': all_tests}) else: return bad_request(request, {'message': 'The file uploaded was not recognised as a grade excel file.' ' Are you sure the file is an .xlsx file? Otherwise, download a new' ' gradesheet and try using that instead'}) else: # GET request form = GradeUploadForm() return render(request, 'importer/importmodulepart.html', {'form': form, 'pk': pk, 'module_part': module_part}) @login_required @require_http_methods(["GET", "POST"]) @transaction.atomic def import_test(request, pk): """ Test import. Use an .xlsx file to submit grades to a test On GET the user is presented with a file upload form. On POST, the submitted .xlsx file is processed by the system, registering Grade object for each grade in the excel file. Lines that do not have a filled in student number are ignored. Students that are not declared as part of the module (def:import_student_to_module) the test is in raise an import error. :param request: Django request :param pk: Test that grades should be submitted to :return: A redirect to the Grades module's Test view on success. Otherwise a 404 (module does not exist), 403 (no permissions) or 400 (bad excel file or other import error) """ # Check if user is either the module coordinator or teacher of this test. test = get_object_or_404(Test, pk=pk) person = Person.objects.filter(user=request.user).first() if not is_coordinator_or_teacher_of_test(person, test): raise PermissionDenied('You are not a module coordinator or teacher of this test. Please refer to the' 'module coordinator of this test if you think this is in error.') if request.method == "POST": form = TestGradeUploadForm(request.POST, request.FILES) if form.is_valid(): title_row = form.cleaned_data.get('title_row') - 1 sheet = request.FILES['file'].get_book_dict() for table in sheet: # Check dimensions if not len(sheet[table]) > title_row and len(sheet[table][0]) == 3: return bad_request(request, {'message': 'The file that was uploaded was not recognised as a grade ' 'excel file. Are you sure all columns are present? ' 'Otherwise, download a new gradesheet and try using that ' 'instead.'}) # Identify columns try: student_id_field = sheet[table][title_row].index('university_number') grade_field = sheet[table][title_row].index('grade') description_field = sheet[table][title_row].index('description') except ValueError: return bad_request(request, {'message': 'One of the required field [student_id, grade, description]' ' could not be found.'}) # The current user's Person is the corrector of the grades. teacher = Person.objects.filter(user=request.user).first() # Check excel file for invalid students invalid_students = [] for row in sheet[table][(title_row + 1):]: if not Studying.objects.filter(person__university_number=row[0]).filter( module_edition=test.module_part.module_edition_id): invalid_students.append(row[0]) # Check for invalid student numbers in the university_number column, but ignore empty fields. if [student for student in invalid_students if student is not '']: return bad_request(request, {'message': 'Students {} are not enrolled in this module. ' 'Enroll these students first before retrying.' .format(invalid_students)}) elif invalid_students: return bad_request(request, {'message': 'There are grades or description fields in this excel sheet' ' that do not have a student number filled in. Please' ' check the contents of your excel file for stale values' ' in rows.'}) grades = [] for row in sheet[table][(title_row + 1):]: try: student = Person.objects.get(university_number=row[student_id_field]) # check if this is not an empty line, else continue. if student: grades.append(make_grade( student=student, corrector=teacher, test=test, grade=row[grade_field], description=row[description_field] )) except GradeException as e: # Called for either: bad grade, grade out of bounds return bad_request(request, {'message': e}) save_grades(grades) # Bulk-save grades. Also prevents a partial import of the sheet. return redirect('grades:test', pk) else: return bad_request(request, {'message': 'Bad POST'}) else: if Test.objects.filter(pk=pk): form = TestGradeUploadForm() return render(request, 'importer/importtest.html', {'test': Test.objects.get(pk=pk), 'form': form, 'pk': pk}) else: return bad_request(request, {'message', 'Test does not exists'}) @login_required() @require_http_methods(["GET"]) def export_module(request, pk): """ Creates an excel sheet that contains all tests against all students in the module. This sheet is compatible with def:import_module. :param request: Django request :param pk: Module ID :return: A file response containing an .xlsx file. """ module_edition = get_object_or_404(ModuleEdition, pk=pk) person = Person.objects.filter(user=request.user).first() # Check if user is a module coordinator. if not is_coordinator_or_assistant_of_module(person, module_edition): raise PermissionDenied('You are not the module coordinator for this course.') students = Person.objects.filter(studying__module_edition=module_edition).values('university_number', 'name') tests = Test.objects.filter(module_part__module_edition=module_edition) # Pre-fill first few columns. table = [ ['Module:', str(module_edition)]+['' for _ in range(len(tests))], ] + [['' for _ in range(len(tests) + 2)] for _ in range(COLUMN_TITLE_ROW - 4)] # Add the module part name and test name for each test if there is enough header room. if COLUMN_TITLE_ROW > 2: table.append(['', 'Module part >'] + [test.module_part.name for test in tests]) if COLUMN_TITLE_ROW > 1: table.append(['', 'Test name >'] + [test.name for test in tests]) if COLUMN_TITLE_ROW > 0: table.append(['', 'Grade between >'] + ['{} - {}'.format(test.minimum_grade, test.maximum_grade) for test in tests]) # Add machine-readable header row. table.append(['university_number', 'name'] + [test.name for test in tests]) # pre-fill student numbers for student in students: table.append([student['university_number'], student['name']] + [None for _ in range(len(tests))]) return excel.make_response_from_array(table, file_name='Module Grades {} {}-{}.xlsx'.format(module_edition.module.name, module_edition.year, module_edition.block), file_type='xlsx') @login_required() @require_http_methods(["GET"]) def export_module_part(request, pk): """ Creates an excel sheet that contains all tests that are in a course. Used mainly to download sign off excel sheets. :param request: Django request :param pk: Module part ID :return: A file response containing an .xlsx file. """ module_part = get_object_or_404(ModulePart, pk=pk) module_edition = ModuleEdition.objects.get(modulepart=module_part) person = Person.objects.filter(user=request.user).first() # Check if user is a module coordinator. if not is_coordinator_or_teacher_of_module_part(person, module_part): raise PermissionDenied('You are not the module coordinator for this course.') students = Person.objects.filter(studying__module_edition=module_edition).values('university_number', 'name') tests = Test.objects.filter(module_part=module_part).values('pk', 'name', 'minimum_grade', 'maximum_grade') # Pre-fill first few columns. table = [['' for _ in range(len(tests) + 2)] for _ in range(COLUMN_TITLE_ROW - 2)] # Add the module part name and test name for each test if there is enough header room. if COLUMN_TITLE_ROW > 1: table.append(['', 'Test name >'] + [test['name'] for test in tests]) if COLUMN_TITLE_ROW > 0: table.append(['', 'Grade between >'] + ['{} - {}'.format(test['minimum_grade'], test['maximum_grade']) for test in tests]) # Add machine-readable header row. table.append(['university_number', 'name'] + [test['name'] for test in tests]) # pre-fill student numbers for student in students: table.append([student['university_number'], student['name']] + [None for _ in range(len(tests))]) return excel.make_response_from_array(table, file_name='Sign-off sheet {} {}-{}.xlsx'.format(module_edition.module.name, module_edition.year, module_edition.block), file_type='xlsx') @login_required() @require_http_methods(["GET"]) def export_module_part_signoff(request, pk): """ Creates an excel sheet that contains all tests that are in a course. Used mainly to download sign off excel sheets. :param request: Django request :param pk: Module part ID :return: A file response containing an .xlsx file. """ module_part = get_object_or_404(ModulePart, pk=pk) module_edition = ModuleEdition.objects.get(modulepart=module_part) person = Person.objects.filter(user=request.user).first() # Check if user is a module coordinator. if not is_coordinator_or_teacher_of_module_part(person, module_part): raise PermissionDenied('You are not the module coordinator for this course.') students = Person.objects.filter(studying__module_edition=module_edition).values('university_number', 'name') tests = Test.objects.filter(module_part=module_part, type='A').values('pk', 'name', 'minimum_grade', 'maximum_grade') # Pre-fill first few columns. table = [['' for _ in range(len(tests) + 2)] for _ in range(COLUMN_TITLE_ROW - 2)] # Add the module part name and test name for each test if there is enough header room. if COLUMN_TITLE_ROW > 1: table.append(['', 'Test name >'] + [test['name'] for test in tests]) if COLUMN_TITLE_ROW > 0: table.append(['', 'Grade between >'] + ['{} - {}'.format(test['minimum_grade'], test['maximum_grade']) for test in tests]) # Add machine-readable header row. table.append(['university_number', 'name'] + [test['name'] for test in tests]) # pre-fill student numbers for student in students: table.append([student['university_number'], student['name']] + [None for _ in range(len(tests))]) return excel.make_response_from_array(table, file_name='Sign-off sheet {} {}-{}.xlsx'.format(module_edition.module.name, module_edition.year, module_edition.block), file_type='xlsx') @login_required() @require_http_methods(["GET"]) def export_test(request, pk): """ Creates an excel sheet that contains all students that may take the test. This sheet is compatible with def:import_test. It contains a description row, which can be used to submit feedback through. :param request: Django request :param pk: Test ID :return: A file response containing an .xlsx file. """ test = get_object_or_404(Test, pk=pk) person = Person.objects.filter(user=request.user).first() # Check if user is either the module coordinator or teacher of this test. if not is_coordinator_or_teacher_of_test(person, test): raise PermissionDenied('Not allowed to export test.') students = Person.objects.filter(studying__module_edition__modulepart=test.module_part).values('university_number', 'name') # Insert padding table = [ [test.name, "", "grade between:", '{} - {}'.format(test.minimum_grade, test.maximum_grade)] ] + [['', '', '', ''] for _ in range(COLUMN_TITLE_ROW - 1)] # Insert title row table.append(['university_number', 'name', 'grade', 'description']) # Insert student numbers for student in students: table.append([student['university_number'], student['name'], '', '']) return excel.make_response_from_array(table, file_name='Test Grades {} {}-{}.xlsx' .format(test.name, test.module_part.module_edition.year, test.module_part.module_edition.block), file_type='xlsx') def make_grade(student: Person, corrector: Person, test: Test, grade, description: str = ''): """ Helper function that makes Grade objects so they can be inserted in bulk with def:save_grades. :param student: Person object of the student. :param corrector: Person object of the corrector. :param test: Test object. :param grade: A float that is the grade. :param description: An optional description. :return: A grade object, or None (:param grade is empty). """ interpreted_grade = 0 if grade == '': return # Field is empty, assume it does not need to be imported. try: interpreted_grade = float(grade) except (ValueError, TypeError): if test.type == 'A': interpreted_grade = 1 else: raise GradeException('\'{}\' is not a valid input for a grade (found at {}\'s grade for {}.)' .format(grade, student.name, test)) # Probably a typo, give an error. if test.minimum_grade > interpreted_grade or interpreted_grade > test.maximum_grade: raise GradeException( 'Cannot register {}\'s ({}) grade for test {} because it\'s grade ({}) is outside the defined bounds ' '({}-{}).'.format(student.name, student.university_number, test.name, grade, test.minimum_grade, test.maximum_grade)) # try: grade_obj = Grade( student=student, teacher=corrector, test=test, grade=interpreted_grade, time=timezone.now(), description=description ) # except Exception as e: # raise GradeException(e) return grade_obj def save_grades(grades): """ Helper function that saves all grades to the database. :param grades: List of Grade objects, which may contain None values. These are ignored. :return: Nothing. :raises: GradeException if a grade object is malformed. No grades are saved when this happens. """ try: Grade.objects.bulk_create([grade for grade in grades if grade is not None]) except Exception as e: raise GradeException('Error when saving grades to te database.' + str(e)) @login_required def workbook_student_to_module(request, pk): """ Creates an excel sheet that may be filled in to register students to a module. This sheet is compatible with def:import_student_to_module. :param request: Django request :param pk: Test ID :return: A file response containing an .xlsx file. """ # Check if user is a module coordinator. module_edition = get_object_or_404(ModuleEdition, pk=pk) person = Person.objects.filter(user=request.user).first() if not is_coordinator_or_assistant_of_module(person, module_edition): raise PermissionDenied('You are not the module coordinator for this course.') # Insert column titles table = [['university_number', 'name', 'email', 'role']] return excel.make_response_from_array(table, file_name='Module import Sheet.xlsx', file_type='xlsx') @login_required @require_http_methods(["GET", "POST"]) @transaction.atomic def import_student_to_module(request, pk): """ Take .xlsx file, as produced by def:export_student_import_format and retrieve all students and metainformation from it. Case 1 - Known User - Add the user to the active module edition with the right study and role by making a new Studying object Case 2 - Unknown User - Add the student to the database by making a new Person object and proceed like Case 1 Case 3 - Already Added User - Ignore row The function returns a view in which all newly added users, all users that are now added to the module edition and all users that were already in the module are shown. :param request: Django request :param pk: The module edition id :return: /students-module-imported.html redirect in which all fails, successes and addeds are given :raises: Permission denied if the user is not the Module Coordinator :raises: SuspiciousOperation in case of faulty file input """ # Check if user is a module coordinator. module_edition = get_object_or_404(ModuleEdition, pk=pk) person = Person.objects.filter(user=request.user).first() if not is_coordinator_or_assistant_of_module(person, module_edition): raise PermissionDenied('Not allowed to upload students to module.') if request.method == "POST": student_form = ImportStudentForm(request.POST, request.FILES) if student_form.is_valid(): file = request.FILES['file'] dict = file.get_book_dict() # Select first page students_to_module = dict[list(dict.keys())[0]] key_rows = {} emailpattern = re.compile('e[-]?mail*') for i in range(0,len(students_to_module[0])): if 'number' in students_to_module[0][i].lower(): key_rows['number'] = i elif 'name' in students_to_module[0][i].lower(): key_rows['name'] = i elif emailpattern.match(students_to_module[0][i].lower()): key_rows['email'] = i elif 'role' in students_to_module[0][i].lower(): key_rows['role'] = i # Check dimensions if not (len(students_to_module) > 1 and len(key_rows) == 4): return bad_request(request, {'message': 'Not all required columns [university_number, name, email, ' 'role] are in the excel sheet, or no rows to import.'}) context = {'created': [], 'studying': [], 'failed': []} for i in range(1, len(students_to_module)): # Sanitize number input try: if str(students_to_module[i][key_rows['number']])[0] == 's' and int(students_to_module[i][key_rows['number']][1:]) > 0: username = str(students_to_module[i][key_rows['number']]) elif str(students_to_module[i][key_rows['number']])[0] == 'm' and int(students_to_module[i][key_rows['number']][1:]) > 0: return HttpResponseBadRequest('Trying to add an employee as a student to a module.') elif int(students_to_module[i][key_rows['number']]) > 0: username = 's{}'.format(str(students_to_module[i][key_rows['number']])) else: raise ValueError except ValueError: return bad_request(request, {'message': '{} is not a student number.' .format(students_to_module[i][key_rows['number']])}) user, created = User.objects.get_or_create( username=username, defaults={ 'email': students_to_module[i][key_rows['email']] } ) student, created = Person.objects.get_or_create( university_number=username, defaults={ 'user': user, 'name': students_to_module[i][key_rows['name']], 'email': students_to_module[i][key_rows['email']], } ) # Update name and email student.name = students_to_module[i][key_rows['name']] student.email = students_to_module[i][key_rows['email']] student.save() if created: context['created'].append([student.name, student.full_id]) studying, created = Studying.objects.get_or_create( person=student, module_edition=ModuleEdition.objects.get(pk=pk), defaults={ 'role': students_to_module[i][key_rows['role']], } ) if created: module_ed = ModuleEdition.objects.get(id=studying.module_edition.pk) module = Module.objects.get(moduleedition=module_ed) context['studying'].append( [student.name, student.full_id, module.name, module_ed.code]) # studying.study]) else: module_ed = ModuleEdition.objects.get(id=studying.module_edition.pk) module = Module.objects.get(moduleedition=module_ed) context['failed'].append( [student.name, student.full_id, module.name, module_ed.code]) # studying.study]) context['studying'].append( [student.name, student.full_id, module.name, module_ed.code]) # studying.study]) return render(request, 'importer/students-module-imported.html', context={'context': context}) else: raise SuspiciousOperation('Bad POST') else: # if Module_ed.objects.filter(pk=pk): student_form = ImportStudentModule() return render(request, 'importer/import-module-student.html', {'form': student_form, 'pk': pk, 'module_edition': ModuleEdition.objects.get(pk=pk)}) class SuccessfullyImportedView(LoginRequiredMixin, TemplateView): """Show a message that summarizes the imported data and warns of extra steps to be taken """ template_name = 'importer/successfully_imported.html' tests = [] def __init__(self, tests): self.tests = tests super().__init__() def get_context_data(self, **kwargs): context = super().get_context_data() context['tests'] = self.tests return context class ModuleStructureImporter(LoginRequiredMixin, View): """Import to bulk-create Module parts and Tests for a module. """ def dispatch(self, request, *args, **kwargs): module_edition = get_object_or_404(ModuleEdition, pk=kwargs['pk']) if is_coordinator_or_assistant_of_module(Person.objects.filter(user=self.request.user).first(), module_edition): return super(ModuleStructureImporter, self).dispatch(request, *args, **kwargs) else: raise PermissionDenied("You are not the module coordinator of this module.") def get(self, request, pk): module_structure_form = ImportModuleEditionStructureForm() return render(request, 'importer/import-module-structure.html', {'form': module_structure_form, 'pk': pk, 'module_edition': ModuleEdition.objects.get(pk=pk)}) @transaction.atomic def post(self, request, pk): module_edition = get_object_or_404(ModuleEdition, pk=pk) tests_in_sheet = [] module_parts_in_sheet = [] # Collect module parts and tests that cannot be deleted, because they contain Grades. old_tests = [] old_module_parts = [] student_form = ImportModuleEditionStructureForm(request.POST, request.FILES) if student_form.is_valid(): try: with transaction.atomic(): file = request.FILES['file'] workbook = file.get_book_dict() structure = dict() for page in workbook.keys(): module_part, mp_created = ModulePart.objects.get_or_create(name=workbook[page][0][1], module_edition=module_edition) module_parts_in_sheet.append(module_part.pk) for i in range(1, len(workbook[page][0])): try: min_grade = float(workbook[page][2][i]) max_grade = float(workbook[page][3][i]) if min_grade == 0 and max_grade == 1: test_type = 'A' else: test_type = 'E' test, test_created = Test.objects.get_or_create(name=workbook[page][1][i], module_part=module_part, defaults={'type': test_type, 'minimum_grade': min_grade, 'maximum_grade': max_grade}) test.type = test_type test.minimum_grade = min_grade test.maximum_grade = max_grade test.save() tests_in_sheet.append(test.pk) except ValueError as e: # If the either the minimum_grade or maximum_grade is not defined, it's not a test at # all. continue for test in Test.objects.filter(module_part__module_edition=module_edition).exclude( pk__in=tests_in_sheet): if not Grade.objects.filter(test=test): test.delete() else: old_tests.append(test) for module_part in ModulePart.objects.filter(module_edition=module_edition).exclude( pk__in=module_parts_in_sheet): if not Grade.objects.filter(test__module_part=module_part): module_part.delete() else: old_module_parts.append(module_part) if len(old_tests) > 0 or len(old_module_parts) > 0: raise IntegrityError("Some modules that should be removed have grades.") except IntegrityError: return render(request, 'importer/module_structure_import_error.html', context={'old_tests': old_tests, 'old_module_parts': old_module_parts}) else: return bad_request(request, {'message': 'Bad POST'}) return redirect('module_management:module_edition_detail', pk) def export_module_structure(request, pk): """ Returns an excel sheet which can be used to upload the module structure. :param request: Django request :param pk: Module edition primary key :return: Excel worksheet as response. """ # Check if user is a module coordinator. module_edition = get_object_or_404(ModuleEdition, pk=pk) person = Person.objects.filter(user=request.user).first() if not is_coordinator_or_assistant_of_module(person, module_edition): raise PermissionDenied('You are not the module coordinator for this course.') # Insert column titles table = [ ['Module part:', '<<example>>', '', '(Duplicate this page for each module part)'], ['Test:', '<<example test>>', '<<example signoff>>', ''], ['Min. grade', '1', '0', ''], ['Max. grade', '10', '1', ''] ] return excel.make_response_from_array(table, file_name='Module Structure {}.xlsx'.format(module_edition), file_type='xlsx')
16,534
750
238
ac15b3969bc4796063311a9d060ccadf45c21a9b
2,923
py
Python
lsp.py
blguweb/radiarDetection
81cb694c17c6ef8736f30ad691f7da82cc83ea4c
[ "MIT" ]
null
null
null
lsp.py
blguweb/radiarDetection
81cb694c17c6ef8736f30ad691f7da82cc83ea4c
[ "MIT" ]
null
null
null
lsp.py
blguweb/radiarDetection
81cb694c17c6ef8736f30ad691f7da82cc83ea4c
[ "MIT" ]
null
null
null
#coding=utf-8 import os import math #from tqdm import tqdm def lsp(x,y,th,mv_red_th,mv_green_th):#x与y为五人机绝对坐标系,后二者为mv返回大致角度值(为绝对坐标系中y轴方向顺时针转动角度) ''' ''' times=30#雷达扫描次数 num_data_line=600#雷达数据行数 data_ls = [[round(0.6 * x,2),0] for x in range(num_data_line)]#创建存储雷达数据的数组 error_range = 6#mv角度数据误差(度) mv_red_th //= 0.6 mv_green_th //= 0.6 mv_red_th = int(mv_red_th) #取整 mv_green_th = int(mv_green_th) #取整 #for i in tqdm(range(times)):#多次扫描 for i in range(times):#多次扫描 #执行雷达扫视代码 os.system("./simple_grabber /dev/ttyUSB0") with open("data.txt", "r") as f: for line in f.readlines(): angle_dis = line.strip('\n').split(" ") #去掉列表中每一个元素的换行符,以空格作为分割符号,分割角度和距离 #雷达数据下标 j = int(float(angle_dis[0]) // 0.6) #print(j) dis = dis2int(angle_dis[1]) if dis != 0: if ((x + dis * math.sin(math.radians(float(angle_dis[0])))) < 4300) & ((x + dis * math.sin(math.radians(float(angle_dis[0])))) > 0): if ((y + dis * math.cos(math.radians(float(angle_dis[0])))) < 3250) & ((y + dis * math.cos(math.radians(float(angle_dis[0])))) > 0): data_ls[j][1]=dis #更新数据 #angle_dis = deal_ls_data(angle_dis,data_ls[j]) #处理角度和距离数据 j += 1 for i in range(num_data_line): if data_ls[i][1] != 0: print(i," ",data_ls[i]) #print("len",len(data_ls)) mpr = [] mpg = [] f = 0. a = 0. b = 0. print("mv",mv_red_th) for i in range(1,11): if data_ls[mv_red_th - 6 + i][1] != 0: mpr.append(data_ls[mv_red_th - 6 + i]) print("mpr",mpr) f += 1 for i in range(1,int(f)+1): a += mpr[i - 1][0] b += mpr[i - 1][1] print("f",f) if f!=0:decision_red = [a / f,b / f] else : decision_red = [0,0] print("de",decision_red) f = 0. a = 0. b = 0. print("mv",mv_green_th) for i in range(1,11): if data_ls[mv_green_th - 6 + i][1] != 0: mpg.append(data_ls[mv_green_th - 6 + i]) print("mpg",mpg) f += 1 for i in range(1,int(f)+1): a += mpg[i - 1][0] b += mpg[i - 1][1] print("f",f) if f!=0:decision_green = [a / f,b / f] else: decision_green = [0,0] return (x + decision_red[1] * math.sin(math.radians(decision_red[0]))),(y + decision_red[1] * math.cos(math.radians(decision_red[0]))),(x + decision_green[1] * math.sin(math.radians(decision_green[0]))),(y + decision_green[1] * math.cos(math.radians(decision_green[0]))) print("result:",lsp(0,0,45,90))
30.447917
274
0.517961
#coding=utf-8 import os import math #from tqdm import tqdm def dis2int(dis): #将距离从字符串转换成整形 int_dis=0 for i in range(5): int_dis += int(int(dis[i])*math.pow(10, 4 - i)) return int_dis def lsp(x,y,th,mv_red_th,mv_green_th):#x与y为五人机绝对坐标系,后二者为mv返回大致角度值(为绝对坐标系中y轴方向顺时针转动角度) ''' ''' times=30#雷达扫描次数 num_data_line=600#雷达数据行数 data_ls = [[round(0.6 * x,2),0] for x in range(num_data_line)]#创建存储雷达数据的数组 error_range = 6#mv角度数据误差(度) mv_red_th //= 0.6 mv_green_th //= 0.6 mv_red_th = int(mv_red_th) #取整 mv_green_th = int(mv_green_th) #取整 #for i in tqdm(range(times)):#多次扫描 for i in range(times):#多次扫描 #执行雷达扫视代码 os.system("./simple_grabber /dev/ttyUSB0") with open("data.txt", "r") as f: for line in f.readlines(): angle_dis = line.strip('\n').split(" ") #去掉列表中每一个元素的换行符,以空格作为分割符号,分割角度和距离 #雷达数据下标 j = int(float(angle_dis[0]) // 0.6) #print(j) dis = dis2int(angle_dis[1]) if dis != 0: if ((x + dis * math.sin(math.radians(float(angle_dis[0])))) < 4300) & ((x + dis * math.sin(math.radians(float(angle_dis[0])))) > 0): if ((y + dis * math.cos(math.radians(float(angle_dis[0])))) < 3250) & ((y + dis * math.cos(math.radians(float(angle_dis[0])))) > 0): data_ls[j][1]=dis #更新数据 #angle_dis = deal_ls_data(angle_dis,data_ls[j]) #处理角度和距离数据 j += 1 for i in range(num_data_line): if data_ls[i][1] != 0: print(i," ",data_ls[i]) #print("len",len(data_ls)) mpr = [] mpg = [] f = 0. a = 0. b = 0. print("mv",mv_red_th) for i in range(1,11): if data_ls[mv_red_th - 6 + i][1] != 0: mpr.append(data_ls[mv_red_th - 6 + i]) print("mpr",mpr) f += 1 for i in range(1,int(f)+1): a += mpr[i - 1][0] b += mpr[i - 1][1] print("f",f) if f!=0:decision_red = [a / f,b / f] else : decision_red = [0,0] print("de",decision_red) f = 0. a = 0. b = 0. print("mv",mv_green_th) for i in range(1,11): if data_ls[mv_green_th - 6 + i][1] != 0: mpg.append(data_ls[mv_green_th - 6 + i]) print("mpg",mpg) f += 1 for i in range(1,int(f)+1): a += mpg[i - 1][0] b += mpg[i - 1][1] print("f",f) if f!=0:decision_green = [a / f,b / f] else: decision_green = [0,0] return (x + decision_red[1] * math.sin(math.radians(decision_red[0]))),(y + decision_red[1] * math.cos(math.radians(decision_red[0]))),(x + decision_green[1] * math.sin(math.radians(decision_green[0]))),(y + decision_green[1] * math.cos(math.radians(decision_green[0]))) print("result:",lsp(0,0,45,90))
155
0
23
e0b3ce02e06b9dc10e756ee437b6ab424249cddb
6,365
py
Python
basicsr/inference_test.py
ZhangAoCanada/HINet
6c03a65f70a494186a9fed02ce91cdf8deab105a
[ "MIT" ]
null
null
null
basicsr/inference_test.py
ZhangAoCanada/HINet
6c03a65f70a494186a9fed02ce91cdf8deab105a
[ "MIT" ]
null
null
null
basicsr/inference_test.py
ZhangAoCanada/HINet
6c03a65f70a494186a9fed02ce91cdf8deab105a
[ "MIT" ]
null
null
null
# ------------------------------------------------------------------------ # Copyright (c) 2021 megvii-model. All Rights Reserved. # ------------------------------------------------------------------------ # Modified from BasicSR (https://github.com/xinntao/BasicSR) # Copyright 2018-2020 BasicSR Authors # ------------------------------------------------------------------------ import sys sys.path.append("/content/drive/MyDrive/DERAIN/HINet") import importlib import logging from unittest import TestLoader import torch from os import path as osp from basicsr.data import create_dataloader, create_dataset from basicsr.models import create_model from basicsr.train import parse_options from basicsr.utils import (get_env_info, get_root_logger, get_time_str, make_exp_dirs) from basicsr.utils.options import dict2str from basicsr.utils import get_root_logger, imwrite, tensor2img from tqdm import tqdm from copy import deepcopy import time, cv2 from skimage.measure import compare_psnr, compare_ssim import numpy as np # ----------------- from TransWeather ------------------ # ------------------------------------------------------ if __name__ == '__main__': main()
35.758427
135
0.571092
# ------------------------------------------------------------------------ # Copyright (c) 2021 megvii-model. All Rights Reserved. # ------------------------------------------------------------------------ # Modified from BasicSR (https://github.com/xinntao/BasicSR) # Copyright 2018-2020 BasicSR Authors # ------------------------------------------------------------------------ import sys sys.path.append("/content/drive/MyDrive/DERAIN/HINet") import importlib import logging from unittest import TestLoader import torch from os import path as osp from basicsr.data import create_dataloader, create_dataset from basicsr.models import create_model from basicsr.train import parse_options from basicsr.utils import (get_env_info, get_root_logger, get_time_str, make_exp_dirs) from basicsr.utils.options import dict2str from basicsr.utils import get_root_logger, imwrite, tensor2img from tqdm import tqdm from copy import deepcopy import time, cv2 from skimage.measure import compare_psnr, compare_ssim import numpy as np # ----------------- from TransWeather ------------------ def calc_psnr(im1, im2): im1_y = cv2.cvtColor(im1, cv2.COLOR_BGR2YCR_CB)[:, :, 0] im2_y = cv2.cvtColor(im2, cv2.COLOR_BGR2YCR_CB)[:, :, 0] ans = [compare_psnr(im1_y, im2_y)] return ans def calc_ssim(im1, im2): im1_y = cv2.cvtColor(im1, cv2.COLOR_BGR2YCR_CB)[:, :, 0] im2_y = cv2.cvtColor(im2, cv2.COLOR_BGR2YCR_CB)[:, :, 0] ans = [compare_ssim(im1_y, im2_y)] return ans # ------------------------------------------------------ def inference(model, dataloader, opt, current_iter, save_img=True, rgb2bgr=True, use_image=True): metric_module = importlib.import_module('basicsr.metrics') dataset_name = dataloader.dataset.opt['name'] with_metrics = opt['val'].get('metrics') is not None if with_metrics: metric_results = { metric: 0 for metric in opt['val']['metrics'].keys() } pbar = tqdm(total=len(dataloader), unit='image') all_inference_time = [] psnr_list = [] ssim_list = [] cnt = 0 for idx, val_data in enumerate(dataloader): img_name = osp.splitext(osp.basename(val_data['lq_path'][0]))[0] start_time = time.time() model.feed_data(val_data) if opt['val'].get('grids', False): model.grids() model.test() if opt['val'].get('grids', False): model.grids_inverse() visuals = model.get_current_visuals() all_inference_time.append(time.time() - start_time) sr_img = tensor2img([visuals['result']], rgb2bgr=rgb2bgr) gt_img = tensor2img([visuals['gt']], rgb2bgr=rgb2bgr) del model.gt del model.lq del model.output torch.cuda.empty_cache() if save_img: if opt['is_train']: save_img_path = osp.join(opt['path']['visualization'], img_name, f'{img_name}_{current_iter}.png') else: save_img_path = osp.join( opt['path']['visualization'], dataset_name, f'{img_name}.png') imwrite(sr_img, save_img_path) # --- Calculate the average PSNR --- # psnr_list.extend(calc_psnr(sr_img, gt_img)) # --- Calculate the average SSIM --- # ssim_list.extend(calc_ssim(sr_img, gt_img)) pbar.update(1) pbar.set_description(f'Test {img_name}') cnt += 1 pbar.close() current_metric = 0. avr_psnr = sum(psnr_list) / (len(psnr_list) + 1e-10) avr_ssim = sum(ssim_list) / (len(ssim_list) + 1e-10) print("[RESULTS] PSNR: {:.4f}, SSIM: {:.4f}, Average time: {:.4f} ms".format(avr_psnr, avr_ssim, np.mean(all_inference_time)*1000)) return current_metric def main(): # parse options, set distributed setting, set ramdom seed opt = parse_options(is_train=False) torch.backends.cudnn.benchmark = True # torch.backends.cudnn.deterministic = True # mkdir and initialize loggers make_exp_dirs(opt) log_file = osp.join(opt['path']['log'], f"test_{opt['name']}_{get_time_str()}.log") logger = get_root_logger( logger_name='basicsr', log_level=logging.INFO, log_file=log_file) logger.info(get_env_info()) logger.info(dict2str(opt)) testset_root_dir = opt['datasets']['test']['dataroot_gt'] subdirs = ['dawn_cloudy', 'night_outdoors', 'sunny_outdoors', 'underground'] input_subs = ['rain_L', 'rain_H'] # create model model = create_model(opt) for subdir in subdirs: for input_sub in input_subs: print("=====> Currently running: ", subdir, " with ", input_sub) opt['datasets']['test']['dataroot_gt'] = osp.join(testset_root_dir, subdir, 'gt') opt['datasets']['test']['dataroot_lq'] = osp.join(testset_root_dir, subdir, input_sub) # create test dataset and dataloader test_loaders = [] for phase, dataset_opt in sorted(opt['datasets'].items()): dataset_opt['io_backend']['type'] = 'disk' test_set = create_dataset(dataset_opt) test_loader = create_dataloader( test_set, dataset_opt, num_gpu=opt['num_gpu'], dist=opt['dist'], sampler=None, seed=opt['manual_seed']) print("[INFO] number of images: {}".format(len(test_loader.dataset))) logger.info( f"Number of test images in {dataset_opt['name']}: {len(test_set)}") test_loaders.append(test_loader) for test_loader in test_loaders: test_set_name = test_loader.dataset.opt['name'] logger.info(f'Testing {test_set_name}...') rgb2bgr = opt['val'].get('rgb2bgr', True) # wheather use uint8 image to compute metrics use_image = opt['val'].get('use_image', True) inference(model, test_loader, opt, opt['name'], save_img=True, rgb2bgr=True, use_image=True) if __name__ == '__main__': main()
5,066
0
91
977a52aceacc4591282f0f56211f48e3f242cb03
194
py
Python
sort_123.py
malai001/codebank
6834107ab683a38a8799102278369a66b1c1b336
[ "bzip2-1.0.6" ]
1
2017-07-11T05:02:12.000Z
2017-07-11T05:02:12.000Z
sort_123.py
malai001/codebank
6834107ab683a38a8799102278369a66b1c1b336
[ "bzip2-1.0.6" ]
null
null
null
sort_123.py
malai001/codebank
6834107ab683a38a8799102278369a66b1c1b336
[ "bzip2-1.0.6" ]
null
null
null
a = [1,2,3,1,2,3] l = 0 m = 0 h = len(a)-1 while(m<=h): if(a[m]==1): a[l],a[m] = a[m],a[l] l+=1 m+=1 elif(a[m]==2): m+=1 else: a[h],a[m] = a[m],a[h] h-=1 print a
12.125
24
0.360825
a = [1,2,3,1,2,3] l = 0 m = 0 h = len(a)-1 while(m<=h): if(a[m]==1): a[l],a[m] = a[m],a[l] l+=1 m+=1 elif(a[m]==2): m+=1 else: a[h],a[m] = a[m],a[h] h-=1 print a
0
0
0
0f527fbcf41be763958ea69825ceb32c790d1718
5,751
py
Python
plaso/analysis/test_lib.py
cvandeplas/plaso
b625a2c267ed09505cfac84c9593d8c0922852b1
[ "Apache-2.0" ]
3
2016-03-11T02:47:08.000Z
2016-12-24T03:19:27.000Z
plaso/analysis/test_lib.py
cvandeplas/plaso
b625a2c267ed09505cfac84c9593d8c0922852b1
[ "Apache-2.0" ]
null
null
null
plaso/analysis/test_lib.py
cvandeplas/plaso
b625a2c267ed09505cfac84c9593d8c0922852b1
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2014 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Analysis plugin related functions and classes for testing.""" import os import unittest from dfvfs.lib import definitions from dfvfs.path import factory as path_spec_factory from dfvfs.resolver import resolver as path_spec_resolver from plaso.analysis import context from plaso.artifacts import knowledge_base from plaso.lib import event from plaso.lib import queue from plaso.parsers import context as parsers_context class TestAnalysisReportQueueConsumer(queue.AnalysisReportQueueConsumer): """Class that implements a test analysis report queue consumer.""" def __init__(self, queue_object): """Initializes the queue consumer. Args: queue_object: the queue object (instance of Queue). """ super(TestAnalysisReportQueueConsumer, self).__init__(queue_object) self.analysis_reports = [] def _ConsumeAnalysisReport(self, analysis_report): """Consumes an analysis report callback for ConsumeAnalysisReports.""" self.analysis_reports.append(analysis_report) @property def number_of_analysis_reports(self): """The number of analysis reports.""" return len(self.analysis_reports) class AnalysisPluginTestCase(unittest.TestCase): """The unit test case for an analysis plugin.""" _TEST_DATA_PATH = os.path.join(os.getcwd(), 'test_data') # Show full diff results, part of TestCase so does not follow our naming # conventions. maxDiff = None def _GetAnalysisReportsFromQueue(self, analysis_report_queue_consumer): """Retrieves the analysis reports from the queue consumer. Args: analysis_report_queue_consumer: the analysis report queue consumer object (instance of TestAnalysisReportQueueConsumer). Returns: A list of analysis reports (instances of AnalysisReport). """ analysis_report_queue_consumer.ConsumeAnalysisReports() analysis_reports = [] for analysis_report in analysis_report_queue_consumer.analysis_reports: self.assertIsInstance(analysis_report, event.AnalysisReport) analysis_reports.append(analysis_report) return analysis_reports def _GetTestFilePath(self, path_segments): """Retrieves the path of a test file relative to the test data directory. Args: path_segments: the path segments inside the test data directory. Returns: A path of the test file. """ # Note that we need to pass the individual path segments to os.path.join # and not a list. return os.path.join(self._TEST_DATA_PATH, *path_segments) def _ParseFile(self, parser_object, path, knowledge_base_object): """Parses a file using the parser object. Args: parser_object: the parser object. path: the path of the file to parse. knowledge_base_object: the knowledge base object (instance of KnowledgeBase). Returns: An event object queue object (instance of Queue). """ event_queue = queue.SingleThreadedQueue() event_queue_producer = queue.EventObjectQueueProducer(event_queue) parse_error_queue = queue.SingleThreadedQueue() parser_context = parsers_context.ParserContext( event_queue_producer, parse_error_queue, knowledge_base_object) path_spec = path_spec_factory.Factory.NewPathSpec( definitions.TYPE_INDICATOR_OS, location=path) file_entry = path_spec_resolver.Resolver.OpenFileEntry(path_spec) parser_object.Parse(parser_context, file_entry) event_queue.SignalEndOfInput() return event_queue def _RunAnalysisPlugin(self, analysis_plugin, knowledge_base_object): """Analyzes an event object queue using the plugin object. Args: analysis_plugin: the analysis plugin object (instance of AnalysisPlugin). knowledge_base_object: the knowledge base object (instance of KnowledgeBase). Returns: An event object queue object (instance of Queue). """ analysis_report_queue = queue.SingleThreadedQueue() analysis_report_queue_consumer = TestAnalysisReportQueueConsumer( analysis_report_queue) analysis_report_queue_producer = queue.AnalysisReportQueueProducer( analysis_report_queue) analysis_context = context.AnalysisContext( analysis_report_queue_producer, knowledge_base_object) analysis_plugin.RunPlugin(analysis_context) analysis_report_queue.SignalEndOfInput() return analysis_report_queue_consumer def _SetUpKnowledgeBase(self, knowledge_base_values=None): """Sets up a knowledge base. Args: knowledge_base_values: optional dict containing the knowledge base values. The default is None. Returns: An knowledge base object (instance of KnowledgeBase). """ knowledge_base_object = knowledge_base.KnowledgeBase() if knowledge_base_values: for identifier, value in knowledge_base_values.iteritems(): knowledge_base_object.SetValue(identifier, value) return knowledge_base_object
34.437126
79
0.738828
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2014 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Analysis plugin related functions and classes for testing.""" import os import unittest from dfvfs.lib import definitions from dfvfs.path import factory as path_spec_factory from dfvfs.resolver import resolver as path_spec_resolver from plaso.analysis import context from plaso.artifacts import knowledge_base from plaso.lib import event from plaso.lib import queue from plaso.parsers import context as parsers_context class TestAnalysisReportQueueConsumer(queue.AnalysisReportQueueConsumer): """Class that implements a test analysis report queue consumer.""" def __init__(self, queue_object): """Initializes the queue consumer. Args: queue_object: the queue object (instance of Queue). """ super(TestAnalysisReportQueueConsumer, self).__init__(queue_object) self.analysis_reports = [] def _ConsumeAnalysisReport(self, analysis_report): """Consumes an analysis report callback for ConsumeAnalysisReports.""" self.analysis_reports.append(analysis_report) @property def number_of_analysis_reports(self): """The number of analysis reports.""" return len(self.analysis_reports) class AnalysisPluginTestCase(unittest.TestCase): """The unit test case for an analysis plugin.""" _TEST_DATA_PATH = os.path.join(os.getcwd(), 'test_data') # Show full diff results, part of TestCase so does not follow our naming # conventions. maxDiff = None def _GetAnalysisReportsFromQueue(self, analysis_report_queue_consumer): """Retrieves the analysis reports from the queue consumer. Args: analysis_report_queue_consumer: the analysis report queue consumer object (instance of TestAnalysisReportQueueConsumer). Returns: A list of analysis reports (instances of AnalysisReport). """ analysis_report_queue_consumer.ConsumeAnalysisReports() analysis_reports = [] for analysis_report in analysis_report_queue_consumer.analysis_reports: self.assertIsInstance(analysis_report, event.AnalysisReport) analysis_reports.append(analysis_report) return analysis_reports def _GetTestFilePath(self, path_segments): """Retrieves the path of a test file relative to the test data directory. Args: path_segments: the path segments inside the test data directory. Returns: A path of the test file. """ # Note that we need to pass the individual path segments to os.path.join # and not a list. return os.path.join(self._TEST_DATA_PATH, *path_segments) def _ParseFile(self, parser_object, path, knowledge_base_object): """Parses a file using the parser object. Args: parser_object: the parser object. path: the path of the file to parse. knowledge_base_object: the knowledge base object (instance of KnowledgeBase). Returns: An event object queue object (instance of Queue). """ event_queue = queue.SingleThreadedQueue() event_queue_producer = queue.EventObjectQueueProducer(event_queue) parse_error_queue = queue.SingleThreadedQueue() parser_context = parsers_context.ParserContext( event_queue_producer, parse_error_queue, knowledge_base_object) path_spec = path_spec_factory.Factory.NewPathSpec( definitions.TYPE_INDICATOR_OS, location=path) file_entry = path_spec_resolver.Resolver.OpenFileEntry(path_spec) parser_object.Parse(parser_context, file_entry) event_queue.SignalEndOfInput() return event_queue def _RunAnalysisPlugin(self, analysis_plugin, knowledge_base_object): """Analyzes an event object queue using the plugin object. Args: analysis_plugin: the analysis plugin object (instance of AnalysisPlugin). knowledge_base_object: the knowledge base object (instance of KnowledgeBase). Returns: An event object queue object (instance of Queue). """ analysis_report_queue = queue.SingleThreadedQueue() analysis_report_queue_consumer = TestAnalysisReportQueueConsumer( analysis_report_queue) analysis_report_queue_producer = queue.AnalysisReportQueueProducer( analysis_report_queue) analysis_context = context.AnalysisContext( analysis_report_queue_producer, knowledge_base_object) analysis_plugin.RunPlugin(analysis_context) analysis_report_queue.SignalEndOfInput() return analysis_report_queue_consumer def _SetUpKnowledgeBase(self, knowledge_base_values=None): """Sets up a knowledge base. Args: knowledge_base_values: optional dict containing the knowledge base values. The default is None. Returns: An knowledge base object (instance of KnowledgeBase). """ knowledge_base_object = knowledge_base.KnowledgeBase() if knowledge_base_values: for identifier, value in knowledge_base_values.iteritems(): knowledge_base_object.SetValue(identifier, value) return knowledge_base_object
0
0
0
ab052d4fcf325877949746f118c6d1847e0459da
6,901
py
Python
tests/conftest.py
danbider/lightning-pose
23dc5f22e4b40fa8b71193322f11fca703fd8ec9
[ "MIT" ]
47
2021-11-03T07:56:50.000Z
2022-03-23T12:22:38.000Z
tests/conftest.py
danbider/lightning-pose
23dc5f22e4b40fa8b71193322f11fca703fd8ec9
[ "MIT" ]
2
2021-10-19T03:45:12.000Z
2022-01-25T22:20:42.000Z
tests/conftest.py
danbider/lightning-pose
23dc5f22e4b40fa8b71193322f11fca703fd8ec9
[ "MIT" ]
6
2021-11-16T23:32:18.000Z
2022-03-17T16:55:39.000Z
"""Provide pytest fixtures for the entire test suite. These fixtures create data and data modules that can be reused by other tests. Their construction relies heavily on the utility functions provided in `utils/scripts.py`. """ import copy import imgaug.augmenters as iaa from omegaconf import ListConfig, OmegaConf import os import pytest import pytorch_lightning as pl import shutil import torch from typing import Callable, List, Optional import yaml from lightning_pose.data.datamodules import BaseDataModule, UnlabeledDataModule from lightning_pose.data.datasets import BaseTrackingDataset, HeatmapDataset from lightning_pose.utils.predictions import get_videos_in_dir from lightning_pose.utils.scripts import ( get_data_module, get_dataset, get_imgaug_transform, ) _TORCH_DEVICE = "cuda" if torch.cuda.is_available() else "cpu" TOY_DATA_ROOT_DIR = "toy_datasets/toymouseRunningData" @pytest.fixture def cfg() -> dict: """Load all toy data config files without hydra.""" base_dir = os.path.dirname(os.path.dirname(os.path.join(__file__))) config_dir = os.path.join(base_dir, "scripts", "configs") keys = ["data", "losses", "model", "training"] cfg = {} for key in keys: cfg_tmp = os.path.join(config_dir, key, "%s_params.yaml" % key) with open(cfg_tmp) as f: dict_tmp = yaml.load(f, Loader=yaml.FullLoader) cfg[key] = dict_tmp return OmegaConf.create(cfg) @pytest.fixture def imgaug_transform(cfg) -> iaa.Sequential: """Create basic resizing transform.""" return get_imgaug_transform(cfg) @pytest.fixture def base_dataset(cfg, imgaug_transform) -> BaseTrackingDataset: """Create a dataset for regression models from toy data.""" # setup cfg_tmp = copy.deepcopy(cfg) cfg_tmp.model.model_type = "regression" base_dataset = get_dataset( cfg_tmp, data_dir=TOY_DATA_ROOT_DIR, imgaug_transform=imgaug_transform ) # return to tests yield base_dataset # cleanup after all tests have run (no more calls to yield) del base_dataset torch.cuda.empty_cache() @pytest.fixture def heatmap_dataset(cfg, imgaug_transform) -> HeatmapDataset: """Create a dataset for heatmap models from toy data.""" # setup cfg_tmp = copy.deepcopy(cfg) cfg_tmp.model.model_type = "heatmap" heatmap_dataset = get_dataset( cfg_tmp, data_dir=TOY_DATA_ROOT_DIR, imgaug_transform=imgaug_transform ) # return to tests yield heatmap_dataset # cleanup after all tests have run (no more calls to yield) del heatmap_dataset torch.cuda.empty_cache() @pytest.fixture def base_data_module(cfg, base_dataset) -> BaseDataModule: """Create a labeled data module for regression models.""" # setup cfg_tmp = copy.deepcopy(cfg) cfg_tmp.model.losses_to_use = [] # bump up training data so we can test pca_singleview loss cfg_tmp.training.train_prob = 0.95 cfg_tmp.training.val_prob = 0.025 data_module = get_data_module(cfg_tmp, dataset=base_dataset, video_dir=None) data_module.setup() # return to tests yield data_module # cleanup after all tests have run (no more calls to yield) del data_module torch.cuda.empty_cache() @pytest.fixture def heatmap_data_module(cfg, heatmap_dataset) -> BaseDataModule: """Create a labeled data module for heatmap models.""" # setup cfg_tmp = copy.deepcopy(cfg) cfg_tmp.model.losses_to_use = [] # bump up training data so we can test pca_singleview loss cfg_tmp.training.train_prob = 0.95 cfg_tmp.training.val_prob = 0.025 data_module = get_data_module(cfg_tmp, dataset=heatmap_dataset, video_dir=None) data_module.setup() # return to tests yield data_module # cleanup after all tests have run (no more calls to yield) del data_module torch.cuda.empty_cache() @pytest.fixture def base_data_module_combined(cfg, base_dataset) -> UnlabeledDataModule: """Create a combined data module for regression models.""" # setup cfg_tmp = copy.deepcopy(cfg) cfg_tmp.model.losses_to_use = ["temporal"] data_module = get_data_module( cfg_tmp, dataset=base_dataset, video_dir=os.path.join(TOY_DATA_ROOT_DIR, "unlabeled_videos") ) # data_module.setup() # already done in UnlabeledDataModule constructor # return to tests yield data_module # cleanup after all tests have run (no more calls to yield) del data_module torch.cuda.empty_cache() @pytest.fixture def heatmap_data_module_combined(cfg, heatmap_dataset) -> UnlabeledDataModule: """Create a combined data module for heatmap models.""" # setup cfg_tmp = copy.deepcopy(cfg) cfg_tmp.model.losses_to_use = ["temporal"] data_module = get_data_module( cfg_tmp, dataset=heatmap_dataset, video_dir=os.path.join(TOY_DATA_ROOT_DIR, "unlabeled_videos") ) # data_module.setup() # already done in UnlabeledDataModule constructor # return to tests yield data_module # cleanup after all tests have run (no more calls to yield) del data_module torch.cuda.empty_cache() @pytest.fixture def trainer(cfg) -> pl.Trainer: """Create a basic pytorch lightning trainer for testing models.""" ckpt_callback = pl.callbacks.model_checkpoint.ModelCheckpoint( monitor="val_supervised_loss" ) transfer_unfreeze_callback = pl.callbacks.BackboneFinetuning( unfreeze_backbone_at_epoch=10, lambda_func=lambda epoch: 1.5, backbone_initial_ratio_lr=0.1, should_align=True, train_bn=True, ) # determine gpu setup if _TORCH_DEVICE == "cpu": gpus = 0 elif isinstance(cfg.training.gpu_id, list): gpus = cfg.training.gpu_id elif isinstance(cfg.training.gpu_id, ListConfig): gpus = list(cfg.training.gpu_id) elif isinstance(cfg.training.gpu_id, int): gpus = [cfg.training.gpu_id] else: raise NotImplementedError( "training.gpu_id must be list or int, not {}".format( type(cfg.training.gpu_id) ) ) trainer = pl.Trainer( gpus=gpus, max_epochs=2, min_epochs=2, check_val_every_n_epoch=1, log_every_n_steps=1, callbacks=[ckpt_callback, transfer_unfreeze_callback], limit_train_batches=2, ) return trainer @pytest.fixture @pytest.fixture @pytest.fixture
28.634855
84
0.705115
"""Provide pytest fixtures for the entire test suite. These fixtures create data and data modules that can be reused by other tests. Their construction relies heavily on the utility functions provided in `utils/scripts.py`. """ import copy import imgaug.augmenters as iaa from omegaconf import ListConfig, OmegaConf import os import pytest import pytorch_lightning as pl import shutil import torch from typing import Callable, List, Optional import yaml from lightning_pose.data.datamodules import BaseDataModule, UnlabeledDataModule from lightning_pose.data.datasets import BaseTrackingDataset, HeatmapDataset from lightning_pose.utils.predictions import get_videos_in_dir from lightning_pose.utils.scripts import ( get_data_module, get_dataset, get_imgaug_transform, ) _TORCH_DEVICE = "cuda" if torch.cuda.is_available() else "cpu" TOY_DATA_ROOT_DIR = "toy_datasets/toymouseRunningData" @pytest.fixture def cfg() -> dict: """Load all toy data config files without hydra.""" base_dir = os.path.dirname(os.path.dirname(os.path.join(__file__))) config_dir = os.path.join(base_dir, "scripts", "configs") keys = ["data", "losses", "model", "training"] cfg = {} for key in keys: cfg_tmp = os.path.join(config_dir, key, "%s_params.yaml" % key) with open(cfg_tmp) as f: dict_tmp = yaml.load(f, Loader=yaml.FullLoader) cfg[key] = dict_tmp return OmegaConf.create(cfg) @pytest.fixture def imgaug_transform(cfg) -> iaa.Sequential: """Create basic resizing transform.""" return get_imgaug_transform(cfg) @pytest.fixture def base_dataset(cfg, imgaug_transform) -> BaseTrackingDataset: """Create a dataset for regression models from toy data.""" # setup cfg_tmp = copy.deepcopy(cfg) cfg_tmp.model.model_type = "regression" base_dataset = get_dataset( cfg_tmp, data_dir=TOY_DATA_ROOT_DIR, imgaug_transform=imgaug_transform ) # return to tests yield base_dataset # cleanup after all tests have run (no more calls to yield) del base_dataset torch.cuda.empty_cache() @pytest.fixture def heatmap_dataset(cfg, imgaug_transform) -> HeatmapDataset: """Create a dataset for heatmap models from toy data.""" # setup cfg_tmp = copy.deepcopy(cfg) cfg_tmp.model.model_type = "heatmap" heatmap_dataset = get_dataset( cfg_tmp, data_dir=TOY_DATA_ROOT_DIR, imgaug_transform=imgaug_transform ) # return to tests yield heatmap_dataset # cleanup after all tests have run (no more calls to yield) del heatmap_dataset torch.cuda.empty_cache() @pytest.fixture def base_data_module(cfg, base_dataset) -> BaseDataModule: """Create a labeled data module for regression models.""" # setup cfg_tmp = copy.deepcopy(cfg) cfg_tmp.model.losses_to_use = [] # bump up training data so we can test pca_singleview loss cfg_tmp.training.train_prob = 0.95 cfg_tmp.training.val_prob = 0.025 data_module = get_data_module(cfg_tmp, dataset=base_dataset, video_dir=None) data_module.setup() # return to tests yield data_module # cleanup after all tests have run (no more calls to yield) del data_module torch.cuda.empty_cache() @pytest.fixture def heatmap_data_module(cfg, heatmap_dataset) -> BaseDataModule: """Create a labeled data module for heatmap models.""" # setup cfg_tmp = copy.deepcopy(cfg) cfg_tmp.model.losses_to_use = [] # bump up training data so we can test pca_singleview loss cfg_tmp.training.train_prob = 0.95 cfg_tmp.training.val_prob = 0.025 data_module = get_data_module(cfg_tmp, dataset=heatmap_dataset, video_dir=None) data_module.setup() # return to tests yield data_module # cleanup after all tests have run (no more calls to yield) del data_module torch.cuda.empty_cache() @pytest.fixture def base_data_module_combined(cfg, base_dataset) -> UnlabeledDataModule: """Create a combined data module for regression models.""" # setup cfg_tmp = copy.deepcopy(cfg) cfg_tmp.model.losses_to_use = ["temporal"] data_module = get_data_module( cfg_tmp, dataset=base_dataset, video_dir=os.path.join(TOY_DATA_ROOT_DIR, "unlabeled_videos") ) # data_module.setup() # already done in UnlabeledDataModule constructor # return to tests yield data_module # cleanup after all tests have run (no more calls to yield) del data_module torch.cuda.empty_cache() @pytest.fixture def heatmap_data_module_combined(cfg, heatmap_dataset) -> UnlabeledDataModule: """Create a combined data module for heatmap models.""" # setup cfg_tmp = copy.deepcopy(cfg) cfg_tmp.model.losses_to_use = ["temporal"] data_module = get_data_module( cfg_tmp, dataset=heatmap_dataset, video_dir=os.path.join(TOY_DATA_ROOT_DIR, "unlabeled_videos") ) # data_module.setup() # already done in UnlabeledDataModule constructor # return to tests yield data_module # cleanup after all tests have run (no more calls to yield) del data_module torch.cuda.empty_cache() @pytest.fixture def trainer(cfg) -> pl.Trainer: """Create a basic pytorch lightning trainer for testing models.""" ckpt_callback = pl.callbacks.model_checkpoint.ModelCheckpoint( monitor="val_supervised_loss" ) transfer_unfreeze_callback = pl.callbacks.BackboneFinetuning( unfreeze_backbone_at_epoch=10, lambda_func=lambda epoch: 1.5, backbone_initial_ratio_lr=0.1, should_align=True, train_bn=True, ) # determine gpu setup if _TORCH_DEVICE == "cpu": gpus = 0 elif isinstance(cfg.training.gpu_id, list): gpus = cfg.training.gpu_id elif isinstance(cfg.training.gpu_id, ListConfig): gpus = list(cfg.training.gpu_id) elif isinstance(cfg.training.gpu_id, int): gpus = [cfg.training.gpu_id] else: raise NotImplementedError( "training.gpu_id must be list or int, not {}".format( type(cfg.training.gpu_id) ) ) trainer = pl.Trainer( gpus=gpus, max_epochs=2, min_epochs=2, check_val_every_n_epoch=1, log_every_n_steps=1, callbacks=[ckpt_callback, transfer_unfreeze_callback], limit_train_batches=2, ) return trainer @pytest.fixture def remove_logs() -> Callable: def _remove_logs(): base_dir = os.path.dirname(os.path.dirname(os.path.join(__file__))) logging_dir = os.path.join(base_dir, "lightning_logs") shutil.rmtree(logging_dir) return _remove_logs @pytest.fixture def video_list() -> List[str]: return get_videos_in_dir(os.path.join(TOY_DATA_ROOT_DIR, "unlabeled_videos")) @pytest.fixture def toy_data_dir() -> str: return TOY_DATA_ROOT_DIR
356
0
66
76164ad7c850bfbf1dd29a68a4e24774dd59e647
30
py
Python
iot_inspector_client/queries/__init__.py
IoT-Inspector/python-client
88a5b4f27e7f95e544a0c62da89cd1f42be0af3f
[ "MIT" ]
3
2021-04-14T20:21:34.000Z
2021-05-19T20:59:03.000Z
iot_inspector_client/queries/__init__.py
IoT-Inspector/python-client
88a5b4f27e7f95e544a0c62da89cd1f42be0af3f
[ "MIT" ]
6
2021-04-20T10:45:30.000Z
2022-01-22T13:02:52.000Z
iot_inspector_client/queries/__init__.py
IoT-Inspector/python-client
88a5b4f27e7f95e544a0c62da89cd1f42be0af3f
[ "MIT" ]
1
2022-01-19T17:48:44.000Z
2022-01-19T17:48:44.000Z
from .utils import load_query
15
29
0.833333
from .utils import load_query
0
0
0
0efa1c8d1416695a1aacbad21331a04b9a79f3f1
6,095
py
Python
tests/test_cosalib_cmdlib.py
shanemcd/coreos-assembler
a295e945bb0f4ba7a998c2440990680157b7e0d9
[ "Apache-2.0" ]
249
2018-09-11T14:43:09.000Z
2022-03-26T05:03:11.000Z
tests/test_cosalib_cmdlib.py
shanemcd/coreos-assembler
a295e945bb0f4ba7a998c2440990680157b7e0d9
[ "Apache-2.0" ]
2,262
2018-08-28T16:56:35.000Z
2022-03-31T22:40:11.000Z
tests/test_cosalib_cmdlib.py
jmarrero/coreos-assembler
3f0b818a54767d17600e1b7b9155b6d7d9534353
[ "Apache-2.0" ]
148
2018-08-29T14:59:19.000Z
2022-03-14T12:57:42.000Z
import datetime import os import platform import pytest import subprocess import sys import uuid sys.path.insert(0, 'src') from cosalib import cmdlib PY_MAJOR, PY_MINOR, PY_PATCH = platform.python_version_tuple() def test_run_verbose(): """ Verify run_verbose returns expected information """ result = cmdlib.run_verbose(['echo', 'hi']) assert result.stdout is None with pytest.raises(FileNotFoundError): cmdlib.run_verbose(['idonotexist']) # If we are not at least on Python 3.7 we must skip the following test if PY_MAJOR == 3 and PY_MINOR >= 7: result = cmdlib.run_verbose(['echo', 'hi'], capture_output=True) assert result.stdout == b'hi\n' def test_write_and_load_json(tmpdir): """ Ensure write_json writes loadable json """ data = { 'test': ['data'], } path = os.path.join(tmpdir, 'data.json') cmdlib.write_json(path, data) # Ensure the file exists assert os.path.isfile(path) # Ensure the data matches assert cmdlib.load_json(path) == data def test_sha256sum_file(tmpdir): """ Verify we get the proper sha256 sum """ test_file = os.path.join(tmpdir, 'testfile') with open(test_file, 'w') as f: f.write('test') # $ sha256sum testfile # 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 e = '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08' shasum = cmdlib.sha256sum_file(test_file) assert shasum == e def test_fatal(capsys): """ Ensure that fatal does indeed attempt to exit """ test_string = str(uuid.uuid4()) err = None with pytest.raises(SystemExit) as err: cmdlib.fatal(test_string) # Check that our test string is in stderr assert test_string in str(err) def test_info(capsys): """ Verify test_info writes properly to stderr without exit """ test_string = str(uuid.uuid4()) cmdlib.info(test_string) captured = capsys.readouterr() assert test_string in captured.err def test_rfc3339_time(): """ Verify the format returned from rfc3339_time """ t = cmdlib.rfc3339_time() assert datetime.datetime.strptime(t, '%Y-%m-%dT%H:%M:%SZ') # now and utcnow don't set TZ's. We should get a raise with pytest.raises(AssertionError): cmdlib.rfc3339_time(datetime.datetime.now()) def test_rm_allow_noent(tmpdir): """ Ensure rm_allow_noent works both with existing and non existing files """ test_path = os.path.join(tmpdir, 'testfile') with open(test_path, 'w') as f: f.write('test') # Exists cmdlib.rm_allow_noent(test_path) # Doesn't exist cmdlib.rm_allow_noent(test_path) def test_import_ostree_commit(monkeypatch, tmpdir): """ Verify the correct ostree/tar commands are executed when import_ostree_commit is called. """ repo_tmp = os.path.join(tmpdir, 'tmp') os.mkdir(repo_tmp) class monkeyspcheck_call: """ Verifies each subprocess.check_call matches what is required. """ check_call_count = 0 def monkeyspcall(*args, **kwargs): """ Verifies suprocess.call matches what we need. """ assert args[0] == ['ostree', 'show', '--repo', tmpdir, 'commit'] # Monkey patch the subprocess function monkeypatch.setattr(subprocess, 'check_call', monkeyspcheck_call()) monkeypatch.setattr(subprocess, 'call', monkeyspcall) build = { 'ostree-commit': 'commit', 'images': { 'ostree': { 'path': 'tarfile.tar' } } } cmdlib.import_ostree_commit(tmpdir, './', build)
26.732456
77
0.59475
import datetime import os import platform import pytest import subprocess import sys import uuid sys.path.insert(0, 'src') from cosalib import cmdlib PY_MAJOR, PY_MINOR, PY_PATCH = platform.python_version_tuple() def test_run_verbose(): """ Verify run_verbose returns expected information """ result = cmdlib.run_verbose(['echo', 'hi']) assert result.stdout is None with pytest.raises(FileNotFoundError): cmdlib.run_verbose(['idonotexist']) # If we are not at least on Python 3.7 we must skip the following test if PY_MAJOR == 3 and PY_MINOR >= 7: result = cmdlib.run_verbose(['echo', 'hi'], capture_output=True) assert result.stdout == b'hi\n' def test_write_and_load_json(tmpdir): """ Ensure write_json writes loadable json """ data = { 'test': ['data'], } path = os.path.join(tmpdir, 'data.json') cmdlib.write_json(path, data) # Ensure the file exists assert os.path.isfile(path) # Ensure the data matches assert cmdlib.load_json(path) == data def test_sha256sum_file(tmpdir): """ Verify we get the proper sha256 sum """ test_file = os.path.join(tmpdir, 'testfile') with open(test_file, 'w') as f: f.write('test') # $ sha256sum testfile # 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 e = '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08' shasum = cmdlib.sha256sum_file(test_file) assert shasum == e def test_fatal(capsys): """ Ensure that fatal does indeed attempt to exit """ test_string = str(uuid.uuid4()) err = None with pytest.raises(SystemExit) as err: cmdlib.fatal(test_string) # Check that our test string is in stderr assert test_string in str(err) def test_info(capsys): """ Verify test_info writes properly to stderr without exit """ test_string = str(uuid.uuid4()) cmdlib.info(test_string) captured = capsys.readouterr() assert test_string in captured.err def test_rfc3339_time(): """ Verify the format returned from rfc3339_time """ t = cmdlib.rfc3339_time() assert datetime.datetime.strptime(t, '%Y-%m-%dT%H:%M:%SZ') # now and utcnow don't set TZ's. We should get a raise with pytest.raises(AssertionError): cmdlib.rfc3339_time(datetime.datetime.now()) def test_rm_allow_noent(tmpdir): """ Ensure rm_allow_noent works both with existing and non existing files """ test_path = os.path.join(tmpdir, 'testfile') with open(test_path, 'w') as f: f.write('test') # Exists cmdlib.rm_allow_noent(test_path) # Doesn't exist cmdlib.rm_allow_noent(test_path) def test_import_ostree_commit(monkeypatch, tmpdir): """ Verify the correct ostree/tar commands are executed when import_ostree_commit is called. """ repo_tmp = os.path.join(tmpdir, 'tmp') os.mkdir(repo_tmp) class monkeyspcheck_call: """ Verifies each subprocess.check_call matches what is required. """ check_call_count = 0 def __call__(self, *args, **kwargs): if self.check_call_count == 0: assert args[0] == [ 'ostree', 'init', '--repo', tmpdir, '--mode=archive'] if self.check_call_count == 1: assert args[0][0:2] == ['tar', '-C'] assert args[0][3:5] == ['-xf', './tarfile.tar'] if self.check_call_count == 2: assert args[0][0:4] == [ 'ostree', 'pull-local', '--repo', tmpdir] assert args[0][5] == 'commit' self.check_call_count += 1 def monkeyspcall(*args, **kwargs): """ Verifies suprocess.call matches what we need. """ assert args[0] == ['ostree', 'show', '--repo', tmpdir, 'commit'] # Monkey patch the subprocess function monkeypatch.setattr(subprocess, 'check_call', monkeyspcheck_call()) monkeypatch.setattr(subprocess, 'call', monkeyspcall) build = { 'ostree-commit': 'commit', 'images': { 'ostree': { 'path': 'tarfile.tar' } } } cmdlib.import_ostree_commit(tmpdir, './', build) def test_image_info(tmpdir): cmdlib.run_verbose([ "qemu-img", "create", "-f", "qcow2", f"{tmpdir}/test.qcow2", "10M"]) assert cmdlib.image_info(f"{tmpdir}/test.qcow2").get('format') == "qcow2" cmdlib.run_verbose([ "qemu-img", "create", "-f", "vpc", '-o', 'force_size,subformat=fixed', f"{tmpdir}/test.vpc", "10M"]) assert cmdlib.image_info(f"{tmpdir}/test.vpc").get('format') == "vpc" def test_merge_dicts(tmpdir): x = { 1: "Nope", 2: ["a", "b", "c"], 3: {"3a": True} } y = {4: True} z = {1: "yup", 3: { "3a": False, "3b": "found" } } # merge y into x m = cmdlib.merge_dicts(x, y) for i in range(1, 4): assert i in m assert y[4] is True # merge z into x m = cmdlib.merge_dicts(x, z) assert m[1] == "Nope" assert x[2] == m[2] assert m[3]["3a"] is True assert m[3]["3b"] == "found" # merge x into z m = cmdlib.merge_dicts(z, x) assert m[1] == "yup" assert x[2] == m[2] assert m[3] == z[3] def test_flatten_image_yaml(tmpdir): fn = f"{tmpdir}/image.yaml" with open(fn, 'w') as f: f.write(""" size: 10 extra-kargs: - foobar unique-key-a: true """) o = cmdlib.flatten_image_yaml(fn) assert o['size'] == 10 assert o['extra-kargs'] == ['foobar'] assert o['unique-key-a'] with open(fn, 'a') as f: f.write("include: image-base.yaml") base_fn = f"{tmpdir}/image-base.yaml" with open(base_fn, 'w') as f: f.write(""" size: 8 extra-kargs: - bazboo unique-key-b: true """) o = cmdlib.flatten_image_yaml(fn) assert o['size'] == 10 assert o['extra-kargs'] == ['foobar', 'bazboo'] assert o['unique-key-a'] assert o['unique-key-b']
2,303
0
100
daea94a3811d4fbda0c97cd4b522850520def761
3,691
py
Python
release/scripts/startup/bl_ui/properties_workspace.py
mmk-code/blender
c8fc23fdbe09c33f5342ed51735dab50fe4f071b
[ "Naumen", "Condor-1.1", "MS-PL" ]
2
2019-03-20T13:10:46.000Z
2019-05-15T20:00:31.000Z
engine/2.80/scripts/startup/bl_ui/properties_workspace.py
byteinc/Phasor
f7d23a489c2b4bcc3c1961ac955926484ff8b8d9
[ "Unlicense" ]
null
null
null
engine/2.80/scripts/startup/bl_ui/properties_workspace.py
byteinc/Phasor
f7d23a489c2b4bcc3c1961ac955926484ff8b8d9
[ "Unlicense" ]
null
null
null
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # <pep8 compliant> import bpy from bpy.types import ( Panel, ) from rna_prop_ui import PropertyPanel classes = ( WORKSPACE_PT_main, WORKSPACE_PT_addons, WORKSPACE_PT_custom_props, ) if __name__ == "__main__": # only for live edit. from bpy.utils import register_class for cls in classes: register_class(cls)
31.547009
77
0.638309
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # <pep8 compliant> import bpy from bpy.types import ( Panel, ) from rna_prop_ui import PropertyPanel class WorkSpaceButtonsPanel: bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = ".workspace" class WORKSPACE_PT_main(WorkSpaceButtonsPanel, Panel): bl_label = "Workspace" bl_options = {'DEFAULT_CLOSED'} def draw(self, context): workspace = context.workspace layout = self.layout layout.use_property_split = True layout.prop(workspace, "object_mode", text="Mode") class WORKSPACE_PT_addons(WorkSpaceButtonsPanel, Panel): bl_label = "Filter Add-ons" bl_parent_id = "WORKSPACE_PT_main" def draw_header(self, context): workspace = context.workspace self.layout.prop(workspace, "use_filter_by_owner", text="") def draw(self, context): layout = self.layout # align just to pack more tightly col = layout.box().column(align=True) workspace = context.workspace prefs = context.preferences col.active = workspace.use_filter_by_owner import addon_utils addon_map = {mod.__name__: mod for mod in addon_utils.modules()} owner_ids = {owner_id.name for owner_id in workspace.owner_ids} for addon in prefs.addons: module_name = addon.module info = addon_utils.module_bl_info(addon_map[module_name]) if not info["use_owner"]: continue is_enabled = module_name in owner_ids row = col.row() row.operator( "wm.owner_disable" if is_enabled else "wm.owner_enable", icon='CHECKBOX_HLT' if is_enabled else 'CHECKBOX_DEHLT', text="", emboss=False, ).owner_id = module_name row.label(text="%s: %s" % (info["category"], info["name"])) if is_enabled: owner_ids.remove(module_name) # Detect unused if owner_ids: layout.label(text="Unknown add-ons", icon='ERROR') col = layout.box().column(align=True) for module_name in sorted(owner_ids): row = col.row() row.operator( "wm.owner_disable", icon='CHECKBOX_HLT', text="", emboss=False, ).owner_id = module_name row.label(text=module_name) class WORKSPACE_PT_custom_props(WorkSpaceButtonsPanel, PropertyPanel, Panel): bl_parent_id = "WORKSPACE_PT_main" _context_path = "workspace" _property_type = bpy.types.WorkSpace classes = ( WORKSPACE_PT_main, WORKSPACE_PT_addons, WORKSPACE_PT_custom_props, ) if __name__ == "__main__": # only for live edit. from bpy.utils import register_class for cls in classes: register_class(cls)
1,903
552
92
468a25b174ed8ac5bf498b1f130bd5cf63f10a97
1,275
py
Python
setup.py
pfrouleau/wce-triage-v2
25610cda55f5cb2170e13e121ae1cbaa92ef7626
[ "MIT" ]
3
2019-07-25T03:24:23.000Z
2021-06-23T14:01:34.000Z
setup.py
pfrouleau/wce-triage-v2
25610cda55f5cb2170e13e121ae1cbaa92ef7626
[ "MIT" ]
1
2019-12-20T16:04:19.000Z
2019-12-20T16:04:19.000Z
setup.py
pfrouleau/wce-triage-v2
25610cda55f5cb2170e13e121ae1cbaa92ef7626
[ "MIT" ]
2
2019-07-25T03:24:26.000Z
2021-02-14T05:27:11.000Z
import setuptools, sys, os with open("README.rst", "r") as fh: long_description = fh.read() # The wce triage is designed to work with Ubuntu 18.04LTS and after # that comes with Python 3.6. python_version = sys.version_info need_python_version = (3, 6) if python_version < need_python_version: raise RuntimeError("wce_triage requires Python version %d.%d or higher" % need_python_version) sys.path.append(os.getcwd()) from wce_triage.version import * setuptools.setup( name="wce_triage", version=TRIAGE_VERSION, author="Naoyuki Tai", author_email="ntai@cleanwinner.com", description="WCE Triage", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/ntai/wce-triage-v2", packages=['wce_triage', 'wce_triage.bin', 'wce_triage.components', 'wce_triage.lib', 'wce_triage.http', 'wce_triage.ops', 'wce_triage.setup', 'test'], include_package_data=True, install_requires=[ 'python-socketio', 'aiohttp', 'aiohttp_cors' ], classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: POSIX :: Linux", ], )
26.5625
73
0.661176
import setuptools, sys, os with open("README.rst", "r") as fh: long_description = fh.read() # The wce triage is designed to work with Ubuntu 18.04LTS and after # that comes with Python 3.6. python_version = sys.version_info need_python_version = (3, 6) if python_version < need_python_version: raise RuntimeError("wce_triage requires Python version %d.%d or higher" % need_python_version) sys.path.append(os.getcwd()) from wce_triage.version import * setuptools.setup( name="wce_triage", version=TRIAGE_VERSION, author="Naoyuki Tai", author_email="ntai@cleanwinner.com", description="WCE Triage", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/ntai/wce-triage-v2", packages=['wce_triage', 'wce_triage.bin', 'wce_triage.components', 'wce_triage.lib', 'wce_triage.http', 'wce_triage.ops', 'wce_triage.setup', 'test'], include_package_data=True, install_requires=[ 'python-socketio', 'aiohttp', 'aiohttp_cors' ], classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: POSIX :: Linux", ], )
0
0
0
189cd7625aaa95f6630ac9cfcded7b39a36c88fe
5,500
py
Python
src/main/python/dev4py/utils/dicts.py
St4rG00se/dev4py-utils
7507bd443cb231b6362e66ff6b161c8d792f39dc
[ "Apache-2.0" ]
null
null
null
src/main/python/dev4py/utils/dicts.py
St4rG00se/dev4py-utils
7507bd443cb231b6362e66ff6b161c8d792f39dc
[ "Apache-2.0" ]
null
null
null
src/main/python/dev4py/utils/dicts.py
St4rG00se/dev4py-utils
7507bd443cb231b6362e66ff6b161c8d792f39dc
[ "Apache-2.0" ]
null
null
null
""" The `dicts` module provides a set of utility functions to simplify dict operations """ # Copyright 2022 the original author or authors (i.e.: St4rG00se for Dev4py). # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from functools import partial from typing import Optional, Any from dev4py.utils.JOptional import JOptional from dev4py.utils.objects import non_none, require_non_none, to_none from dev4py.utils.types import K, V, Supplier def is_dict(value: Any) -> bool: """ If the given value is a dict, returns true, otherwise false Returns: bool: true if the given value is a dict, otherwise false """ return isinstance(value, dict) def _get_value(dictionary: dict[K, V], key: K) -> Optional[V]: """ private function to replace get_joptional_value lambda Note: lambda are not used in order to be compatible with multiprocessing (lambda are not serializable) """ # lambda d: d.get(key) return dictionary.get(key) def get_joptional_value(dictionary: Optional[dict[K, V]], key: K) -> JOptional[V]: """ Tries to get a value from a dict with the given key and returns a JOptional describing the result Args: dictionary: The dict key: The key Returns: JOptional[V]: An empty JOptional if dictionary is None or the searched key result is None, otherwise a JOptional with a present value """ if non_none(dictionary) and not is_dict(dictionary): raise TypeError("Optional[dict[K, V]] parameter is required") return JOptional \ .of_noneable(dictionary) \ .map(partial(_get_value, key=key)) def get_value( dictionary: Optional[dict[K, V]], key: K, default_supplier: Supplier[Optional[V]] = to_none ) -> Optional[V]: """ Returns the value from a dict with the given key if presents, otherwise returns the result produced by the supplying function Args: dictionary: The dict key: The searched key default_supplier: The supplying function that produces a value to be returned Returns: Optional[V]: The value, if present, otherwise the result produced by the supplying function (even if dictionary is None) """ return get_joptional_value(dictionary, key).or_else_get(default_supplier) def get_value_from_path( dictionary: Optional[dict[K, Any]], path: list[Any], default_supplier: Supplier[Optional[V]] = to_none ) -> Optional[V]: """ Returns the value from a deep dict (dict of dicts) with the given key path if present, otherwise returns the result produced by the supplying function Args: dictionary: The dict path: The searched key path default_supplier: The supplying function that produces a value to be returned Returns: Optional[V]: The value, if present, otherwise the result produced by the supplying function (even if dictionary is None) Raises: TypeError: if dictionary is not None and not a dict """ if non_none(dictionary) and not is_dict(dictionary): raise TypeError("Optional[dict[K, V]] dictionary parameter must be a dict or None value") if not path: return default_supplier() if len(path) == 1: return get_value(dictionary, path[0], default_supplier) current_path_value: Any = get_value(dictionary, path[0]) return get_value_from_path( current_path_value, path[1:], default_supplier ) if is_dict(current_path_value) else default_supplier() def put_value(dictionary: dict[K, V], key: K, value: V) -> Optional[V]: """ Associates the specified value with the specified key in the given map. If the map previously contained a mapping for the key, the old value is returned and replaced by the specified value Args: dictionary: The dict key: The key with which the specified value is to be associated value: The value to be associated with the specified key Returns: Optional[V]: The previous value associated with key, or None if there was no mapping for key. Raises: TypeError: if dictionary is not a dict """ if not is_dict(dictionary): raise TypeError("dictionary must be a dict value") result: Optional[V] = dictionary.get(key) dictionary[key] = value return result def empty_dict() -> dict[Any, Any]: """ Returns an empty dict Returns: dict[Any, Any]: an empty dict """ return {} def update(dict_1: dict[K, V], dict_2: dict[K, V]) -> dict[K, V]: """ Adds all elements of the second dict to the first one and returns it Args: dict_1: The dict where add elements dict_2: The dict with elements to add Returns: dict_1 (dict[K, V]): The first dict with added elements from dict_2 Raises: TypeError: if dict_1 or dict_2 is None """ require_non_none(dict_1).update(require_non_none(dict_2)) return dict_1
32.163743
120
0.687273
""" The `dicts` module provides a set of utility functions to simplify dict operations """ # Copyright 2022 the original author or authors (i.e.: St4rG00se for Dev4py). # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from functools import partial from typing import Optional, Any from dev4py.utils.JOptional import JOptional from dev4py.utils.objects import non_none, require_non_none, to_none from dev4py.utils.types import K, V, Supplier def is_dict(value: Any) -> bool: """ If the given value is a dict, returns true, otherwise false Returns: bool: true if the given value is a dict, otherwise false """ return isinstance(value, dict) def _get_value(dictionary: dict[K, V], key: K) -> Optional[V]: """ private function to replace get_joptional_value lambda Note: lambda are not used in order to be compatible with multiprocessing (lambda are not serializable) """ # lambda d: d.get(key) return dictionary.get(key) def get_joptional_value(dictionary: Optional[dict[K, V]], key: K) -> JOptional[V]: """ Tries to get a value from a dict with the given key and returns a JOptional describing the result Args: dictionary: The dict key: The key Returns: JOptional[V]: An empty JOptional if dictionary is None or the searched key result is None, otherwise a JOptional with a present value """ if non_none(dictionary) and not is_dict(dictionary): raise TypeError("Optional[dict[K, V]] parameter is required") return JOptional \ .of_noneable(dictionary) \ .map(partial(_get_value, key=key)) def get_value( dictionary: Optional[dict[K, V]], key: K, default_supplier: Supplier[Optional[V]] = to_none ) -> Optional[V]: """ Returns the value from a dict with the given key if presents, otherwise returns the result produced by the supplying function Args: dictionary: The dict key: The searched key default_supplier: The supplying function that produces a value to be returned Returns: Optional[V]: The value, if present, otherwise the result produced by the supplying function (even if dictionary is None) """ return get_joptional_value(dictionary, key).or_else_get(default_supplier) def get_value_from_path( dictionary: Optional[dict[K, Any]], path: list[Any], default_supplier: Supplier[Optional[V]] = to_none ) -> Optional[V]: """ Returns the value from a deep dict (dict of dicts) with the given key path if present, otherwise returns the result produced by the supplying function Args: dictionary: The dict path: The searched key path default_supplier: The supplying function that produces a value to be returned Returns: Optional[V]: The value, if present, otherwise the result produced by the supplying function (even if dictionary is None) Raises: TypeError: if dictionary is not None and not a dict """ if non_none(dictionary) and not is_dict(dictionary): raise TypeError("Optional[dict[K, V]] dictionary parameter must be a dict or None value") if not path: return default_supplier() if len(path) == 1: return get_value(dictionary, path[0], default_supplier) current_path_value: Any = get_value(dictionary, path[0]) return get_value_from_path( current_path_value, path[1:], default_supplier ) if is_dict(current_path_value) else default_supplier() def put_value(dictionary: dict[K, V], key: K, value: V) -> Optional[V]: """ Associates the specified value with the specified key in the given map. If the map previously contained a mapping for the key, the old value is returned and replaced by the specified value Args: dictionary: The dict key: The key with which the specified value is to be associated value: The value to be associated with the specified key Returns: Optional[V]: The previous value associated with key, or None if there was no mapping for key. Raises: TypeError: if dictionary is not a dict """ if not is_dict(dictionary): raise TypeError("dictionary must be a dict value") result: Optional[V] = dictionary.get(key) dictionary[key] = value return result def empty_dict() -> dict[Any, Any]: """ Returns an empty dict Returns: dict[Any, Any]: an empty dict """ return {} def update(dict_1: dict[K, V], dict_2: dict[K, V]) -> dict[K, V]: """ Adds all elements of the second dict to the first one and returns it Args: dict_1: The dict where add elements dict_2: The dict with elements to add Returns: dict_1 (dict[K, V]): The first dict with added elements from dict_2 Raises: TypeError: if dict_1 or dict_2 is None """ require_non_none(dict_1).update(require_non_none(dict_2)) return dict_1
0
0
0
60bc56ceec284ddfd7facd879668c71a84410bde
725
py
Python
tutorial/snippets/serializers/UserSerializer.py
sinner/testing-djrf
729312cc55a85a7b6a9b0ed159a29a6d0570d139
[ "MIT" ]
null
null
null
tutorial/snippets/serializers/UserSerializer.py
sinner/testing-djrf
729312cc55a85a7b6a9b0ed159a29a6d0570d139
[ "MIT" ]
null
null
null
tutorial/snippets/serializers/UserSerializer.py
sinner/testing-djrf
729312cc55a85a7b6a9b0ed159a29a6d0570d139
[ "MIT" ]
null
null
null
from rest_framework import serializers from django.contrib.auth.models import User from snippets.models import Contact from snippets.models import Snippet from snippets.serializers import ContactSerializer
34.52381
92
0.736552
from rest_framework import serializers from django.contrib.auth.models import User from snippets.models import Contact from snippets.models import Snippet from snippets.serializers import ContactSerializer class UserSerializer(serializers.ModelSerializer): snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all()) contact = ContactSerializer(many=False) class Meta: model = User fields = ('id', 'username', 'email', 'contact', 'snippets') def create(self, validated_data): contact_data = validated_data.pop('contact') user = User.objects.create(**validated_data) Contact.objects.create(user=user, **contact_data) return user
196
299
23
bf7ba2bf762b26c528325abaa78c23eea1b93956
3,241
py
Python
hskl/classification.py
qiancao/hskl
7a530d3e1cc10f0f85e5a1f3edbdcd91f2c2cc8a
[ "BSD-3-Clause" ]
7
2021-03-01T18:07:49.000Z
2021-09-12T10:22:21.000Z
hskl/classification.py
qiancao/hskl
7a530d3e1cc10f0f85e5a1f3edbdcd91f2c2cc8a
[ "BSD-3-Clause" ]
null
null
null
hskl/classification.py
qiancao/hskl
7a530d3e1cc10f0f85e5a1f3edbdcd91f2c2cc8a
[ "BSD-3-Clause" ]
4
2021-03-25T13:36:54.000Z
2021-05-30T10:25:06.000Z
# -*- coding: utf-8 -*- """ hskl Classification Module Data I/O conventions X: (DimX, DimY, NumSpectralChannels) <np.array> Y: (DimX, DimY) <np.array,dtype=uint8> 0 - ignored 1 - first label 2 - second label ... """ # Author: Qian Cao # License: BSD 3-Clause import numpy as np from sklearn.utils import all_estimators from sklearn.base import BaseEstimator, ClassifierMixin from .base import flatten_with_label, HyperspectralMixin from sklearn.metrics import accuracy_score # TODO: Search for list of models will be moved to models/sklearn _sklearn_methods = dict(all_estimators(type_filter='classifier')) _methods_list = ['AdaBoostClassifier', 'BaggingClassifier', 'BernoulliNB', 'DecisionTreeClassifier','ExtraTreesClassifier', 'GaussianNB','GradientBoostingClassifier', 'KNeighborsClassifier','LinearDiscriminantAnalysis', 'LinearSVC','LogisticRegression','MLPClassifier', 'QuadraticDiscriminantAnalysis','RandomForestClassifier', 'RidgeClassifier','SGDClassifier','SVC'] _parallel_methods = [] _methods = {k:_sklearn_methods[k] for k in _methods_list if k in _sklearn_methods} def list_sklearn_methods(): """List Available Classifier Methods in Scikit-Learn Returns ------- list of classifier names """ return list(_sklearn_methods.keys()) def list_methods(): """List Available Classifier Methods Tested for Hyperspectral-sklearn Returns ------- list of classifier names """ return list(_methods.keys()) class HyperspectralClassifier(BaseEstimator, HyperspectralMixin, ClassifierMixin): """Hyperspectral Classifier Wrapper of classifiers in sklearn Parameters ---------- method_name : str, default='RandomForest' Invokes correponding classification algorithm in scikit-learn. method_param : dict, default={} A parameter used for demonstation of how to pass and store paramters. """ _estimator_type = "classifier" def fit(self, X, Y, sample_fraction=None): """ Fit model to inputs and labels. """ self.est = self._fit(self.est, X, Y, sample_fraction) return self def predict(self, X, Y = None): """ Use model to predict input labels. """ Y = self._predict(self.est, X, Y) return Y def score(self, X, Y): """ Evaluate Classification accuracy Adapted from Classifier Mixin """ sample_weight = None # TODO: Implement sample weighting X, Y = flatten_with_label(X, Y) return super().score(X, Y, sample_weight) if __name__ == "__main__": pass
27.700855
82
0.639309
# -*- coding: utf-8 -*- """ hskl Classification Module Data I/O conventions X: (DimX, DimY, NumSpectralChannels) <np.array> Y: (DimX, DimY) <np.array,dtype=uint8> 0 - ignored 1 - first label 2 - second label ... """ # Author: Qian Cao # License: BSD 3-Clause import numpy as np from sklearn.utils import all_estimators from sklearn.base import BaseEstimator, ClassifierMixin from .base import flatten_with_label, HyperspectralMixin from sklearn.metrics import accuracy_score # TODO: Search for list of models will be moved to models/sklearn _sklearn_methods = dict(all_estimators(type_filter='classifier')) _methods_list = ['AdaBoostClassifier', 'BaggingClassifier', 'BernoulliNB', 'DecisionTreeClassifier','ExtraTreesClassifier', 'GaussianNB','GradientBoostingClassifier', 'KNeighborsClassifier','LinearDiscriminantAnalysis', 'LinearSVC','LogisticRegression','MLPClassifier', 'QuadraticDiscriminantAnalysis','RandomForestClassifier', 'RidgeClassifier','SGDClassifier','SVC'] _parallel_methods = [] _methods = {k:_sklearn_methods[k] for k in _methods_list if k in _sklearn_methods} def list_sklearn_methods(): """List Available Classifier Methods in Scikit-Learn Returns ------- list of classifier names """ return list(_sklearn_methods.keys()) def list_methods(): """List Available Classifier Methods Tested for Hyperspectral-sklearn Returns ------- list of classifier names """ return list(_methods.keys()) class HyperspectralClassifier(BaseEstimator, HyperspectralMixin, ClassifierMixin): """Hyperspectral Classifier Wrapper of classifiers in sklearn Parameters ---------- method_name : str, default='RandomForest' Invokes correponding classification algorithm in scikit-learn. method_param : dict, default={} A parameter used for demonstation of how to pass and store paramters. """ _estimator_type = "classifier" def __init__(self, method_name='RandomForest', method_params={}): self.__dict__.update(method_params) if (method_name in _methods): self.est = _methods[method_name](**method_params) else: raise KeyError(" ".join(["Method ", method_name, " not found. \ Use list_methods() to view available classifiers."])) def fit(self, X, Y, sample_fraction=None): """ Fit model to inputs and labels. """ self.est = self._fit(self.est, X, Y, sample_fraction) return self def predict(self, X, Y = None): """ Use model to predict input labels. """ Y = self._predict(self.est, X, Y) return Y def score(self, X, Y): """ Evaluate Classification accuracy Adapted from Classifier Mixin """ sample_weight = None # TODO: Implement sample weighting X, Y = flatten_with_label(X, Y) return super().score(X, Y, sample_weight) def _more_tags(self): return {'requires_y': True} if __name__ == "__main__": pass
414
0
62
d4c92148b0ac4e28242be712fafb2a11f6a3d5a4
1,106
py
Python
dynts/utils/populate.py
quantmind/dynts
21ac57c648bfec402fa6b1fe569496cf098fb5e8
[ "BSD-3-Clause" ]
57
2015-02-10T13:42:06.000Z
2022-03-28T14:48:36.000Z
dynts/utils/populate.py
quantmind/dynts
21ac57c648bfec402fa6b1fe569496cf098fb5e8
[ "BSD-3-Clause" ]
1
2016-11-01T07:43:05.000Z
2016-11-01T07:43:05.000Z
dynts/utils/populate.py
quantmind/dynts
21ac57c648bfec402fa6b1fe569496cf098fb5e8
[ "BSD-3-Clause" ]
17
2015-05-08T04:09:19.000Z
2021-08-02T19:24:52.000Z
from datetime import date, timedelta from random import uniform from numpy import ndarray def polygen(*coefficients): '''Polynomial generating function''' if not coefficients: return lambda i: 0 else: c0 = coefficients[0] coefficients = coefficients[1:] return _
22.12
64
0.563291
from datetime import date, timedelta from random import uniform from numpy import ndarray def _generator(x): return uniform(0, 1) class gdata(object): def __init__(self, data): self.data = data def __iter__(self): return (v for v in self.data) def datepopulate(size = 10, start=None, delta=1): dt = start or date.today() - timedelta(days=delta*(size-1)) td = timedelta(days=delta) return [dt+s*td for s in range(size)] def populate(size=100, cols=1, generator=None): generator = generator or _generator data = ndarray([size,cols]) for c in range(0, cols): data[:, c] = [generator(i) for i in range(0, size)] return data def polygen(*coefficients): '''Polynomial generating function''' if not coefficients: return lambda i: 0 else: c0 = coefficients[0] coefficients = coefficients[1:] def _(i): v = c0 for c in coefficients: v += c*i i *= i return v return _
582
-1
191
d4bddb57b63ff8699be1cdd5f9d5d69256c5b486
4,376
py
Python
awsm_rank/awsm_rank.py
psacawa/awsm-rank
36a8900c60c75e33973769162ec12b6dd4017dcd
[ "MIT" ]
null
null
null
awsm_rank/awsm_rank.py
psacawa/awsm-rank
36a8900c60c75e33973769162ec12b6dd4017dcd
[ "MIT" ]
null
null
null
awsm_rank/awsm_rank.py
psacawa/awsm-rank
36a8900c60c75e33973769162ec12b6dd4017dcd
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import re import sys import argparse import asyncio import json from os import environ from typing import List from pprint import pprint import logging import subprocess from urllib.parse import urlparse from aiohttp import ClientSession, ClientError import requests from bs4 import BeautifulSoup from tabulate import tabulate logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler(sys.stdout)) forbidden_usernames = ["apps", "site", "topics"] def main(): """Scrape and parse a github page. For all linked github projects, determine the number of stars asynchronously. Order the results by decreasing number of stars. Authentication can be provided by the GITHUB_API_TOKEN environmental variable, or preferentially via the --token argument. If not given, am unauthenticated query will be attempted. """ parser = argparse.ArgumentParser() parser.add_argument("url", type=str) parser.add_argument("--token", type=str) parser.add_argument("--limit", type=int) parser.add_argument("--debug", dest="debug", action="store_true") parser.add_argument("--open", dest="open", action="store_true") args = parser.parse_args() if args.debug: logger.setLevel(logging.DEBUG) token = environ.get("GITHUB_API_TOKEN", None) or args.token logger.debug(f"Using authentication token: {token}") projects = get_linked_projects(args.url) repo_endpoints = get_repo_api_endpoints(projects) ranking = asyncio.run(get_stargazer_counts(repo_endpoints, token=token)) if args.limit: ranking = ranking[: args.limit] if args.open: open_urls(ranking) else: print_ranking(ranking) def open_urls(ranking): """Open the urls in the ranking in firefox. Add option to choose the web browser?""" urls = [item["url"] for item in ranking] firefox_cmd = "firefox".split() + urls logger.debug(f"Executing: {' '.join (firefox_cmd)}") subprocess.run(firefox_cmd) def get_linked_projects(url): """Get github projects linked a given webpage""" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") links = soup.find_all("a") links = [a["href"] for a in links if "href" in a.attrs] links = list (set(links)) pattern = r"^https://github.com/(?P<user>[\w-]+)/(?P<repo>[\w-]+)$" prog = re.compile(pattern).search matches = map(prog, links) repos = list(filter(None, matches)) return repos def get_repo_api_endpoints(projects: List[re.Match]): """ Transform a project URL into an API repo endpoint""" groups = [project.groupdict() for project in projects] return [ f"https://api.github.com/repos/{group['user']}/{group['repo']}" for group in groups if group["user"] not in forbidden_usernames ] async def get_ranking_data(session: ClientSession, repo_url): """Get individual repos data""" logger.debug(f"beginning request to {repo_url}") try: async with session.get(repo_url) as response: logger.debug(f"get response to {repo_url}") data = await response.text() data = json.loads(data) return { "name": data["name"], "owner": data["owner"]["login"], "stargazers": data["stargazers_count"], "url": data["html_url"], } except KeyError as e: logger.error(f"Response malformed at {repo_url} - {data}") except ClientError: logger.error(f"Request failed at {repo_url}") if __name__ == "__main__": main()
33.661538
91
0.675046
#!/usr/bin/env python3 import re import sys import argparse import asyncio import json from os import environ from typing import List from pprint import pprint import logging import subprocess from urllib.parse import urlparse from aiohttp import ClientSession, ClientError import requests from bs4 import BeautifulSoup from tabulate import tabulate logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler(sys.stdout)) forbidden_usernames = ["apps", "site", "topics"] def main(): """Scrape and parse a github page. For all linked github projects, determine the number of stars asynchronously. Order the results by decreasing number of stars. Authentication can be provided by the GITHUB_API_TOKEN environmental variable, or preferentially via the --token argument. If not given, am unauthenticated query will be attempted. """ parser = argparse.ArgumentParser() parser.add_argument("url", type=str) parser.add_argument("--token", type=str) parser.add_argument("--limit", type=int) parser.add_argument("--debug", dest="debug", action="store_true") parser.add_argument("--open", dest="open", action="store_true") args = parser.parse_args() if args.debug: logger.setLevel(logging.DEBUG) token = environ.get("GITHUB_API_TOKEN", None) or args.token logger.debug(f"Using authentication token: {token}") projects = get_linked_projects(args.url) repo_endpoints = get_repo_api_endpoints(projects) ranking = asyncio.run(get_stargazer_counts(repo_endpoints, token=token)) if args.limit: ranking = ranking[: args.limit] if args.open: open_urls(ranking) else: print_ranking(ranking) def print_ranking(ranking): # don't display urls for item in ranking: item.pop("url") print(tabulate(ranking, headers="keys")) def open_urls(ranking): """Open the urls in the ranking in firefox. Add option to choose the web browser?""" urls = [item["url"] for item in ranking] firefox_cmd = "firefox".split() + urls logger.debug(f"Executing: {' '.join (firefox_cmd)}") subprocess.run(firefox_cmd) def get_linked_projects(url): """Get github projects linked a given webpage""" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") links = soup.find_all("a") links = [a["href"] for a in links if "href" in a.attrs] links = list (set(links)) pattern = r"^https://github.com/(?P<user>[\w-]+)/(?P<repo>[\w-]+)$" prog = re.compile(pattern).search matches = map(prog, links) repos = list(filter(None, matches)) return repos def get_repo_api_endpoints(projects: List[re.Match]): """ Transform a project URL into an API repo endpoint""" groups = [project.groupdict() for project in projects] return [ f"https://api.github.com/repos/{group['user']}/{group['repo']}" for group in groups if group["user"] not in forbidden_usernames ] async def get_ranking_data(session: ClientSession, repo_url): """Get individual repos data""" logger.debug(f"beginning request to {repo_url}") try: async with session.get(repo_url) as response: logger.debug(f"get response to {repo_url}") data = await response.text() data = json.loads(data) return { "name": data["name"], "owner": data["owner"]["login"], "stargazers": data["stargazers_count"], "url": data["html_url"], } except KeyError as e: logger.error(f"Response malformed at {repo_url} - {data}") except ClientError: logger.error(f"Request failed at {repo_url}") async def get_stargazer_counts(repos, token=None): auth_header = {"Authorization": f"token {token}"} if token else {} async with ClientSession(headers=auth_header) as session: logger.debug("beginning session") tasks = [get_ranking_data(session, repo) for repo in repos] ranked_repos = await asyncio.gather(*tasks) ranked_repos = [r for r in ranked_repos if r and "stargazers" in r] logger.debug(ranked_repos) ranked_repos = sorted(ranked_repos, key=lambda x: x["stargazers"], reverse=True) return ranked_repos if __name__ == "__main__": main()
670
0
46
9c94d36e656c8b0972e4d60231610351bbee92fa
9,994
py
Python
BioLAMA/best.py
dmis-lab/BioLAMA
28eabf54af362e58e7b8b8096b3a71c432b4f02b
[ "Apache-2.0" ]
29
2021-09-16T02:26:37.000Z
2022-03-27T08:48:55.000Z
BioLAMA/best.py
dmis-lab/BioLAMA
28eabf54af362e58e7b8b8096b3a71c432b4f02b
[ "Apache-2.0" ]
5
2021-09-24T02:32:49.000Z
2022-03-17T11:53:55.000Z
BioLAMA/best.py
dmis-lab/BioLAMA
28eabf54af362e58e7b8b8096b3a71c432b4f02b
[ "Apache-2.0" ]
2
2021-12-16T07:09:13.000Z
2022-03-17T03:47:20.000Z
""" .. module:: BEST :platform: Unix, linux, Windows .. moduleauthor:: Sunkyu Kim <sunkyu-kim@korea.ac.kr> ================================ Biomedical Entity Query API v2 ================================ API Description ================ This API is for use of BEST(Biomedical Entity Search Tool) in various purposes. All users can access BEST at : http://best.korea.ac.kr/ For bugs and inquiries, please contact: * Jaewoo Kang(kangj@korea.ac.kr) * Sunkyu Kim(sunkyu-kim@korea.ac.kr) Reference : https://doi.org/10.1371/journal.pone.0164680 Usage Examples =============== To see ‘gene’s related ‘breast cancer’, use this sample code. >>> bestQuery = best.BESTQuery("breast cancer", filterObjectName="gene", noAbsTxt=False) >>> searchResult = best.getRelevantBioEntities(bestQuery) >>> print(searchResult) [{ 'entityname' : 'ERBB2', 'score' : 8098.43, 'PMIDs' : ['28427196', '28341751', '28199325'], 'abstracts' : [ 'Molecular-based cancer tests...', 'The molecular subtype of breast...' 'Breast cancer is the second leading cause of...'], 'numArticles':14537 'rank' : 1}, { 'entityname' : 'ESR1', 'score' : 7340.54, 'PMIDs' : ['27923387', '28274211', '26276891'], 'abstracts' : [ 'Several studies have shown that mammographic..', 'A shift towards less burdening and more...' 'The complete molecular basis of the organ-...'], 'numArticles':18084 'rank' : 2}, ... ] Changing noAbsTxt=True can make the process faster. >>> bestQuery = best.BESTQuery("breast cancer", filterObjectName="gene", noAbsTxt=True) >>> searchResult = best.getRelevantBioEntities(bestQuery) >>> print(searchResult) [{ 'entityname' : 'ERBB2', 'score' : 8098.43, 'PMIDs' : [], 'abstracts' : [], 'numArticles':14537 'rank' : 1}, { 'entityname' : 'ESR1', 'score' : 7340.54, 'PMIDs' : [], 'abstracts' : [], 'numArticles':18084 'rank' : 2}, ... ] If you want to see other entity types, change filterObjectName. .. note:: Total 10 filterObjects(entity types) are available. * gene * drug * chemical compound * target * disease * toxin * transcription factor * mirna * pathway * mutation >>> bestQuery = best.BESTQuery("breast cancer", filterObjectName="drug", noAbsTxt=True) >>> searchResult = best.getRelevantBioEntities(bestQuery) >>> print(searchResult) [{ 'entityname' : 'tamoxifen', 'score' : 3208.687, 'abstracts' : [], 'numArticles':10583 'rank' : 1}, { 'entityname' : 'doxorubicin', 'score' : 1639.867, 'abstracts' : [], 'numArticles':6074 'rank' : 2}, ... ] Class/Function Description =========================== """ import http #from http.client import HTTPException import socket class BESTQuery(): """ BESTQuery class is basic query object for BEST API. """ __besturl = "http://best.korea.ac.kr/s?" def __init__(self, querystr, filterObjectName="All Entity Type", topN=20, noAbsTxt=True): """BESTQuery :param querystr, filterObjectName : result type, topN, noAbsTxt : if True, the result doesn't include the abstract texts. . >>> query = BESTQuery("lung cancer", filterObjectName="gene", topN=10, noAbsTxt=False) >>> # 10 genes related with lung cancer is searched including the abstract texts. """ self.querystr = querystr self.filterObjectName = filterObjectName self.topN = topN self.noAbsTxt = noAbsTxt def setQuerystr (self, querystr): """Setting the query :param querystr: a string object >>> query.setQuery(["cancer"]) """ if type(querystr) is not str: print ("Initialize error : invalid query. It should be a string object.") print (querystr) return if len(querystr) == 0: return self.querystr = querystr def getQuerystr (self): """Getting the query String :return: A string >>> querystr = query.getQuerystr() >>> print (querystr) ["cancer"] """ return self.querystr def setTopN (self, n): """ Setting the number of results retrieved by query :param n: the number of results to be retrieved >>> query.setTopN(100) """ self.topN = n def getTopN (self): """ Getting the number of results retrieved by query :return: the number of results to be retrieved >>> print (query.getTopN()) 100 """ return self.topN def setFilterObjectName (self, oname): """ Setting the filtering object. Total 10 types are available. * gene * drug * chemical compound * target * disease * toxin * transcription factor * mirna * pathway * mutation >>> qeury.setFilterObjectName("Gene") """ self.filterObjectName = oname def getFilterObjectName (self): """ Getting the filtering entity type. >>> print(query.getFilterObjectName()) "breast cancer" """ return self.filterObjectName def getRelevantBioEntities(bestQuery): """ Function for retrieval from BEST :param bestQuery: BESTQuery :return: parsed objects (dict-BIOENTITY). * BIOENTITY (dict): {"entityName":str, "rank":int, "score":float, "numArticles":int, "abstracts":[str]} >>> bestQuery = BESTQuery( "lung cancer", filterObjectName="gene", topN=10, noAbsTxt=True ) >>> relevantEntities = getRelevantBioEntities(bestQuery) """ if not (type(bestQuery) is BESTQuery): print ("query is invalid! please check your query object.") return None if not bestQuery._isValid() : print ("Query object is invalid. Please check the query") print ("Query : ") print (" query: " + str(bestQuery.query)) print (" topN: " + str(bestQuery.topN)) return None urlquery = bestQuery.makeQueryString() import urllib resultStr = "" again = 0 while (again < 5): try: request = urllib.request.Request(urlquery) request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)') geneUrl = urllib.request.urlopen(request, timeout=5) resultStr = geneUrl.read().decode('utf-8') again = 10 except http.client.BadStatusLine: again += 1 except http.client.HTTPException: again += 1 except socket.timeout: again += 1 except socket.error: again += 1 except urllib.error.URLError: again += 1 except Exception: again += 1 if again == 5: print("Network status is not good") return None result = __makeDataFromBestQueryResult(resultStr) return result
30.562691
201
0.558735
""" .. module:: BEST :platform: Unix, linux, Windows .. moduleauthor:: Sunkyu Kim <sunkyu-kim@korea.ac.kr> ================================ Biomedical Entity Query API v2 ================================ API Description ================ This API is for use of BEST(Biomedical Entity Search Tool) in various purposes. All users can access BEST at : http://best.korea.ac.kr/ For bugs and inquiries, please contact: * Jaewoo Kang(kangj@korea.ac.kr) * Sunkyu Kim(sunkyu-kim@korea.ac.kr) Reference : https://doi.org/10.1371/journal.pone.0164680 Usage Examples =============== To see ‘gene’s related ‘breast cancer’, use this sample code. >>> bestQuery = best.BESTQuery("breast cancer", filterObjectName="gene", noAbsTxt=False) >>> searchResult = best.getRelevantBioEntities(bestQuery) >>> print(searchResult) [{ 'entityname' : 'ERBB2', 'score' : 8098.43, 'PMIDs' : ['28427196', '28341751', '28199325'], 'abstracts' : [ 'Molecular-based cancer tests...', 'The molecular subtype of breast...' 'Breast cancer is the second leading cause of...'], 'numArticles':14537 'rank' : 1}, { 'entityname' : 'ESR1', 'score' : 7340.54, 'PMIDs' : ['27923387', '28274211', '26276891'], 'abstracts' : [ 'Several studies have shown that mammographic..', 'A shift towards less burdening and more...' 'The complete molecular basis of the organ-...'], 'numArticles':18084 'rank' : 2}, ... ] Changing noAbsTxt=True can make the process faster. >>> bestQuery = best.BESTQuery("breast cancer", filterObjectName="gene", noAbsTxt=True) >>> searchResult = best.getRelevantBioEntities(bestQuery) >>> print(searchResult) [{ 'entityname' : 'ERBB2', 'score' : 8098.43, 'PMIDs' : [], 'abstracts' : [], 'numArticles':14537 'rank' : 1}, { 'entityname' : 'ESR1', 'score' : 7340.54, 'PMIDs' : [], 'abstracts' : [], 'numArticles':18084 'rank' : 2}, ... ] If you want to see other entity types, change filterObjectName. .. note:: Total 10 filterObjects(entity types) are available. * gene * drug * chemical compound * target * disease * toxin * transcription factor * mirna * pathway * mutation >>> bestQuery = best.BESTQuery("breast cancer", filterObjectName="drug", noAbsTxt=True) >>> searchResult = best.getRelevantBioEntities(bestQuery) >>> print(searchResult) [{ 'entityname' : 'tamoxifen', 'score' : 3208.687, 'abstracts' : [], 'numArticles':10583 'rank' : 1}, { 'entityname' : 'doxorubicin', 'score' : 1639.867, 'abstracts' : [], 'numArticles':6074 'rank' : 2}, ... ] Class/Function Description =========================== """ import http #from http.client import HTTPException import socket class BESTQuery(): """ BESTQuery class is basic query object for BEST API. """ __besturl = "http://best.korea.ac.kr/s?" def __init__(self, querystr, filterObjectName="All Entity Type", topN=20, noAbsTxt=True): """BESTQuery :param querystr, filterObjectName : result type, topN, noAbsTxt : if True, the result doesn't include the abstract texts. . >>> query = BESTQuery("lung cancer", filterObjectName="gene", topN=10, noAbsTxt=False) >>> # 10 genes related with lung cancer is searched including the abstract texts. """ self.querystr = querystr self.filterObjectName = filterObjectName self.topN = topN self.noAbsTxt = noAbsTxt def setQuerystr (self, querystr): """Setting the query :param querystr: a string object >>> query.setQuery(["cancer"]) """ if type(querystr) is not str: print ("Initialize error : invalid query. It should be a string object.") print (querystr) return if len(querystr) == 0: return self.querystr = querystr def getQuerystr (self): """Getting the query String :return: A string >>> querystr = query.getQuerystr() >>> print (querystr) ["cancer"] """ return self.querystr def _isValid(self): if self.querystr is not None and self.querystr is not None and type(self.querystr) is not str: return False for keya in self.querystr : if type(keya) is not str : return False if self.topN <= 0: return False return True def setTopN (self, n): """ Setting the number of results retrieved by query :param n: the number of results to be retrieved >>> query.setTopN(100) """ self.topN = n def getTopN (self): """ Getting the number of results retrieved by query :return: the number of results to be retrieved >>> print (query.getTopN()) 100 """ return self.topN def setFilterObjectName (self, oname): """ Setting the filtering object. Total 10 types are available. * gene * drug * chemical compound * target * disease * toxin * transcription factor * mirna * pathway * mutation >>> qeury.setFilterObjectName("Gene") """ self.filterObjectName = oname def getFilterObjectName (self): """ Getting the filtering entity type. >>> print(query.getFilterObjectName()) "breast cancer" """ return self.filterObjectName def makeQueryString(self): queryKeywords = self.querystr querytype = self.filterObjectName.lower() noAbsTxt = self.noAbsTxt import urllib.parse queryKeywords = "q=" + urllib.parse.quote(queryKeywords) otype = "" if querytype == "gene": otype = "8" elif querytype == "drug": otype = "5" elif querytype == "chemical compound": otype = "3" elif querytype == "target": otype = "14" elif querytype == "disease": otype = "4" elif querytype == "toxin": otype = "15" elif querytype == "transcription factor": otype = "16" elif querytype == "mirna": otype = "10" elif querytype == "pathway": otype = "12" elif querytype == "mutation": otype = "17" elif querytype == "all entity type": otype = "" else: print ("Invalid type! Object type : All Entity Type") otype = "" if noAbsTxt: strQuery = self.__besturl + "t=l&wt=xslt&tr=tmpl2.xsl" + "&otype=" + otype + "&rows=" + str(self.topN) + "&" + queryKeywords else: strQuery = self.__besturl + "t=l&wt=xslt&tr=tmpl_170602.xsl" + "&otype=" + otype + "&rows=" + str(self.topN) + "&" + queryKeywords return strQuery def toDataObj(self): return {"query":self.querystr, "filterObjectName":self.filterObjectName, "topN":self.topN} def getRelevantBioEntities(bestQuery): """ Function for retrieval from BEST :param bestQuery: BESTQuery :return: parsed objects (dict-BIOENTITY). * BIOENTITY (dict): {"entityName":str, "rank":int, "score":float, "numArticles":int, "abstracts":[str]} >>> bestQuery = BESTQuery( "lung cancer", filterObjectName="gene", topN=10, noAbsTxt=True ) >>> relevantEntities = getRelevantBioEntities(bestQuery) """ if not (type(bestQuery) is BESTQuery): print ("query is invalid! please check your query object.") return None if not bestQuery._isValid() : print ("Query object is invalid. Please check the query") print ("Query : ") print (" query: " + str(bestQuery.query)) print (" topN: " + str(bestQuery.topN)) return None urlquery = bestQuery.makeQueryString() import urllib resultStr = "" again = 0 while (again < 5): try: request = urllib.request.Request(urlquery) request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)') geneUrl = urllib.request.urlopen(request, timeout=5) resultStr = geneUrl.read().decode('utf-8') again = 10 except http.client.BadStatusLine: again += 1 except http.client.HTTPException: again += 1 except socket.timeout: again += 1 except socket.error: again += 1 except urllib.error.URLError: again += 1 except Exception: again += 1 if again == 5: print("Network status is not good") return None result = __makeDataFromBestQueryResult(resultStr) return result def __makeDataFromBestQueryResult(resultStr): lines = resultStr.split('\n') linesCnt = len(lines) resultDataArr = [] curData = {"rank":0} for i in range(1, linesCnt) : line = lines[i] if line.startswith("@@@"): pmid, text = line[3:].strip().split("###") curData["abstracts"].append(text) curData["PMIDs"].append(pmid) else: if len(line.strip()) == 0 : continue if curData["rank"] != 0: resultDataArr.append(curData) dataResult = line.split(" | ") curData = {"rank":int(dataResult[0].strip()), "entityName":dataResult[1].strip(), "score":float(dataResult[2].strip()), "numArticles":int(dataResult[3].strip()), "abstracts":[], "PMIDs":[]} resultDataArr.append(curData) return resultDataArr
2,624
0
104
3faf6cfa0866ca8d6a6f948152e173e23006d08d
352
py
Python
python-benchmarking-tools/test/test_log.py
HASTE-project/benchmarking-tools
3e65cd4019287051a612bc21fa68e4b1a5bbc745
[ "BSD-3-Clause" ]
null
null
null
python-benchmarking-tools/test/test_log.py
HASTE-project/benchmarking-tools
3e65cd4019287051a612bc21fa68e4b1a5bbc745
[ "BSD-3-Clause" ]
null
null
null
python-benchmarking-tools/test/test_log.py
HASTE-project/benchmarking-tools
3e65cd4019287051a612bc21fa68e4b1a5bbc745
[ "BSD-3-Clause" ]
null
null
null
import io import unittest import unittest.mock from haste.benchmarking import log
23.466667
64
0.713068
import io import unittest import unittest.mock from haste.benchmarking import log class TestLog(unittest.TestCase): @unittest.mock.patch('sys.stdout', new_callable=io.StringIO) def test_log(self, mock_stdout): log.log('topic', 'message') print(mock_stdout.getvalue()) self.assertEqual('foo', mock_stdout.getvalue())
141
104
23
d09a47265de40fa28d63d23152163d2afe398393
32
py
Python
RandomBot/__init__.py
RandomBotDev/RandomBotCog
a00db232cf6eeb85293060a3ffaf6d44f4330450
[ "MIT" ]
null
null
null
RandomBot/__init__.py
RandomBotDev/RandomBotCog
a00db232cf6eeb85293060a3ffaf6d44f4330450
[ "MIT" ]
null
null
null
RandomBot/__init__.py
RandomBotDev/RandomBotCog
a00db232cf6eeb85293060a3ffaf6d44f4330450
[ "MIT" ]
1
2022-03-07T11:48:37.000Z
2022-03-07T11:48:37.000Z
from RandomBot.MainCog import *
16
31
0.8125
from RandomBot.MainCog import *
0
0
0
d55115c108a4e0def496b8f1eed2b517ab34ee3a
1,398
py
Python
notebooks/chisel-tutorial/src/chisel-tutorial/adder4.py
edwardcwang/magmathon
f9a1e9d93823d0a90e77c968d952d05b553a6a86
[ "MIT" ]
null
null
null
notebooks/chisel-tutorial/src/chisel-tutorial/adder4.py
edwardcwang/magmathon
f9a1e9d93823d0a90e77c968d952d05b553a6a86
[ "MIT" ]
null
null
null
notebooks/chisel-tutorial/src/chisel-tutorial/adder4.py
edwardcwang/magmathon
f9a1e9d93823d0a90e77c968d952d05b553a6a86
[ "MIT" ]
null
null
null
# coding: utf-8 # In[1]: import sys sys.path.append("../../examples") from full_adder import FullAdder from magma import * # In[2]: T = Bits(4) # In[3]: from magma.simulator import PythonSimulator from magma.bit_vector import BitVector simulator = PythonSimulator(Adder4) simulator.set_value(Adder4.a, BitVector(2, num_bits=4)) simulator.set_value(Adder4.b, BitVector(3, num_bits=4)) simulator.set_value(Adder4.cin, True) simulator.evaluate() assert simulator.get_value(Adder4.out) == BitVector(6, num_bits=4) assert simulator.get_value(Adder4.cout) == False print("Success!")
24.103448
82
0.619456
# coding: utf-8 # In[1]: import sys sys.path.append("../../examples") from full_adder import FullAdder from magma import * # In[2]: T = Bits(4) class Adder4(Circuit): name = "Adder4" IO = ["a", In(T), "b", In(T), "cin", In(Bit), "out", Out(T), "cout", Out(Bit)] @classmethod def definition(io): adder1 = FullAdder() wire(io.a[0], adder1.a) wire(io.b[0], adder1.b) wire(io.cin, adder1.cin) adder2 = FullAdder() wire(io.a[1], adder2.a) wire(io.b[1], adder2.b) wire(adder1.cout, adder2.cin) adder3 = FullAdder() wire(io.a[2], adder3.a) wire(io.b[2], adder3.b) wire(adder2.cout, adder3.cin) adder4 = FullAdder() wire(io.a[3], adder4.a) wire(io.b[3], adder4.b) wire(adder3.cout, adder4.cin) wire(adder4.cout, io.cout) wire(bits([adder1.out, adder2.out, adder3.out, adder4.out]), io.out) # In[3]: from magma.simulator import PythonSimulator from magma.bit_vector import BitVector simulator = PythonSimulator(Adder4) simulator.set_value(Adder4.a, BitVector(2, num_bits=4)) simulator.set_value(Adder4.b, BitVector(3, num_bits=4)) simulator.set_value(Adder4.cin, True) simulator.evaluate() assert simulator.get_value(Adder4.out) == BitVector(6, num_bits=4) assert simulator.get_value(Adder4.cout) == False print("Success!")
638
147
22
7bfcdc9926552a8b0a147972eecca053f069298b
694
py
Python
Algorithms/0021_Merge_Two_Sorted_Lists/Python/Merge_Two_Sorted_Lists_Solution_1.py
lht19900714/Leetcode_Solutions
dac7a038329a5c1f8a78e86cc6f49116b963f1fb
[ "MIT" ]
null
null
null
Algorithms/0021_Merge_Two_Sorted_Lists/Python/Merge_Two_Sorted_Lists_Solution_1.py
lht19900714/Leetcode_Solutions
dac7a038329a5c1f8a78e86cc6f49116b963f1fb
[ "MIT" ]
null
null
null
Algorithms/0021_Merge_Two_Sorted_Lists/Python/Merge_Two_Sorted_Lists_Solution_1.py
lht19900714/Leetcode_Solutions
dac7a038329a5c1f8a78e86cc6f49116b963f1fb
[ "MIT" ]
null
null
null
# Space: O(1) # Time: O(n) # Recursive approach # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
18.756757
53
0.489914
# Space: O(1) # Time: O(n) # Recursive approach # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeTwoLists(self, l1, l2): def helper(l1, l2): if l1 is None and l2 is None: return None if l1 is None: return l2 if l2 is None: return l1 res = ListNode(0) if l1.val < l2.val: l1.next = helper(l1.next, l2) res.next = l1 else: l2.next = helper(l1, l2.next) res.next = l2 return res.next return helper(l1, l2)
462
-6
50
0fcb44b3908d0bb94f87d70dc7b56e91aa980468
3,257
py
Python
dvc/utils/fs.py
ap-kulkarni/dvc
735b563ce411413d29be4d9ec2eca716356de3b9
[ "Apache-2.0" ]
null
null
null
dvc/utils/fs.py
ap-kulkarni/dvc
735b563ce411413d29be4d9ec2eca716356de3b9
[ "Apache-2.0" ]
null
null
null
dvc/utils/fs.py
ap-kulkarni/dvc
735b563ce411413d29be4d9ec2eca716356de3b9
[ "Apache-2.0" ]
null
null
null
import errno import logging import os import shutil import stat import sys from typing import TYPE_CHECKING from dvc.exceptions import DvcException if TYPE_CHECKING: from dvc.types import StrPath logger = logging.getLogger(__name__) def path_isin(child: "StrPath", parent: "StrPath") -> bool: """Check if given `child` path is inside `parent`.""" parent = os.path.join(normalize_path(parent), "") child = normalize_path(child) return child != parent and child.startswith(parent)
26.917355
76
0.634326
import errno import logging import os import shutil import stat import sys from typing import TYPE_CHECKING from dvc.exceptions import DvcException if TYPE_CHECKING: from dvc.types import StrPath logger = logging.getLogger(__name__) class BasePathNotInCheckedPathException(DvcException): def __init__(self, path, base_path): msg = "Path: {} does not overlap with base path: {}".format( path, base_path ) super().__init__(msg) def contains_symlink_up_to(path: "StrPath", base_path: "StrPath"): from dvc.fs import system base_path = os.path.normcase(os.fspath(base_path)) path = os.path.normcase(os.fspath(path)) if base_path not in path: raise BasePathNotInCheckedPathException(path, base_path) if path == base_path: return False if system.is_symlink(path): return True if os.path.dirname(path) == path: return False return contains_symlink_up_to(os.path.dirname(path), base_path) def _chmod(func, p, excinfo): # pylint: disable=unused-argument perm = os.lstat(p).st_mode perm |= stat.S_IWRITE try: os.chmod(p, perm) except OSError as exc: # broken symlink or file is not owned by us if exc.errno not in [errno.ENOENT, errno.EPERM]: raise func(p) def _unlink(path, onerror): try: os.unlink(path) except OSError: onerror(os.unlink, path, sys.exc_info()) def remove(path): logger.debug("Removing '%s'", path) try: if os.path.isdir(path): shutil.rmtree(path, onerror=_chmod) else: _unlink(path, _chmod) except OSError as exc: if exc.errno != errno.ENOENT: raise def path_isin(child: "StrPath", parent: "StrPath") -> bool: """Check if given `child` path is inside `parent`.""" def normalize_path(path) -> str: return os.path.normcase(os.path.normpath(path)) parent = os.path.join(normalize_path(parent), "") child = normalize_path(child) return child != parent and child.startswith(parent) def makedirs(path, exist_ok=False, mode=None): if mode is None: os.makedirs(path, exist_ok=exist_ok) return # Modified version of os.makedirs() with support for extended mode # (e.g. S_ISGID) head, tail = os.path.split(path) if not tail: head, tail = os.path.split(head) if head and tail and not os.path.exists(head): try: makedirs(head, exist_ok=exist_ok, mode=mode) except FileExistsError: # Defeats race condition when another thread created the path pass cdir = os.curdir if isinstance(tail, bytes): cdir = bytes(os.curdir, "ASCII") if tail == cdir: # xxx/newdir/. exists if xxx/newdir exists return try: os.mkdir(path, mode) except OSError: # Cannot rely on checking for EEXIST, since the operating system # could give priority to other errors like EACCES or EROFS if not exist_ok or not os.path.isdir(path): raise try: os.chmod(path, mode) except OSError: logger.trace("failed to chmod '%o' '%s'", mode, path, exc_info=True)
2,522
33
191
e6b4b48425df0aec5cd3b453e554c427e79241d4
3,935
py
Python
tfplot/figure.py
sirspinach/tensorflow-plot
d6ad65cb4392e9adbf65d3dc8086a2eacd1e9f43
[ "MIT" ]
null
null
null
tfplot/figure.py
sirspinach/tensorflow-plot
d6ad65cb4392e9adbf65d3dc8086a2eacd1e9f43
[ "MIT" ]
null
null
null
tfplot/figure.py
sirspinach/tensorflow-plot
d6ad65cb4392e9adbf65d3dc8086a2eacd1e9f43
[ "MIT" ]
null
null
null
''' Figure utilities. ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import types import matplotlib.pyplot as plt from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg import six from io import BytesIO from tensorflow import Summary from . import mpl_figure def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw): """ Create a figure and a set of subplots, as in `pyplot.subplots()`. It works almost similar to `pyplot.subplots()`, but differ from it in that it does not involve any side effect as pyplot does (e.g. modifying thread states such as current figure or current subplot). (docstrings inherited from `matplotlib.pyplot.subplots`) """ FigureClass = fig_kw.pop('FigureClass', Figure) fig = FigureClass(**fig_kw) # attach a new Agg canvas if fig.canvas is None: FigureCanvasAgg(fig) # create subplots, e.g. fig.subplots() in matplotlib 2.1+ if not hasattr(fig, 'subplots'): if six.PY2: fig.subplots = types.MethodType(mpl_figure.subplots, fig, FigureClass) else: fig.subplots = types.MethodType(mpl_figure.subplots, fig) axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey, squeeze=squeeze, subplot_kw=subplot_kw, gridspec_kw=gridspec_kw) return fig, axs # inherit and append a part of the docstring from pyplot.subplots() subplots.__doc__ += plt.subplots.__doc__[plt.subplots.__doc__.find('Parameters'):]\ .replace('plt.subplots', 'tfplot.subplots') def to_array(fig): """ Convert a matplotlib figure ``fig`` into a 3D numpy array. Example: >>> fig, ax = tfplot.subplots(figsize=(4, 4)) >>> # draw whatever, e.g. ax.text(0.5, 0.5, "text") >>> im = to_array(fig) # ndarray [288, 288, 4] Args: fig: A ``matplotlib.figure.Figure`` object. Returns: A numpy ``ndarray`` of shape ``(?, ?, 4)``, containing an RGB-A image of the figure. """ # attach a new canvas if not exists if fig.canvas is None: FigureCanvasAgg(fig) fig.canvas.draw() w, h = fig.canvas.get_width_height() img = np.frombuffer(fig.canvas.tostring_argb(), dtype=np.uint8) img = img.reshape((h, w, 4)) img = img[:, :, (1, 2, 3, 0)] # argb -> rgba return img def to_summary(fig, tag): """ Convert a matplotlib figure ``fig`` into a TensorFlow Summary object that can be directly fed into ``Summary.FileWriter``. Example: >>> fig, ax = ... # (as above) >>> summary = to_summary(fig, tag='MyFigure/image') >>> type(summary) tensorflow.core.framework.summary_pb2.Summary >>> summary_writer.add_summary(summary, global_step=global_step) Args: fig: A ``matplotlib.figure.Figure`` object. tag (string): The tag name of the created summary. Returns: A TensorFlow ``Summary`` protobuf object containing the plot image as a image summary. """ if not isinstance(tag, six.string_types): raise TypeError("tag must be a string type") # attach a new canvas if not exists if fig.canvas is None: FigureCanvasAgg(fig) fig.canvas.draw() w, h = fig.canvas.get_width_height() # get PNG data from the figure png_buffer = BytesIO() fig.canvas.print_png(png_buffer) png_encoded = png_buffer.getvalue() png_buffer.close() summary_image = Summary.Image(height=h, width=w, colorspace=4, # RGB-A encoded_image_string=png_encoded) summary = Summary(value=[Summary.Value(tag=tag, image=summary_image)]) return summary __all__ = ( 'to_array', 'to_summary', 'subplots', )
28.309353
83
0.652097
''' Figure utilities. ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import types import matplotlib.pyplot as plt from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg import six from io import BytesIO from tensorflow import Summary from . import mpl_figure def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw): """ Create a figure and a set of subplots, as in `pyplot.subplots()`. It works almost similar to `pyplot.subplots()`, but differ from it in that it does not involve any side effect as pyplot does (e.g. modifying thread states such as current figure or current subplot). (docstrings inherited from `matplotlib.pyplot.subplots`) """ FigureClass = fig_kw.pop('FigureClass', Figure) fig = FigureClass(**fig_kw) # attach a new Agg canvas if fig.canvas is None: FigureCanvasAgg(fig) # create subplots, e.g. fig.subplots() in matplotlib 2.1+ if not hasattr(fig, 'subplots'): if six.PY2: fig.subplots = types.MethodType(mpl_figure.subplots, fig, FigureClass) else: fig.subplots = types.MethodType(mpl_figure.subplots, fig) axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey, squeeze=squeeze, subplot_kw=subplot_kw, gridspec_kw=gridspec_kw) return fig, axs # inherit and append a part of the docstring from pyplot.subplots() subplots.__doc__ += plt.subplots.__doc__[plt.subplots.__doc__.find('Parameters'):]\ .replace('plt.subplots', 'tfplot.subplots') def to_array(fig): """ Convert a matplotlib figure ``fig`` into a 3D numpy array. Example: >>> fig, ax = tfplot.subplots(figsize=(4, 4)) >>> # draw whatever, e.g. ax.text(0.5, 0.5, "text") >>> im = to_array(fig) # ndarray [288, 288, 4] Args: fig: A ``matplotlib.figure.Figure`` object. Returns: A numpy ``ndarray`` of shape ``(?, ?, 4)``, containing an RGB-A image of the figure. """ # attach a new canvas if not exists if fig.canvas is None: FigureCanvasAgg(fig) fig.canvas.draw() w, h = fig.canvas.get_width_height() img = np.frombuffer(fig.canvas.tostring_argb(), dtype=np.uint8) img = img.reshape((h, w, 4)) img = img[:, :, (1, 2, 3, 0)] # argb -> rgba return img def to_summary(fig, tag): """ Convert a matplotlib figure ``fig`` into a TensorFlow Summary object that can be directly fed into ``Summary.FileWriter``. Example: >>> fig, ax = ... # (as above) >>> summary = to_summary(fig, tag='MyFigure/image') >>> type(summary) tensorflow.core.framework.summary_pb2.Summary >>> summary_writer.add_summary(summary, global_step=global_step) Args: fig: A ``matplotlib.figure.Figure`` object. tag (string): The tag name of the created summary. Returns: A TensorFlow ``Summary`` protobuf object containing the plot image as a image summary. """ if not isinstance(tag, six.string_types): raise TypeError("tag must be a string type") # attach a new canvas if not exists if fig.canvas is None: FigureCanvasAgg(fig) fig.canvas.draw() w, h = fig.canvas.get_width_height() # get PNG data from the figure png_buffer = BytesIO() fig.canvas.print_png(png_buffer) png_encoded = png_buffer.getvalue() png_buffer.close() summary_image = Summary.Image(height=h, width=w, colorspace=4, # RGB-A encoded_image_string=png_encoded) summary = Summary(value=[Summary.Value(tag=tag, image=summary_image)]) return summary __all__ = ( 'to_array', 'to_summary', 'subplots', )
0
0
0
254837b592b886220849629aa4e47fbd84c719a1
18,279
py
Python
campy/private/backends/jbe/platformat.py
TristenSeth/campy
9e726c342d682239e1c19e6f5645c0b2167d7fab
[ "MIT" ]
5
2018-12-03T19:18:50.000Z
2021-05-31T07:17:06.000Z
campy/private/backends/jbe/platformat.py
TristenSeth/campy
9e726c342d682239e1c19e6f5645c0b2167d7fab
[ "MIT" ]
1
2017-06-07T04:33:46.000Z
2017-06-07T04:33:46.000Z
campy/private/backends/jbe/platformat.py
TristenSeth/campy
9e726c342d682239e1c19e6f5645c0b2167d7fab
[ "MIT" ]
1
2017-06-06T07:29:07.000Z
2017-06-06T07:29:07.000Z
""" Java Backend Format Strings The following section lists format strings for the Java backend, and can/ should be updated as the text API to the Stanford Portable Library changes. The strings are marked using keyword format syntax, which can be expanded by keyword in Python """ # Platform::filelib_fileExists # Platform::filelib_isFile # Platform::filelib_isSymbolicLink # Platform::filelib_isDirectory # Platform::filelib_setCurrentDirectory # Platform::filelib_getCurrentDirectory # Platform::filelib_getTempDirectory # Platform::filelib_createDirectory # Platform::filelib_deleteFile # Platform::filelib_getDirectoryPathSeparator # Platform::filelib_getSearchPathSeparator # Platform::filelib_expandPathname # Platform::filelib_listDirectory # Platform::filelib_fileExists # Platform::filelib_isFile # Platform::filelib_isSymbolicLink # Platform::filelib_isDirectory # Platform::filelib_setCurrentDirectory # Platform::filelib_getCurrentDirectory # Platform::filelib_getTempDirectory # Platform::filelib_createDirectory # Platform::filelib_deleteFile # Platform::filelib_getDirectoryPathSeparator # Platform::filelib_getSearchPathSeparator # Platform::filelib_expandPathname # Platform::filelib_listDirectory # Platform::setStackSize # Platform::os_getLastError # Platform::regex_match # Platform::regex_matchCount # Platform::regex_matchCountWithLines # Platform::regex_replace # Transfer to functions: DONE: # File_ # TODO: special File_openFileDialog = 'File.openFileDialog("{title!q}", "{mode}", "{path!q}")' # TODO check if needs to be quoted GWindow_constructor = 'GWindow.create("{id}", {width}, {height}, "{top_compound}", {visible!b})' GWindow_delete = 'GWindow.delete("{id}")' GWindow_close = 'GWindow.close("{id}")' GWindow_requestFocus = 'GWindow.requestFocus("{id}")' GWindow_setExitOnClose = 'GWindow.setExitOnClose("{id}", {value!b})' GWindow_clear = 'GWindow.clear("{id}")' GWindow_clearCanvas = 'GWindow.clearCanvas("{id}")' GWindow_repaint = 'GWindow.repaint("{id}")' GWindow_saveCanvasPixels = 'GWindow.saveCanvasPixels("{id}", {filename!q}' GWindow_setSize = 'GWindow.setSize("{id}", {width}, {height})' GWindow_setCanvasSize = 'GWindow.setCanvasSize("{id}", {width}, {height})' GWindow_setCloseOperation = 'GWindow.setCloseOperation("{id}", {op}' GWindow_minimize = 'GWindow.minimize("{id}")' GWindow_pack = 'GWindow.pack("{id}")' GWindow_setTitle = 'GWindow.setTitle("{id}", {title!q})' GWindow_setLocation = 'GWindow.setLocation("{id}", {x}, {y})' GWindow_setLocationSaved = 'GWindow.setLocationSaved("{id}", {value!b})' GWindow_setPixel = 'GWindow.setPixel("{id}", {x}, {y}, {rgb}, {repaint!b})' GWindow_setPixels = 'GWindow.setPixels("{id}", {base64!q})' # TODO: Special GWindow_toBack = 'GWindow.toBack("{id}")' GWindow_toFront = 'GWindow.toFront("{id}")' GWindow_getScreenHeight = 'GWindow.getScreenHeight()' GWindow_getScreenSize = 'GWindow.getScreenSize()' GWindow_getScreenWidth = 'GWindow.getScreenWidth()' GWindow_draw = 'GWindow.draw("{id}", "{gobj_id}")' GWindow_drawInBackground = 'GWindow.drawInBackground("{id}", "{gobj_id}")' GWindow_exitGraphics = 'GWindow.exitGraphics()' # TODO: special GWindow_setRegionAlignment = 'GWindow.setRegionAlignment("{id}", "{region}", "{align}")' GWindow_setResizable = 'GWindow.setResizable("{id}", {value!b})' GWindow_addToRegion = 'GWindow.addToRegion("{id}", "{gobj_id}", "{region}")' GWindow_getLocation = 'GWindow.getLocation("{id}")' # TODO special GWindow_getPixel = 'GWindow.getPixel("{id}", {x}, {y})' # TODO special GWindow_getPixels = 'GWindow.getPixels("{id}")' # TODO special GWindow_getRegionSize = 'GWindow.getRegionSize("{id}", "{region}")' # TODO: special GWindow_removeFromRegion = 'GWindow.removeFromRegion("{id}", "{gobj_id}", "{region}")' GWindow_getSize = 'GWindow.getSize("{id}")' # TODO special GWindow_getCanvasSize = 'GWindow.getCanvasSize("{id}")' # TODO: special GWindow_getContentPaneSize = 'GWindow.getContentPaneSize("{id}")' # TODO: special GWindow_setVisible = 'GWindow.setVisible("{id}", {flag!b})' GTimer_constructor = 'GTimer.create("{id}", {millis})' GTimer_delete = 'GTimer.deleteTimer("{id}")' GTimer_start = 'GTimer.startTimer("{id}")' GTimer_pause = 'GTimer.pause({millis})' GTimer_stop = 'GTimer.stopTimer("{id}")' HttpServer_sendResponse = 'HttpServer.sendResponse({request_id}, {http_error_code}, {contentType!q}, {responseText!q})' HttpServer_sendResponseFile = 'HttpServer.sendResponseFile({request_id}, {content_type!q}, {response_file_path!q})' HttpServer_start = 'HttpServer.start({port})' HttpServer_stop = 'HttpServer.stop()' Sound_constructor = 'Sound.create("{id}", {filename!q})' Sound_delete = 'Sound.delete("{id}")' Sound_play = 'Sound.play("{id}")' # Platform::url_download GCompound_constructor = 'GCompound.create("{id}")' GCompound_add = 'GCompound.add("{compound_id}", "{gobj_id}")' GObject_delete = 'GObject.delete("{id}")' GObject_remove = 'GObject.remove("{id}")' GObject_sendForward = 'GObject.sendForward("{id}")' GObject_sendToFront = 'GObject.sendToFront("{id}")' GObject_sendBackward = 'GObject.sendBackward("{id}")' GObject_sendToBack = 'GObject.sendToBack("{id}")' GObject_setVisible = 'GObject.setVisible("{id}", {flag!b})' GObject_setColor = 'GObject.setColor("{id}", "{color}")' GObject_scale = 'GObject.scale("{id}", {sx}, {sy})' GObject_rotate = 'GObject.rotate("{id}", {theta})' GObject_contains = 'GObject.contains("{id}", {x}, {y})' # TODO: special move into gobjects.py GObject_getBounds = 'GObject.getBounds("{id}")' # TODO: special GObject_setLineWidth = 'GObject.setLineWidth("{id}", {line_width})' GObject_setLocation = 'GObject.setLocation("{id}", {x}, {y})' GObject_setSize = 'GObject.setSize("{id}", {width}, {height})' GObject_setAntialiasing = 'GObject.setAntialiasing({value!b})' GObject_setFilled = 'GObject.setFilled("{id}", {flag!b})' GObject_setFillColor = 'GObject.setFillColor("{id}", "{color}")' GInteractor_isEnabled = 'GInteractor.isEnabled("{id}")' # TODO: special GInteractor_setEnabled = 'GInteractor.setEnabled("{id}", {value!b})' GInteractor_setFont = 'GInteractor.setFont("{id}", "{font!u}")' GInteractor_setIcon = 'GInteractor.setIcon("{id}", {filename!q})' GInteractor_setMnemonic = 'GInteractor.setMnemonic("{id}", {mnemonic})' # TODO: special GInteractor_setText = 'GInteractor.setText("{id}", {text!u})' GInteractor_setTextPosition = 'GInteractor.setTextPosition("{id}", {horizontal}, {vertical})' GInteractor_setTooltip = 'GInteractor.setTooltip("{id}", {tooltip_text!q})' GRect_constructor = 'GRect.create("{id}", {width}, {height})' GRoundRect_constructor = 'GRoundRect.create("{id}", {width}, {height}, {corner})' G3DRect_constructor = 'G3DRect.create("{id}", {width}, {height}, {raised!b})' G3DRect_setRaised = 'G3DRect.setRaised("{id}", {raised!b})' GOval_constructor = 'GOval.create("{id}", {width}, {height})' GArc_constructor = 'GArc.create("{id}", {width}, {height}, {start}, {sweep})' GArc_setStartAngle = 'GArc.setStartAngle("{id}", {angle})' GArc_setSweepAngle = 'GArc.setSweepAngle("{id}", {angle})' GArc_setFrameRectangle = 'GArc.setFrameRectangle("{id}", {x}, {y}, {width}, {height})' # TODO: special GLine_constructor = 'GLine.create("{id}", {x1}, {y1}, {x2}, {y2})' GLine_setStartPoint = 'GLine.setStartPoint("{id}", {x}, {y})' # TODO special GLine_setEndPoint = 'GLine.setEndPoint("{id}", {x}, {y})' GImage_constructor = 'GImage.create("{id}", "{filename}")' # TODO: special GLabel_constructor = 'GLabel.create("{id}", {label!q})' GLabel_setFont = 'GLabel.setFont("{id}", "{font}")' GLabel_setLabel = 'GLabel.setLabel("{id}", {label!q})' GLabel_getFontAscent = 'GLabel.getFontAscent("{id}")' # TODO: special GLabel_getFontDescent = 'GLabel.getFontDescent("{id}")' # TODO: special GLabel_getSize = 'GLabel.getGLabelSize("{id}")' # TODO: special GPolygon_constructor = 'GPolygon.create("{id}")' GPolygon_addVertex = 'GPolygon.addVertex("{id}", {x}, {y})' # TODO: special DiffImage_compareImages = 'DiffImage.compareImages({file1!q}, {file2!q}, {outfile!q})' DiffImage_compareWindowToImage = 'DiffImage.compareWindowToImage("{id}", {file2!q}, {ignore_winodw_size!b})' DiffImage_show = 'DiffImage.show({file1!q}, {file2!q})' GBufferedImage_constructor = 'GBufferedImage.create("{id}", {x}, {y}, {width}, {height}, {rgb})' # TODO special and round GBufferedImage_fill = 'GBufferedImage.fill("{id}", {rgb})' GBufferedImage_fillRegion = 'GBufferedImage.fillRegion("{id}", {x}, {y}, {width}, {height}, {rgb})' # TODO rounding GBufferedImage_load = 'GBufferedImage.load("{id}", {filename!q})' GBufferedImage_resize = 'GBufferedImage.resize("{id}", {width}, {height}, {retain!b})' # TODO: round GBufferedImage_save = 'GBufferedImage.save("{id}", {filename!q})' GBufferedImage_setRGB = 'GBufferedImage.setRGB("{id}", {x}, {y}, {rgb})' # TODO round GBufferedImage_updateAllPixels = 'GBufferedImage.updateAllPixels("{id}", "{base64}")' # SECTION: GInteractor GInteractor_setAccelerator = 'GInteractor.setAccelerator("{id}", {accelerator!u})' GInteractor_setActionCommand = 'GInteractor.setActionCommand("{id}", {cmd!q})' GInteractor_setBackground = 'GInteractor.setBackground("{id}", "{color}")' GInteractor_addActionListener = 'GInteractor.addActionListener("{id}")' GInteractor_removeActionListener = 'GInteractor.removeActionListener("{id}")' GInteractor_requestFocus = 'GInteractor.requestFocus("{id}")' GInteractor_getFont = 'GInteractor.getFont("{id}")' # TODO: special GInteractor_getMnemonic = 'GInteractor.getMnemonic("{id}")' # TODO: special GInteractor_getSize = 'GInteractor.getSize("{id}")' # TODO: special GButton_constructor = 'GButton.create("{id}", {label!q})' # TODO: special GCheckBox_constructor = 'GCheckBox.create("{id}", {label!q})' GCheckBox_isSelected = 'GCheckBox.isSelected("{id}")' # TODO: special GCheckBox_setSelected = 'GCheckBox.setSelected("{id}", {state!b})' GRadioButton_constructor = 'GRadioButton.create("{id}", {label!q}, {group!q})' GRadioButton_isSelected = 'GRadioButton.isSelected("{id}")' # TODO: special GRadioButton_setSelected = 'GRadioButton.setSelected("{id}", {state!b})' GSlider_constructor = 'GSlider.create("{id}", {min}, {max}, {value})' GSlider_getMajorTickSpacing = 'GSlider.getMajorTickSpacing("{id}")' # TODO: special GSlider_getMinorTickSpacing = 'GSlider.getMinorTickSpacing("{id}")' # TODO: special GSlider_getPaintLabels = 'GSlider.getPaintLabels("{id}")' # TODO: special GSlider_getPaintTicks = 'GSlider.getPaintTicks("{id}")' # TODO: special GSlider_getSnapToTicks = 'GSlider.getSnapToTicks("{id}")' # TODO: special GSlider_getValue = 'GSlider.getValue("{id}")' # TODO: special GSlider_setMajorTickSpacing = 'GSlider.setMajorTickSpacing("{id}", {value})' GSlider_setMinorTickSpacing = 'GSlider.setMinorTickSpacing("{id}", {value})' GSlider_setPaintLabels = 'GSlider.setPaintLabels("{id}", {value!b})' GSlider_setPaintTicks = 'GSlider.setPaintTicks("{id}", {value!b})' GSlider_setSnapToTicks = 'GSlider.setSnapToTicks("{id}", {value!b})' GSlider_setValue = 'GSlider.setValue("{id}", {value})' GTable_constructor = 'GTable.create("{id}", {num_rows}, {num_cols}, {x}, {y}, {width}, {height})' # TODO: special GTable_autofitColumnWidths = 'GTable.autofitColumnWidths("{id}")' GTable_clear = 'GTable.clear("{id}")' GTable_clearFormatting = 'GTable.clearFormatting("{id}")' GTable_get = 'GTable.get("{id}", {row}, {column})' # TODO: special GTable_getColumnWidth = 'GTable.getColumnWidth("{id}", {column})' # TODO: special GTable_getSelection = 'GTable.getSelection("{id}")' # TODO: special GTable_resize = 'GTable.resize("{id}", {num_rows}, {num_cols})' # TODO: special GTable_select = 'GTable.select("{id}", {row}, {column})' GTable_set = 'GTable.set("{id}", {row}, {column}, {value!q})' GTable_setCellAlignment = 'GTable.setCellAlignment("{id}", {row}, {column}, {align})' GTable_setCellBackground = 'GTable.setCellBackground("{id}", {row}, {column}, {color!q})' GTable_setCellFont = 'GTable.setCellFont("{id}", {row}, {column}, {font!q})' GTable_setCellForeground = 'GTable.setCellForeground("{id}", {row}, {column}, {color!q}))' GTable_setColumnAlignment = 'GTable.setColumnAlignment("{id}", {column}, {align}))' GTable_setColumnBackground = 'GTable.setColumnBackground("{id}", {column}, {color!q})' GTable_setColumnFont = 'GTable.setColumnFont("{id}", {column}, {font!q})' GTable_setColumnForeground = 'GTable.setColumnForeground("{id}", {column}, {color!q})' GTable_setColumnHeaderStyle = 'GTable.setColumnHeaderStyle("{id}", {style})' GTable_setColumnWidth = 'GTable.setColumnWidth("{id}", {column}, {width})' GTable_setEditable = 'GTable.setEditable("{id}", {editable!b})' GTable_setEditorValue = 'GTable.setEditorValue("{id}", {row}, {column}, {value!q})' GTable_setEventEnabled = 'GTable.setEventEnabled("{id}", {type}, {enabled!b})' GTable_setFont = 'GTable.setFont("{id}", {font!q})' GTable_setHorizontalAlignment = 'GTable.setHorizontalAlignment("{id}", {alignment!q})' GTable_setRowAlignment = 'GTable.setRowAlignment("{id}", {row}, {align})' GTable_setRowBackground = 'GTable.setRowBackground("{id}", {row}, {color!q})' GTable_setRowColumnHeadersVisible = 'GTable.setRowColumnHeadersVisible("{id}", {visible!b})' GTable_setRowFont = 'GTable.setRowFont("{id}", {row}, {font!q})' GTable_setRowForeground = 'GTable.setRowForeground("{id}", {row}, {color!q})' GTextArea_constructor = 'GTextArea.create("{id}", {width}, {height})' GTextArea_getText = 'GTextArea.getText("{id}")' # TODO: special GTextArea_setEditable = 'GTextArea.setEditable("{id}", {editable!b})' GTextArea_setFont = 'GTextArea.setFont("{id}", {font!q})' GTextArea_setText = 'GTextArea.setText("{id}", {text!q})' GTextField_constructor = 'GTextField.create("{id}", {num_chars})' # TODO: special GTextField_getText = 'GTextField.getText("{id}")' # TODO: special GTextField_isEditable = 'GTextField.isEditable("{id}")' # TODO: special GTextField_setEditable = 'GTextField.setEditable("{id}", {editable!b})' GTextField_setPlaceholder = 'GTextField.setPlaceholder("{id}", {text!q})' GTextField_setText = 'GTextField.setText("{id}", {text!q})' GChooser_constructor = 'GChooser.create("{id}")' #TODO: special GChooser_addItem = 'GChooser.addItem("{id}", {item!q})' GChooser_getSelectedItem = 'GChooser.getSelectedItem("{id}")' # TODO: special GChooser_setSelectedItem = 'GChooser.setSelectedItem("{id}", {item!q})' # END SECTION: GInteractor GEvent_getNextEvent = 'GEvent.getNextEvent({mask})' # TODO: special GEvent_waitForEvent = 'GEvent.waitForEvent({mask})' # TODO: special GFileChooser_showOpenDialog = 'GFileChooser.showOpenDialog({current_dir!q}, {file_filter!q})' # TODO: special GFileChooser_showSaveDialog = 'GFileChooser.showSaveDialog({current_dir!q}, {file_filter!q})' # TODO: special GOptionPane_showConfirmDialog = 'GOptionPane.showConfirmDialog({message!u}, {title!u}, {type})' # TODO: special GOptionPane_showInputDialog = 'GOptionPane.showInputDialog({message!u}, {title!u})' # TODO: special GOptionPane_showMessageDialog = 'GOptionPane.showMessageDialog({message!u}, {title!u}, {type})' # TODO: special GOptionPane_showOptionDialog = 'GOptionPane.showOptionDialog({message!u}, {title!u}, {options}, {initially_selected!q})' #TODO: very special GOptionPane_showTextFileDialog = 'GOptionPane.showTextFileDialog({message!u}, {title!u}, {rows}, {cols})' # TODO: special Clipboard_get = 'Clipboard.get()' # TODO: special Clipboard_set = 'Clipboard.set({text!u})' # Platform::cpplib_setCppLibraryVersion # Platform::cpplib_getCppLibraryVersion SPL_getJavaBackEndVersion = 'StanfordCppLib.getJbeVersion()' # TODO: special # JBEConsole_isBlocked = 'JBEConsole.isBlocked()' JBEConsole_print = 'JBEConsole.print({line!q}, {stderr!b})' # TODO: special JBEConsole_getLine = 'JBEConsole.getLine()' # TODO: special JBEConsole_clear = 'JBEConsole.clear()' JBEConsole_minimize = 'JBEConsole.minimize()' JBEConsole_setFont = 'JBEConsole.setFont({font})' JBEConsole_setSize = 'JBEConsole.setSize({width}, {height})' JBEConsole_setTitle = 'JBEConsole.setTitle({title!q})' JBEConsole_setLocation = 'JBEConsole.setLocation({x}, {y})' JBEConsole_setCloseOperation = 'JBEConsole.setCloseOperation({value})' JBEConsole_setErrorColor = 'JBEConsole.setErrorColor({color!q})' JBEConsole_setExitProgramOnClose = 'JBEConsole.setExitProgramOnClose({value!b})' JBEConsole_setLocationSaved = 'JBEConsole.setLocationSaved({value!b})' JBEConsole_setOutputColor = 'JBEConsole.setOutputColor({color!q})' JBEConsole_setVisible = 'JBEConsole.setVisible({value!b})' JBEConsole_toFront = 'JBEConsole.toFront()' Note_play = 'Note.play({note!u})' # TODO: special AutograderInput_addButton = 'AutograderInput.addButton({text!u}, {input!u})' # TODO: special AutograderInput_removeButton = 'AutograderInput.removeButton({text!u})' AutograderInput_addCategory = 'AutograderInput.addCategory({name!u})' AutograderInput_removeCategory = 'AutograderInput.removeCategory({name!u})' AutograderInput_setVisible = 'AutograderInput.setVisible({visible!b})' AutograderUnitTest_addTest = 'AutograderUnitTest.addTest({test_name!u}, {category!u}, {style_check!b})' AutograderUnitTest_catchExceptions = 'AutograderUnitTest.catchExceptions()' # TODO: special AutograderUnitTest_clearTests = 'AutograderUnitTest.clearTests({style_check!b})' AutograderUnitTest_clearTestResults = 'AutograderUnitTest.clearTestResults({style_check!b})' AutograderUnitTest_isChecked = 'AutograderUnitTest.isChecked({full_test_name!u})' # TODO special AutograderUnitTest_setChecked = 'AutograderUnitTest.setChecked({full_test_name!u}, {checked!b})' AutograderUnitTest_setTestCounts = 'AutograderUnitTest.setTestCounts({pass_count}, {test_count}, {style_check!b})' AutograderUnitTest_setTestDetails = 'AutograderUnitTest.setTestDetails({test_full_name!u}, {deets!u}, {style_check!b})' AutograderUnitTest_setTestingCompleted = 'AutograderUnitTest.setTestingCompleted({completed!b}, {style_check!b})' AutograderUnitTest_setTestResult = 'AutograderUnitTest.setTestResult({test_full_name!u}, {result!u}, {style_check!b})' AutograderUnitTest_setTestRuntime = 'AutograderUnitTest.setTestRuntime({test_full_name}, {runtime_ms})' AutograderUnitTest_setVisible = 'AutograderUnitTest.setVisible({visible!b}, {style_check!b})' AutograderUnitTest_setWindowDescriptionText = 'AutograderUnitTest.setWindowDescriptionText({text!u}, {style_check!b})'
56.070552
141
0.743914
""" Java Backend Format Strings The following section lists format strings for the Java backend, and can/ should be updated as the text API to the Stanford Portable Library changes. The strings are marked using keyword format syntax, which can be expanded by keyword in Python """ # Platform::filelib_fileExists # Platform::filelib_isFile # Platform::filelib_isSymbolicLink # Platform::filelib_isDirectory # Platform::filelib_setCurrentDirectory # Platform::filelib_getCurrentDirectory # Platform::filelib_getTempDirectory # Platform::filelib_createDirectory # Platform::filelib_deleteFile # Platform::filelib_getDirectoryPathSeparator # Platform::filelib_getSearchPathSeparator # Platform::filelib_expandPathname # Platform::filelib_listDirectory # Platform::filelib_fileExists # Platform::filelib_isFile # Platform::filelib_isSymbolicLink # Platform::filelib_isDirectory # Platform::filelib_setCurrentDirectory # Platform::filelib_getCurrentDirectory # Platform::filelib_getTempDirectory # Platform::filelib_createDirectory # Platform::filelib_deleteFile # Platform::filelib_getDirectoryPathSeparator # Platform::filelib_getSearchPathSeparator # Platform::filelib_expandPathname # Platform::filelib_listDirectory # Platform::setStackSize # Platform::os_getLastError # Platform::regex_match # Platform::regex_matchCount # Platform::regex_matchCountWithLines # Platform::regex_replace # Transfer to functions: DONE: # File_ # TODO: special File_openFileDialog = 'File.openFileDialog("{title!q}", "{mode}", "{path!q}")' # TODO check if needs to be quoted GWindow_constructor = 'GWindow.create("{id}", {width}, {height}, "{top_compound}", {visible!b})' GWindow_delete = 'GWindow.delete("{id}")' GWindow_close = 'GWindow.close("{id}")' GWindow_requestFocus = 'GWindow.requestFocus("{id}")' GWindow_setExitOnClose = 'GWindow.setExitOnClose("{id}", {value!b})' GWindow_clear = 'GWindow.clear("{id}")' GWindow_clearCanvas = 'GWindow.clearCanvas("{id}")' GWindow_repaint = 'GWindow.repaint("{id}")' GWindow_saveCanvasPixels = 'GWindow.saveCanvasPixels("{id}", {filename!q}' GWindow_setSize = 'GWindow.setSize("{id}", {width}, {height})' GWindow_setCanvasSize = 'GWindow.setCanvasSize("{id}", {width}, {height})' GWindow_setCloseOperation = 'GWindow.setCloseOperation("{id}", {op}' GWindow_minimize = 'GWindow.minimize("{id}")' GWindow_pack = 'GWindow.pack("{id}")' GWindow_setTitle = 'GWindow.setTitle("{id}", {title!q})' GWindow_setLocation = 'GWindow.setLocation("{id}", {x}, {y})' GWindow_setLocationSaved = 'GWindow.setLocationSaved("{id}", {value!b})' GWindow_setPixel = 'GWindow.setPixel("{id}", {x}, {y}, {rgb}, {repaint!b})' GWindow_setPixels = 'GWindow.setPixels("{id}", {base64!q})' # TODO: Special GWindow_toBack = 'GWindow.toBack("{id}")' GWindow_toFront = 'GWindow.toFront("{id}")' GWindow_getScreenHeight = 'GWindow.getScreenHeight()' GWindow_getScreenSize = 'GWindow.getScreenSize()' GWindow_getScreenWidth = 'GWindow.getScreenWidth()' GWindow_draw = 'GWindow.draw("{id}", "{gobj_id}")' GWindow_drawInBackground = 'GWindow.drawInBackground("{id}", "{gobj_id}")' GWindow_exitGraphics = 'GWindow.exitGraphics()' # TODO: special GWindow_setRegionAlignment = 'GWindow.setRegionAlignment("{id}", "{region}", "{align}")' GWindow_setResizable = 'GWindow.setResizable("{id}", {value!b})' GWindow_addToRegion = 'GWindow.addToRegion("{id}", "{gobj_id}", "{region}")' GWindow_getLocation = 'GWindow.getLocation("{id}")' # TODO special GWindow_getPixel = 'GWindow.getPixel("{id}", {x}, {y})' # TODO special GWindow_getPixels = 'GWindow.getPixels("{id}")' # TODO special GWindow_getRegionSize = 'GWindow.getRegionSize("{id}", "{region}")' # TODO: special GWindow_removeFromRegion = 'GWindow.removeFromRegion("{id}", "{gobj_id}", "{region}")' GWindow_getSize = 'GWindow.getSize("{id}")' # TODO special GWindow_getCanvasSize = 'GWindow.getCanvasSize("{id}")' # TODO: special GWindow_getContentPaneSize = 'GWindow.getContentPaneSize("{id}")' # TODO: special GWindow_setVisible = 'GWindow.setVisible("{id}", {flag!b})' GTimer_constructor = 'GTimer.create("{id}", {millis})' GTimer_delete = 'GTimer.deleteTimer("{id}")' GTimer_start = 'GTimer.startTimer("{id}")' GTimer_pause = 'GTimer.pause({millis})' GTimer_stop = 'GTimer.stopTimer("{id}")' HttpServer_sendResponse = 'HttpServer.sendResponse({request_id}, {http_error_code}, {contentType!q}, {responseText!q})' HttpServer_sendResponseFile = 'HttpServer.sendResponseFile({request_id}, {content_type!q}, {response_file_path!q})' HttpServer_start = 'HttpServer.start({port})' HttpServer_stop = 'HttpServer.stop()' Sound_constructor = 'Sound.create("{id}", {filename!q})' Sound_delete = 'Sound.delete("{id}")' Sound_play = 'Sound.play("{id}")' # Platform::url_download GCompound_constructor = 'GCompound.create("{id}")' GCompound_add = 'GCompound.add("{compound_id}", "{gobj_id}")' GObject_delete = 'GObject.delete("{id}")' GObject_remove = 'GObject.remove("{id}")' GObject_sendForward = 'GObject.sendForward("{id}")' GObject_sendToFront = 'GObject.sendToFront("{id}")' GObject_sendBackward = 'GObject.sendBackward("{id}")' GObject_sendToBack = 'GObject.sendToBack("{id}")' GObject_setVisible = 'GObject.setVisible("{id}", {flag!b})' GObject_setColor = 'GObject.setColor("{id}", "{color}")' GObject_scale = 'GObject.scale("{id}", {sx}, {sy})' GObject_rotate = 'GObject.rotate("{id}", {theta})' GObject_contains = 'GObject.contains("{id}", {x}, {y})' # TODO: special move into gobjects.py GObject_getBounds = 'GObject.getBounds("{id}")' # TODO: special GObject_setLineWidth = 'GObject.setLineWidth("{id}", {line_width})' GObject_setLocation = 'GObject.setLocation("{id}", {x}, {y})' GObject_setSize = 'GObject.setSize("{id}", {width}, {height})' GObject_setAntialiasing = 'GObject.setAntialiasing({value!b})' GObject_setFilled = 'GObject.setFilled("{id}", {flag!b})' GObject_setFillColor = 'GObject.setFillColor("{id}", "{color}")' GInteractor_isEnabled = 'GInteractor.isEnabled("{id}")' # TODO: special GInteractor_setEnabled = 'GInteractor.setEnabled("{id}", {value!b})' GInteractor_setFont = 'GInteractor.setFont("{id}", "{font!u}")' GInteractor_setIcon = 'GInteractor.setIcon("{id}", {filename!q})' GInteractor_setMnemonic = 'GInteractor.setMnemonic("{id}", {mnemonic})' # TODO: special GInteractor_setText = 'GInteractor.setText("{id}", {text!u})' GInteractor_setTextPosition = 'GInteractor.setTextPosition("{id}", {horizontal}, {vertical})' GInteractor_setTooltip = 'GInteractor.setTooltip("{id}", {tooltip_text!q})' GRect_constructor = 'GRect.create("{id}", {width}, {height})' GRoundRect_constructor = 'GRoundRect.create("{id}", {width}, {height}, {corner})' G3DRect_constructor = 'G3DRect.create("{id}", {width}, {height}, {raised!b})' G3DRect_setRaised = 'G3DRect.setRaised("{id}", {raised!b})' GOval_constructor = 'GOval.create("{id}", {width}, {height})' GArc_constructor = 'GArc.create("{id}", {width}, {height}, {start}, {sweep})' GArc_setStartAngle = 'GArc.setStartAngle("{id}", {angle})' GArc_setSweepAngle = 'GArc.setSweepAngle("{id}", {angle})' GArc_setFrameRectangle = 'GArc.setFrameRectangle("{id}", {x}, {y}, {width}, {height})' # TODO: special GLine_constructor = 'GLine.create("{id}", {x1}, {y1}, {x2}, {y2})' GLine_setStartPoint = 'GLine.setStartPoint("{id}", {x}, {y})' # TODO special GLine_setEndPoint = 'GLine.setEndPoint("{id}", {x}, {y})' GImage_constructor = 'GImage.create("{id}", "{filename}")' # TODO: special GLabel_constructor = 'GLabel.create("{id}", {label!q})' GLabel_setFont = 'GLabel.setFont("{id}", "{font}")' GLabel_setLabel = 'GLabel.setLabel("{id}", {label!q})' GLabel_getFontAscent = 'GLabel.getFontAscent("{id}")' # TODO: special GLabel_getFontDescent = 'GLabel.getFontDescent("{id}")' # TODO: special GLabel_getSize = 'GLabel.getGLabelSize("{id}")' # TODO: special GPolygon_constructor = 'GPolygon.create("{id}")' GPolygon_addVertex = 'GPolygon.addVertex("{id}", {x}, {y})' # TODO: special DiffImage_compareImages = 'DiffImage.compareImages({file1!q}, {file2!q}, {outfile!q})' DiffImage_compareWindowToImage = 'DiffImage.compareWindowToImage("{id}", {file2!q}, {ignore_winodw_size!b})' DiffImage_show = 'DiffImage.show({file1!q}, {file2!q})' GBufferedImage_constructor = 'GBufferedImage.create("{id}", {x}, {y}, {width}, {height}, {rgb})' # TODO special and round GBufferedImage_fill = 'GBufferedImage.fill("{id}", {rgb})' GBufferedImage_fillRegion = 'GBufferedImage.fillRegion("{id}", {x}, {y}, {width}, {height}, {rgb})' # TODO rounding GBufferedImage_load = 'GBufferedImage.load("{id}", {filename!q})' GBufferedImage_resize = 'GBufferedImage.resize("{id}", {width}, {height}, {retain!b})' # TODO: round GBufferedImage_save = 'GBufferedImage.save("{id}", {filename!q})' GBufferedImage_setRGB = 'GBufferedImage.setRGB("{id}", {x}, {y}, {rgb})' # TODO round GBufferedImage_updateAllPixels = 'GBufferedImage.updateAllPixels("{id}", "{base64}")' # SECTION: GInteractor GInteractor_setAccelerator = 'GInteractor.setAccelerator("{id}", {accelerator!u})' GInteractor_setActionCommand = 'GInteractor.setActionCommand("{id}", {cmd!q})' GInteractor_setBackground = 'GInteractor.setBackground("{id}", "{color}")' GInteractor_addActionListener = 'GInteractor.addActionListener("{id}")' GInteractor_removeActionListener = 'GInteractor.removeActionListener("{id}")' GInteractor_requestFocus = 'GInteractor.requestFocus("{id}")' GInteractor_getFont = 'GInteractor.getFont("{id}")' # TODO: special GInteractor_getMnemonic = 'GInteractor.getMnemonic("{id}")' # TODO: special GInteractor_getSize = 'GInteractor.getSize("{id}")' # TODO: special GButton_constructor = 'GButton.create("{id}", {label!q})' # TODO: special GCheckBox_constructor = 'GCheckBox.create("{id}", {label!q})' GCheckBox_isSelected = 'GCheckBox.isSelected("{id}")' # TODO: special GCheckBox_setSelected = 'GCheckBox.setSelected("{id}", {state!b})' GRadioButton_constructor = 'GRadioButton.create("{id}", {label!q}, {group!q})' GRadioButton_isSelected = 'GRadioButton.isSelected("{id}")' # TODO: special GRadioButton_setSelected = 'GRadioButton.setSelected("{id}", {state!b})' GSlider_constructor = 'GSlider.create("{id}", {min}, {max}, {value})' GSlider_getMajorTickSpacing = 'GSlider.getMajorTickSpacing("{id}")' # TODO: special GSlider_getMinorTickSpacing = 'GSlider.getMinorTickSpacing("{id}")' # TODO: special GSlider_getPaintLabels = 'GSlider.getPaintLabels("{id}")' # TODO: special GSlider_getPaintTicks = 'GSlider.getPaintTicks("{id}")' # TODO: special GSlider_getSnapToTicks = 'GSlider.getSnapToTicks("{id}")' # TODO: special GSlider_getValue = 'GSlider.getValue("{id}")' # TODO: special GSlider_setMajorTickSpacing = 'GSlider.setMajorTickSpacing("{id}", {value})' GSlider_setMinorTickSpacing = 'GSlider.setMinorTickSpacing("{id}", {value})' GSlider_setPaintLabels = 'GSlider.setPaintLabels("{id}", {value!b})' GSlider_setPaintTicks = 'GSlider.setPaintTicks("{id}", {value!b})' GSlider_setSnapToTicks = 'GSlider.setSnapToTicks("{id}", {value!b})' GSlider_setValue = 'GSlider.setValue("{id}", {value})' GTable_constructor = 'GTable.create("{id}", {num_rows}, {num_cols}, {x}, {y}, {width}, {height})' # TODO: special GTable_autofitColumnWidths = 'GTable.autofitColumnWidths("{id}")' GTable_clear = 'GTable.clear("{id}")' GTable_clearFormatting = 'GTable.clearFormatting("{id}")' GTable_get = 'GTable.get("{id}", {row}, {column})' # TODO: special GTable_getColumnWidth = 'GTable.getColumnWidth("{id}", {column})' # TODO: special GTable_getSelection = 'GTable.getSelection("{id}")' # TODO: special GTable_resize = 'GTable.resize("{id}", {num_rows}, {num_cols})' # TODO: special GTable_select = 'GTable.select("{id}", {row}, {column})' GTable_set = 'GTable.set("{id}", {row}, {column}, {value!q})' GTable_setCellAlignment = 'GTable.setCellAlignment("{id}", {row}, {column}, {align})' GTable_setCellBackground = 'GTable.setCellBackground("{id}", {row}, {column}, {color!q})' GTable_setCellFont = 'GTable.setCellFont("{id}", {row}, {column}, {font!q})' GTable_setCellForeground = 'GTable.setCellForeground("{id}", {row}, {column}, {color!q}))' GTable_setColumnAlignment = 'GTable.setColumnAlignment("{id}", {column}, {align}))' GTable_setColumnBackground = 'GTable.setColumnBackground("{id}", {column}, {color!q})' GTable_setColumnFont = 'GTable.setColumnFont("{id}", {column}, {font!q})' GTable_setColumnForeground = 'GTable.setColumnForeground("{id}", {column}, {color!q})' GTable_setColumnHeaderStyle = 'GTable.setColumnHeaderStyle("{id}", {style})' GTable_setColumnWidth = 'GTable.setColumnWidth("{id}", {column}, {width})' GTable_setEditable = 'GTable.setEditable("{id}", {editable!b})' GTable_setEditorValue = 'GTable.setEditorValue("{id}", {row}, {column}, {value!q})' GTable_setEventEnabled = 'GTable.setEventEnabled("{id}", {type}, {enabled!b})' GTable_setFont = 'GTable.setFont("{id}", {font!q})' GTable_setHorizontalAlignment = 'GTable.setHorizontalAlignment("{id}", {alignment!q})' GTable_setRowAlignment = 'GTable.setRowAlignment("{id}", {row}, {align})' GTable_setRowBackground = 'GTable.setRowBackground("{id}", {row}, {color!q})' GTable_setRowColumnHeadersVisible = 'GTable.setRowColumnHeadersVisible("{id}", {visible!b})' GTable_setRowFont = 'GTable.setRowFont("{id}", {row}, {font!q})' GTable_setRowForeground = 'GTable.setRowForeground("{id}", {row}, {color!q})' GTextArea_constructor = 'GTextArea.create("{id}", {width}, {height})' GTextArea_getText = 'GTextArea.getText("{id}")' # TODO: special GTextArea_setEditable = 'GTextArea.setEditable("{id}", {editable!b})' GTextArea_setFont = 'GTextArea.setFont("{id}", {font!q})' GTextArea_setText = 'GTextArea.setText("{id}", {text!q})' GTextField_constructor = 'GTextField.create("{id}", {num_chars})' # TODO: special GTextField_getText = 'GTextField.getText("{id}")' # TODO: special GTextField_isEditable = 'GTextField.isEditable("{id}")' # TODO: special GTextField_setEditable = 'GTextField.setEditable("{id}", {editable!b})' GTextField_setPlaceholder = 'GTextField.setPlaceholder("{id}", {text!q})' GTextField_setText = 'GTextField.setText("{id}", {text!q})' GChooser_constructor = 'GChooser.create("{id}")' #TODO: special GChooser_addItem = 'GChooser.addItem("{id}", {item!q})' GChooser_getSelectedItem = 'GChooser.getSelectedItem("{id}")' # TODO: special GChooser_setSelectedItem = 'GChooser.setSelectedItem("{id}", {item!q})' # END SECTION: GInteractor GEvent_getNextEvent = 'GEvent.getNextEvent({mask})' # TODO: special GEvent_waitForEvent = 'GEvent.waitForEvent({mask})' # TODO: special GFileChooser_showOpenDialog = 'GFileChooser.showOpenDialog({current_dir!q}, {file_filter!q})' # TODO: special GFileChooser_showSaveDialog = 'GFileChooser.showSaveDialog({current_dir!q}, {file_filter!q})' # TODO: special GOptionPane_showConfirmDialog = 'GOptionPane.showConfirmDialog({message!u}, {title!u}, {type})' # TODO: special GOptionPane_showInputDialog = 'GOptionPane.showInputDialog({message!u}, {title!u})' # TODO: special GOptionPane_showMessageDialog = 'GOptionPane.showMessageDialog({message!u}, {title!u}, {type})' # TODO: special GOptionPane_showOptionDialog = 'GOptionPane.showOptionDialog({message!u}, {title!u}, {options}, {initially_selected!q})' #TODO: very special GOptionPane_showTextFileDialog = 'GOptionPane.showTextFileDialog({message!u}, {title!u}, {rows}, {cols})' # TODO: special Clipboard_get = 'Clipboard.get()' # TODO: special Clipboard_set = 'Clipboard.set({text!u})' # Platform::cpplib_setCppLibraryVersion # Platform::cpplib_getCppLibraryVersion SPL_getJavaBackEndVersion = 'StanfordCppLib.getJbeVersion()' # TODO: special # JBEConsole_isBlocked = 'JBEConsole.isBlocked()' JBEConsole_print = 'JBEConsole.print({line!q}, {stderr!b})' # TODO: special JBEConsole_getLine = 'JBEConsole.getLine()' # TODO: special JBEConsole_clear = 'JBEConsole.clear()' JBEConsole_minimize = 'JBEConsole.minimize()' JBEConsole_setFont = 'JBEConsole.setFont({font})' JBEConsole_setSize = 'JBEConsole.setSize({width}, {height})' JBEConsole_setTitle = 'JBEConsole.setTitle({title!q})' JBEConsole_setLocation = 'JBEConsole.setLocation({x}, {y})' JBEConsole_setCloseOperation = 'JBEConsole.setCloseOperation({value})' JBEConsole_setErrorColor = 'JBEConsole.setErrorColor({color!q})' JBEConsole_setExitProgramOnClose = 'JBEConsole.setExitProgramOnClose({value!b})' JBEConsole_setLocationSaved = 'JBEConsole.setLocationSaved({value!b})' JBEConsole_setOutputColor = 'JBEConsole.setOutputColor({color!q})' JBEConsole_setVisible = 'JBEConsole.setVisible({value!b})' JBEConsole_toFront = 'JBEConsole.toFront()' Note_play = 'Note.play({note!u})' # TODO: special AutograderInput_addButton = 'AutograderInput.addButton({text!u}, {input!u})' # TODO: special AutograderInput_removeButton = 'AutograderInput.removeButton({text!u})' AutograderInput_addCategory = 'AutograderInput.addCategory({name!u})' AutograderInput_removeCategory = 'AutograderInput.removeCategory({name!u})' AutograderInput_setVisible = 'AutograderInput.setVisible({visible!b})' AutograderUnitTest_addTest = 'AutograderUnitTest.addTest({test_name!u}, {category!u}, {style_check!b})' AutograderUnitTest_catchExceptions = 'AutograderUnitTest.catchExceptions()' # TODO: special AutograderUnitTest_clearTests = 'AutograderUnitTest.clearTests({style_check!b})' AutograderUnitTest_clearTestResults = 'AutograderUnitTest.clearTestResults({style_check!b})' AutograderUnitTest_isChecked = 'AutograderUnitTest.isChecked({full_test_name!u})' # TODO special AutograderUnitTest_setChecked = 'AutograderUnitTest.setChecked({full_test_name!u}, {checked!b})' AutograderUnitTest_setTestCounts = 'AutograderUnitTest.setTestCounts({pass_count}, {test_count}, {style_check!b})' AutograderUnitTest_setTestDetails = 'AutograderUnitTest.setTestDetails({test_full_name!u}, {deets!u}, {style_check!b})' AutograderUnitTest_setTestingCompleted = 'AutograderUnitTest.setTestingCompleted({completed!b}, {style_check!b})' AutograderUnitTest_setTestResult = 'AutograderUnitTest.setTestResult({test_full_name!u}, {result!u}, {style_check!b})' AutograderUnitTest_setTestRuntime = 'AutograderUnitTest.setTestRuntime({test_full_name}, {runtime_ms})' AutograderUnitTest_setVisible = 'AutograderUnitTest.setVisible({visible!b}, {style_check!b})' AutograderUnitTest_setWindowDescriptionText = 'AutograderUnitTest.setWindowDescriptionText({text!u}, {style_check!b})'
0
0
0
ac37cde218154420b284a26ad457b2fee3a27de3
1,998
py
Python
ipproxytool/spiders/proxy/freeproxylists.py
txgyy/ipproxytool
59db3c4394abaf3df4a31ac35d297a1c7f929f65
[ "MIT" ]
11
2018-07-24T10:45:54.000Z
2021-06-30T08:42:18.000Z
ipproxytool/spiders/proxy/freeproxylists.py
txgyy/ipproxytool
59db3c4394abaf3df4a31ac35d297a1c7f929f65
[ "MIT" ]
3
2021-03-31T18:28:23.000Z
2022-03-02T14:54:29.000Z
ipproxytool/spiders/proxy/freeproxylists.py
txgyy/ipproxytool
59db3c4394abaf3df4a31ac35d297a1c7f929f65
[ "MIT" ]
4
2018-11-07T07:15:47.000Z
2020-04-15T14:15:18.000Z
# coding=utf-8 import urllib import re from proxy import Proxy from .basespider import BaseSpider from bs4 import BeautifulSoup
33.864407
111
0.506507
# coding=utf-8 import urllib import re from proxy import Proxy from .basespider import BaseSpider from bs4 import BeautifulSoup class FreeProxyListsSpider(BaseSpider): name = 'freeproxylists' def __init__(self, *a, **kwargs): super(FreeProxyListsSpider, self).__init__(*a, **kwargs) self.urls = [ 'http://www.freeproxylists.net/' ] self.headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Connection': 'keep-alive', 'Host': 'www.freeproxylists.net', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:50.0) Gecko/20100101 Firefox/50.0', } self.init() def parse_page(self, response): pattern = re.compile('<tr class=(.*?)</tr>', re.S) items = re.findall(pattern = pattern, string = response.body) for i, item in enumerate(items): if i > 0: if 'async' in item: continue ip_pattern = re.compile('IPDecode\(\"(.*?)\"\)', re.S) ip_decode = re.findall(ip_pattern, item)[0] ip_url = urllib.unquote(ip_decode) ip_soup = BeautifulSoup(ip_url, 'lxml') ip = ip_soup.text.encode() item = '<tr class=' + item + '</tr>' soup = BeautifulSoup(item, 'lxml') tbodys = soup.find_all('td') proxy = Proxy() proxy.set_value( ip = ip, port = tbodys[1].text.encode(), country = tbodys[4].text.encode(), anonymity = tbodys[3].text.encode(), source = self.name, ) self.add_proxy(proxy = proxy)
1,744
100
23
a8b83a04607ee8cd36a6e73180f394da0c9619ea
1,248
py
Python
tracardi/service/storage/drivers/elastic/log.py
DawidekZagajnik/tracardi
979015b7b14cb87fb639efb1eee6537932319b61
[ "MIT" ]
null
null
null
tracardi/service/storage/drivers/elastic/log.py
DawidekZagajnik/tracardi
979015b7b14cb87fb639efb1eee6537932319b61
[ "MIT" ]
null
null
null
tracardi/service/storage/drivers/elastic/log.py
DawidekZagajnik/tracardi
979015b7b14cb87fb639efb1eee6537932319b61
[ "MIT" ]
null
null
null
from tracardi.service.storage.elastic_client import ElasticClient from tracardi.service.storage.factory import storage_manager from tracardi.domain.storage_result import StorageResult from tracardi.service.storage.index import resources
33.72973
101
0.659455
from tracardi.service.storage.elastic_client import ElasticClient from tracardi.service.storage.factory import storage_manager from tracardi.domain.storage_result import StorageResult from tracardi.service.storage.index import resources async def load_all(start: int = 0, limit: int = 100) -> StorageResult: return await storage_manager('log').load_all( start, limit, sort=[{"date": {"order": "desc", "format": "strict_date_optional_time_nanos"}}]) async def load_by_query_string(query_string: str, start: int = 0, limit: int = 100) -> StorageResult: result = await storage_manager('log').query({ "query": { "query_string": { "query": query_string } }, "sort": [ {"date": {"order": "desc", "format": "strict_date_optional_time_nanos"}} ], "from": start, "size": limit }) return StorageResult(result) async def exists(): if "log" not in resources.resources: raise ConnectionError(f"Log index misconfiguration. Index does not exist.") es = ElasticClient.instance() index = resources.resources["log"] return await es.exists_index_template(name=index.get_prefixed_template_name())
939
0
69
40de51363eddccc28fd1673164d753ebb4fb9c63
2,505
py
Python
python/yugabyte_db_thirdparty/yb_build_thirdparty_main.py
ttyusupov/yugabyte-db-thirdparty
9680123cfe2d7d623e5ba2e4ed5cfbc42dbd5850
[ "CC-BY-3.0" ]
null
null
null
python/yugabyte_db_thirdparty/yb_build_thirdparty_main.py
ttyusupov/yugabyte-db-thirdparty
9680123cfe2d7d623e5ba2e4ed5cfbc42dbd5850
[ "CC-BY-3.0" ]
null
null
null
python/yugabyte_db_thirdparty/yb_build_thirdparty_main.py
ttyusupov/yugabyte-db-thirdparty
9680123cfe2d7d623e5ba2e4ed5cfbc42dbd5850
[ "CC-BY-3.0" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) Yugabyte, Inc. # # 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 applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations # under the License. # import build_definitions from build_definitions import * # noqa from yugabyte_db_thirdparty.builder import Builder from yugabyte_db_thirdparty.custom_logging import ( log_separator, heading, configure_logging, ) from yugabyte_db_thirdparty.multi_build import MultiBuilder from yugabyte_db_thirdparty.remote_build import build_remotely from yugabyte_db_thirdparty.shared_library_checking import get_lib_tester from yugabyte_db_thirdparty.download_manager import DownloadManager import json import_submodules(build_definitions) if __name__ == "__main__": main()
33.851351
99
0.741317
#!/usr/bin/env python3 # Copyright (c) Yugabyte, Inc. # # 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 applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations # under the License. # import build_definitions from build_definitions import * # noqa from yugabyte_db_thirdparty.builder import Builder from yugabyte_db_thirdparty.custom_logging import ( log_separator, heading, configure_logging, ) from yugabyte_db_thirdparty.multi_build import MultiBuilder from yugabyte_db_thirdparty.remote_build import build_remotely from yugabyte_db_thirdparty.shared_library_checking import get_lib_tester from yugabyte_db_thirdparty.download_manager import DownloadManager import json import_submodules(build_definitions) def main() -> None: configure_logging() unset_env_var_if_set('CC') unset_env_var_if_set('CXX') if 'YB_BUILD_THIRDPARTY_DUMP_ENV' in os.environ: heading('Environment of {}:'.format(sys.argv[0])) for key in os.environ: log('{}={}'.format(key, os.environ[key])) log_separator() builder = Builder() builder.parse_args() if builder.remote_build: build_remotely( remote_server=builder.args.remote_build_server, remote_build_code_path=builder.args.remote_build_dir) return if builder.args.multi_build: multi_builder = MultiBuilder(conf_name_pattern=builder.args.multi_build_conf_name_pattern) multi_builder.build() return builder.finish_initialization() builder.run() if builder.args.license_report: with open('license_report.json', 'w') as output_file: json.dump(builder.license_report, output_file, indent=2) if not builder.args.download_extract_only: # Check that the executables and libraries we have built don't depend on any unexpected # dynamic libraries installed on this system. lib_tester = get_lib_tester() lib_tester.add_allowed_shared_lib_paths(builder.additional_allowed_shared_lib_paths) lib_tester.run() if __name__ == "__main__": main()
1,305
0
23
f9230cc2630f651c77fc85d50504908444d0686f
1,195
py
Python
wikimon_bot/views/google.py
facerecog/wikimon
212be56277f711ac145972254b3fead3f92e949c
[ "MIT" ]
7
2016-05-06T12:52:20.000Z
2018-02-13T15:48:15.000Z
wikimon_bot/views/google.py
facerecog/wikimon
212be56277f711ac145972254b3fead3f92e949c
[ "MIT" ]
null
null
null
wikimon_bot/views/google.py
facerecog/wikimon
212be56277f711ac145972254b3fead3f92e949c
[ "MIT" ]
3
2017-01-14T14:25:01.000Z
2021-03-11T21:01:36.000Z
""" GoogleViews: /s(earch) <term> /i(mage) <term> youtube urls """ from ..utils import media_sender import requests, urllib
38.548387
114
0.645188
""" GoogleViews: /s(earch) <term> /i(mage) <term> youtube urls """ from ..utils import media_sender import requests, urllib class GoogleViews(): def __init__(self, interface_layer): self.image_sender = media_sender.ImageSender(interface_layer) self.video_sender = media_sender.VideoSender(interface_layer) self.yt_sender = media_sender.YoutubeSender(interface_layer) self.url_print_sender = media_sender.UrlPrintSender(interface_layer) self.routes = [ (".*https?:\/\/(?:www\.|m\.)?youtu(?:be.com\/watch\?v=|\.be/)(?P<video_id>[\w-]+)(&\S*)?$", self.send_yt_video), ("/s(earch)?\s(?P<term>[^$]+)$", self.google_search), ] def send_yt_video(self, message, match): self.yt_sender.send_by_url(jid=message.getFrom(), file_url=match.group("video_id")) def google_search(self, message, match): req = requests.get("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s" % match.group("term")) page_url = urllib.unquote(req.json()["responseData"]["results"][0]["url"]) self.url_print_sender.send_by_url(jid=message.getFrom(), file_url=page_url)
951
-1
103
d3d28355849fba837e5d0a48bc1a5239d87df296
4,355
py
Python
seisflows/solver/specfem3d.py
umairbinwaheed/seisflows
b28cd89e1b37875c2e226f30a8c14d788fa7798f
[ "BSD-2-Clause" ]
2
2021-05-12T03:28:31.000Z
2021-12-08T14:43:20.000Z
seisflows/solver/specfem3d.py
umairbinwaheed/seisflows
b28cd89e1b37875c2e226f30a8c14d788fa7798f
[ "BSD-2-Clause" ]
null
null
null
seisflows/solver/specfem3d.py
umairbinwaheed/seisflows
b28cd89e1b37875c2e226f30a8c14d788fa7798f
[ "BSD-2-Clause" ]
1
2021-12-08T14:43:49.000Z
2021-12-08T14:43:49.000Z
import subprocess from glob import glob from os.path import join import numpy as np import seisflows.seistools.specfem3d as solvertools from seisflows.seistools.shared import getpar, setpar from seisflows.tools import unix from seisflows.tools.code import exists from seisflows.tools.config import SeisflowsParameters, SeisflowsPaths, \ ParameterError, loadclass PAR = SeisflowsParameters() PATH = SeisflowsPaths() import system class specfem3d(loadclass('solver', 'base')): """ Python interface for SPECFEM3D See base class for method descriptions """ def check(self): """ Checks parameters and paths """ super(specfem3d, self).check() # check time stepping parameters if 'NT' not in PAR: raise Exception if 'DT' not in PAR: raise Exception if 'F0' not in PAR: raise Exception def generate_data(self, **model_kwargs): """ Generates data """ self.generate_mesh(**model_kwargs) unix.cd(self.getpath) setpar('SIMULATION_TYPE', '1') setpar('SAVE_FORWARD', '.true.') self.mpirun('bin/xspecfem3D') unix.mv(self.data_wildcard, 'traces/obs') self.export_traces(PATH.OUTPUT, 'traces/obs') def generate_mesh(self, model_path=None, model_name=None, model_type='gll'): """ Performs meshing and database generation """ assert(model_name) assert(model_type) self.initialize_solver_directories() unix.cd(self.getpath) if model_type in ['gll']: par = getpar('MODEL').strip() if par != 'gll': if self.getnode == 0: print 'WARNING: Unexpected Par_file setting:' print 'MODEL =', par assert(exists(model_path)) self.check_mesh_properties(model_path) src = glob(model_path +'/'+ '*') dst = self.model_databases unix.cp(src, dst) self.mpirun('bin/xmeshfem3D') self.mpirun('bin/xgenerate_databases') self.export_model(PATH.OUTPUT +'/'+ model_name) else: raise NotImplementedError ### low-level solver interface def forward(self): """ Calls SPECFEM3D forward solver """ setpar('SIMULATION_TYPE', '1') setpar('SAVE_FORWARD', '.true.') self.mpirun('bin/xgenerate_databases') self.mpirun('bin/xspecfem3D') def adjoint(self): """ Calls SPECFEM3D adjoint solver """ setpar('SIMULATION_TYPE', '3') setpar('SAVE_FORWARD', '.false.') unix.rm('SEM') unix.ln('traces/adj', 'SEM') self.mpirun('bin/xspecfem3D') ### input file writers def check_solver_parameter_files(self): """ Checks solver parameters """ nt = getpar('NSTEP', cast=int) dt = getpar('DT', cast=float) if nt != PAR.NT: if self.getnode == 0: print "WARNING: nt != PAR.NT" setpar('NSTEP', PAR.NT) if dt != PAR.DT: if self.getnode == 0: print "WARNING: dt != PAR.DT" setpar('DT', PAR.DT) if self.mesh.nproc != PAR.NPROC: if self.getnode == 0: print 'Warning: mesh.nproc != PAR.NPROC' if 'MULTIPLES' in PAR: raise NotImplementedError ### miscellaneous @property @property @property @property
25.617647
80
0.589208
import subprocess from glob import glob from os.path import join import numpy as np import seisflows.seistools.specfem3d as solvertools from seisflows.seistools.shared import getpar, setpar from seisflows.tools import unix from seisflows.tools.code import exists from seisflows.tools.config import SeisflowsParameters, SeisflowsPaths, \ ParameterError, loadclass PAR = SeisflowsParameters() PATH = SeisflowsPaths() import system class specfem3d(loadclass('solver', 'base')): """ Python interface for SPECFEM3D See base class for method descriptions """ def check(self): """ Checks parameters and paths """ super(specfem3d, self).check() # check time stepping parameters if 'NT' not in PAR: raise Exception if 'DT' not in PAR: raise Exception if 'F0' not in PAR: raise Exception def generate_data(self, **model_kwargs): """ Generates data """ self.generate_mesh(**model_kwargs) unix.cd(self.getpath) setpar('SIMULATION_TYPE', '1') setpar('SAVE_FORWARD', '.true.') self.mpirun('bin/xspecfem3D') unix.mv(self.data_wildcard, 'traces/obs') self.export_traces(PATH.OUTPUT, 'traces/obs') def generate_mesh(self, model_path=None, model_name=None, model_type='gll'): """ Performs meshing and database generation """ assert(model_name) assert(model_type) self.initialize_solver_directories() unix.cd(self.getpath) if model_type in ['gll']: par = getpar('MODEL').strip() if par != 'gll': if self.getnode == 0: print 'WARNING: Unexpected Par_file setting:' print 'MODEL =', par assert(exists(model_path)) self.check_mesh_properties(model_path) src = glob(model_path +'/'+ '*') dst = self.model_databases unix.cp(src, dst) self.mpirun('bin/xmeshfem3D') self.mpirun('bin/xgenerate_databases') self.export_model(PATH.OUTPUT +'/'+ model_name) else: raise NotImplementedError ### low-level solver interface def forward(self): """ Calls SPECFEM3D forward solver """ setpar('SIMULATION_TYPE', '1') setpar('SAVE_FORWARD', '.true.') self.mpirun('bin/xgenerate_databases') self.mpirun('bin/xspecfem3D') def adjoint(self): """ Calls SPECFEM3D adjoint solver """ setpar('SIMULATION_TYPE', '3') setpar('SAVE_FORWARD', '.false.') unix.rm('SEM') unix.ln('traces/adj', 'SEM') self.mpirun('bin/xspecfem3D') ### input file writers def check_solver_parameter_files(self): """ Checks solver parameters """ nt = getpar('NSTEP', cast=int) dt = getpar('DT', cast=float) if nt != PAR.NT: if self.getnode == 0: print "WARNING: nt != PAR.NT" setpar('NSTEP', PAR.NT) if dt != PAR.DT: if self.getnode == 0: print "WARNING: dt != PAR.DT" setpar('DT', PAR.DT) if self.mesh.nproc != PAR.NPROC: if self.getnode == 0: print 'Warning: mesh.nproc != PAR.NPROC' if 'MULTIPLES' in PAR: raise NotImplementedError def write_parameters(self): unix.cd(self.getpath) solvertools.write_parameters(vars(PAR)) def write_receivers(self): unix.cd(self.getpath) key = 'use_existing_STATIONS' val = '.true.' setpar(key, val) _, h = preprocess.load('traces/obs') solvertools.write_receivers(h.nr, h.rx, h.rz) def write_sources(self): unix.cd(self.getpath) _, h = preprocess.load(dir='traces/obs') solvertools.write_sources(vars(PAR), h) ### miscellaneous @property def data_wildcard(self): return glob('OUTPUT_FILES/*SU') @property def kernel_databases(self): return join(self.getpath, 'OUTPUT_FILES/DATABASES_MPI') @property def model_databases(self): return join(self.getpath, 'OUTPUT_FILES/DATABASES_MPI') @property def source_prefix(self): return 'FORCESOLUTION'
650
0
185
d53e3296d343fcbd5e9aedf582b891457907c88c
4,197
py
Python
tensormonk/loss/utils.py
Tensor46/TensorMONK
67617d3fdf8fde072ba9cab42de7d67c79b17494
[ "MIT" ]
29
2018-07-06T23:57:23.000Z
2022-03-08T20:38:57.000Z
tensormonk/loss/utils.py
Tensor46/TensorMONK
67617d3fdf8fde072ba9cab42de7d67c79b17494
[ "MIT" ]
3
2018-12-14T22:21:26.000Z
2020-06-19T02:13:34.000Z
tensormonk/loss/utils.py
Tensor46/TensorMONK
67617d3fdf8fde072ba9cab42de7d67c79b17494
[ "MIT" ]
8
2018-07-06T23:58:03.000Z
2021-04-12T01:35:54.000Z
""" TensorMONK :: loss :: utils """ __all__ = ["compute_n_embedding", "compute_top15", "one_hot", "one_hot_idx", "hard_negative_mask"] import torch import numpy as np @torch.no_grad() @torch.no_grad() @torch.no_grad() @torch.no_grad() def hard_negative_mask(prediction: torch.Tensor, targets: torch.Tensor, pos_to_neg_ratio: float = 0.25): r""" Hard negative mask generator for object detection (includes both positives and hard negatives). Args: prediction (torch.Tensor): label predictions of the network must be 2D/3D tensor. 2D: Two class problem with scores ranging from 0 to 1, where 0 is background. 3D: N-class predictions before softmax where F.softmax(prediction, -1)[:, :, 0] are the probabilities of background. targets (torch.Tensor): A 2D tensor of labels/targets. 0 is background. pos_to_neg_ratio (float): Ratio of positives to negatives. default = 0.25 """ assert prediction.ndim == 2 or prediction.ndim == 3, \ "hard_negative_mask: prediction must be 2D/3D tensor." assert targets.ndim == 2, \ "hard_negative_mask: targets must be 2D tensor." prediction = prediction.clone() ns = prediction.size(0) foreground_mask = targets > 0 ignore_mask = targets < 0 if prediction.shape == foreground_mask.shape: # assumes, two class problem and sigmoid is applied to output assert 1. >= prediction.max() and prediction.min() >= 0., \ "hard_negative_mask: Use torch.sigmoid(prediction)." # Mark the background_mask with hard negatives background_mask = torch.zeros_like(targets).bool() for i in range(ns): retain = max(1, int(foreground_mask[i].sum() / pos_to_neg_ratio)) probs = prediction[i] # foreground prob to minimum probs[foreground_mask[i]] = 0. # remove invalid targets probs[ignore_mask[i]] = 0. background_mask[i, torch.argsort(probs)[-retain:]] = True else: # assumes, N-class problem and softmax is not applied to output assert ~ prediction.sum(-1).eq(1).all(), \ "hard_negative_mask: Requires predictions before softmax." background_probs = torch.nn.functional.softmax(prediction, -1)[:, :, 0] # Mark the background_mask with hard negatives background_mask = torch.zeros_like(targets).bool() for i in range(ns): retain = max(1, int(foreground_mask[i].sum() / pos_to_neg_ratio)) probs = background_probs[i] # foreground prob to maximum probs[foreground_mask[i]] = 1. # remove invalid targets probs[ignore_mask[i]] = 1. background_mask[i, torch.argsort(probs)[:retain]] = True mask = foreground_mask.bool() | background_mask.bool() return mask
39.59434
79
0.630212
""" TensorMONK :: loss :: utils """ __all__ = ["compute_n_embedding", "compute_top15", "one_hot", "one_hot_idx", "hard_negative_mask"] import torch import numpy as np def compute_n_embedding(tensor_size: tuple): if isinstance(tensor_size, list) or isinstance(tensor_size, tuple): if len(tensor_size) > 1: # batch size is not required tensor_size = np.prod(tensor_size[1:]) else: tensor_size = tensor_size[0] return int(tensor_size) @torch.no_grad() def compute_top15(responses: torch.Tensor, targets: torch.Tensor): predicted = responses.topk(5, 1, True, True)[1] predicted = predicted.t() correct = predicted.eq(targets.view(1, -1).expand_as(predicted)) top1 = correct[:1].reshape(-1).float().sum().mul(100.0 / responses.size(0)) top5 = correct[:5].reshape(-1).float().sum().mul(100.0 / responses.size(0)) return top1, top5 @torch.no_grad() def one_hot(targets: torch.Tensor, n_labels: int): identity = torch.eye(n_labels, dtype=torch.int8).to(targets.device) onehot_targets = identity.index_select(dim=0, index=targets.long().view(-1)) return onehot_targets.requires_grad_(False) @torch.no_grad() def one_hot_idx(targets: torch.Tensor, n_labels: int): targets = targets.view(-1) return targets + \ torch.arange(0, targets.size(0)).to(targets.device) * n_labels @torch.no_grad() def hard_negative_mask(prediction: torch.Tensor, targets: torch.Tensor, pos_to_neg_ratio: float = 0.25): r""" Hard negative mask generator for object detection (includes both positives and hard negatives). Args: prediction (torch.Tensor): label predictions of the network must be 2D/3D tensor. 2D: Two class problem with scores ranging from 0 to 1, where 0 is background. 3D: N-class predictions before softmax where F.softmax(prediction, -1)[:, :, 0] are the probabilities of background. targets (torch.Tensor): A 2D tensor of labels/targets. 0 is background. pos_to_neg_ratio (float): Ratio of positives to negatives. default = 0.25 """ assert prediction.ndim == 2 or prediction.ndim == 3, \ "hard_negative_mask: prediction must be 2D/3D tensor." assert targets.ndim == 2, \ "hard_negative_mask: targets must be 2D tensor." prediction = prediction.clone() ns = prediction.size(0) foreground_mask = targets > 0 ignore_mask = targets < 0 if prediction.shape == foreground_mask.shape: # assumes, two class problem and sigmoid is applied to output assert 1. >= prediction.max() and prediction.min() >= 0., \ "hard_negative_mask: Use torch.sigmoid(prediction)." # Mark the background_mask with hard negatives background_mask = torch.zeros_like(targets).bool() for i in range(ns): retain = max(1, int(foreground_mask[i].sum() / pos_to_neg_ratio)) probs = prediction[i] # foreground prob to minimum probs[foreground_mask[i]] = 0. # remove invalid targets probs[ignore_mask[i]] = 0. background_mask[i, torch.argsort(probs)[-retain:]] = True else: # assumes, N-class problem and softmax is not applied to output assert ~ prediction.sum(-1).eq(1).all(), \ "hard_negative_mask: Requires predictions before softmax." background_probs = torch.nn.functional.softmax(prediction, -1)[:, :, 0] # Mark the background_mask with hard negatives background_mask = torch.zeros_like(targets).bool() for i in range(ns): retain = max(1, int(foreground_mask[i].sum() / pos_to_neg_ratio)) probs = background_probs[i] # foreground prob to maximum probs[foreground_mask[i]] = 1. # remove invalid targets probs[ignore_mask[i]] = 1. background_mask[i, torch.argsort(probs)[:retain]] = True mask = foreground_mask.bool() | background_mask.bool() return mask
1,101
0
89
bfafc368176b6513edfd8f2cc1521fbf61f656f2
3,885
py
Python
qiskit/ignis/verification/entanglement/linear.py
yehuda-naveh/qiskit-ignis-1
26da6a2173ea3cc46a11753746b6b83c68216c1f
[ "Apache-2.0" ]
null
null
null
qiskit/ignis/verification/entanglement/linear.py
yehuda-naveh/qiskit-ignis-1
26da6a2173ea3cc46a11753746b6b83c68216c1f
[ "Apache-2.0" ]
null
null
null
qiskit/ignis/verification/entanglement/linear.py
yehuda-naveh/qiskit-ignis-1
26da6a2173ea3cc46a11753746b6b83c68216c1f
[ "Apache-2.0" ]
null
null
null
''' The module linear.py provides the linear preparation analogous of parallelize.py. ''' from qiskit import * from qiskit.circuit import Parameter def get_measurement_circ(n, qregname, cregname, full_measurement=True): ''' Creates a measurement circuit that can toggle between measuring the first control qubit or measuring all qubits. The default is measurement of all qubits. Args: n: number of qubits full_measurement: Whether to append full measurement, or only on the first qubit. Returns: The measurement suffix for a circuit ''' q = QuantumRegister(n, qregname) if full_measurement: cla = ClassicalRegister(n, cregname) meas = QuantumCircuit(q, cla) meas.barrier() meas.measure(q, cla) return meas cla = ClassicalRegister(1, cregname) meas = QuantumCircuit(q, cla) meas.barrier() meas.measure(q[0], cla) return meas def get_ghz_simple(n, measure=True, full_measurement=True): ''' Creates a linear GHZ state with the option of measurement Args: n: number of qubits measure (Boolean): Whether to add measurement gates full_measurement: Whether to append full measurement, or only on the first qubit. Relevant only for measure=True Returns: A linear GHZ Circuit ''' q = QuantumRegister(n, 'q') circ = QuantumCircuit(q) circ.h(q[0]) for i in range(1, n): circ.cx(q[i - 1], q[i]) if measure: meas = get_measurement_circ(n, 'q', 'c', full_measurement) circ = circ + meas return circ def get_ghz_mqc(n, delta, full_measurement): ''' This function creates an MQC circuit with n qubits, where the middle phase rotation around the z axis is by delta ''' q = QuantumRegister(n, 'q') circ = get_ghz_simple(n, measure=False) circinv = circ.inverse() circ.barrier() circ.u1(delta, q) circ.x(q) circ.barrier() circ += circinv meas = get_measurement_circ(n, 'q', 'c', full_measurement) circ = circ + meas return circ def get_ghz_mqc_para(n, full_measurement=True): ''' This function creates an MQC circuit with n qubits, where the middle phase rotation around the z axis is by delta Args: n: number of qubits full_measurement: Whether to append full measurement, or only on the first qubit. Returns: An mqc circuit and its Delta parameter ''' q = QuantumRegister(n, 'q') circ = get_ghz_simple(n, measure=False) delta = Parameter('t') circinv = circ.inverse() circ.barrier() circ.u1(delta, q) circ.x(q) circ.barrier() circ += circinv meas = get_measurement_circ(n, 'q', 'c', full_measurement) circ = circ + meas return circ, delta def get_ghz_po(n, delta): ''' This function creates an Parity Oscillation circuit with n qubits, where the middle superposition rotation around the x and y axes is by delta ''' q = QuantumRegister(n, 'q') circ = get_ghz_simple(n, measure=False) circ.barrier() circ.u2(delta, -delta, q) circ.barrier() meas = get_measurement_circ(n, 'q', 'c', True) circ = circ + meas return circ def get_ghz_po_para(n): ''' This function creates a Parity Oscillation circuit with n qubits, where the middle superposition rotation around the x and y axes is by delta Args: n: number of qubits Returns: A parity oscillation circuit and its Delta/minus-delta parameters ''' q = QuantumRegister(n, 'q') delta = Parameter('t') deltaneg = Parameter('-t') circ = get_ghz_simple(n, measure=False) circ.barrier() circ.u2(delta, deltaneg, q) meas = get_measurement_circ(n, 'q', 'c', True) circ = circ + meas return circ, [delta, deltaneg]
27.359155
72
0.646332
''' The module linear.py provides the linear preparation analogous of parallelize.py. ''' from qiskit import * from qiskit.circuit import Parameter def get_measurement_circ(n, qregname, cregname, full_measurement=True): ''' Creates a measurement circuit that can toggle between measuring the first control qubit or measuring all qubits. The default is measurement of all qubits. Args: n: number of qubits full_measurement: Whether to append full measurement, or only on the first qubit. Returns: The measurement suffix for a circuit ''' q = QuantumRegister(n, qregname) if full_measurement: cla = ClassicalRegister(n, cregname) meas = QuantumCircuit(q, cla) meas.barrier() meas.measure(q, cla) return meas cla = ClassicalRegister(1, cregname) meas = QuantumCircuit(q, cla) meas.barrier() meas.measure(q[0], cla) return meas def get_ghz_simple(n, measure=True, full_measurement=True): ''' Creates a linear GHZ state with the option of measurement Args: n: number of qubits measure (Boolean): Whether to add measurement gates full_measurement: Whether to append full measurement, or only on the first qubit. Relevant only for measure=True Returns: A linear GHZ Circuit ''' q = QuantumRegister(n, 'q') circ = QuantumCircuit(q) circ.h(q[0]) for i in range(1, n): circ.cx(q[i - 1], q[i]) if measure: meas = get_measurement_circ(n, 'q', 'c', full_measurement) circ = circ + meas return circ def get_ghz_mqc(n, delta, full_measurement): ''' This function creates an MQC circuit with n qubits, where the middle phase rotation around the z axis is by delta ''' q = QuantumRegister(n, 'q') circ = get_ghz_simple(n, measure=False) circinv = circ.inverse() circ.barrier() circ.u1(delta, q) circ.x(q) circ.barrier() circ += circinv meas = get_measurement_circ(n, 'q', 'c', full_measurement) circ = circ + meas return circ def get_ghz_mqc_para(n, full_measurement=True): ''' This function creates an MQC circuit with n qubits, where the middle phase rotation around the z axis is by delta Args: n: number of qubits full_measurement: Whether to append full measurement, or only on the first qubit. Returns: An mqc circuit and its Delta parameter ''' q = QuantumRegister(n, 'q') circ = get_ghz_simple(n, measure=False) delta = Parameter('t') circinv = circ.inverse() circ.barrier() circ.u1(delta, q) circ.x(q) circ.barrier() circ += circinv meas = get_measurement_circ(n, 'q', 'c', full_measurement) circ = circ + meas return circ, delta def get_ghz_po(n, delta): ''' This function creates an Parity Oscillation circuit with n qubits, where the middle superposition rotation around the x and y axes is by delta ''' q = QuantumRegister(n, 'q') circ = get_ghz_simple(n, measure=False) circ.barrier() circ.u2(delta, -delta, q) circ.barrier() meas = get_measurement_circ(n, 'q', 'c', True) circ = circ + meas return circ def get_ghz_po_para(n): ''' This function creates a Parity Oscillation circuit with n qubits, where the middle superposition rotation around the x and y axes is by delta Args: n: number of qubits Returns: A parity oscillation circuit and its Delta/minus-delta parameters ''' q = QuantumRegister(n, 'q') delta = Parameter('t') deltaneg = Parameter('-t') circ = get_ghz_simple(n, measure=False) circ.barrier() circ.u2(delta, deltaneg, q) meas = get_measurement_circ(n, 'q', 'c', True) circ = circ + meas return circ, [delta, deltaneg]
0
0
0
b3e616c9c00524f30d047f2ab6854aa68f2005ce
8,950
py
Python
mc/db/tests/test_ent.py
aspuru-guzik-group/mission_control
bfe930e1038e9e0d6c4bb327474766e85b2190cb
[ "Apache-2.0" ]
3
2017-09-01T19:49:59.000Z
2018-06-04T10:30:01.000Z
mc/db/tests/test_ent.py
aspuru-guzik-group/mission_control
bfe930e1038e9e0d6c4bb327474766e85b2190cb
[ "Apache-2.0" ]
null
null
null
mc/db/tests/test_ent.py
aspuru-guzik-group/mission_control
bfe930e1038e9e0d6c4bb327474766e85b2190cb
[ "Apache-2.0" ]
1
2018-12-13T19:48:27.000Z
2018-12-13T19:48:27.000Z
import time import unittest import sqlalchemy as _sqla import sqlalchemy.orm as _sqla_orm from .. import models
34.423077
78
0.513296
import time import unittest import sqlalchemy as _sqla import sqlalchemy.orm as _sqla_orm from .. import models class BaseTestCase(unittest.TestCase): def setUp(self): self.engine = _sqla.create_engine('sqlite://') models.utils.Base.metadata.create_all(self.engine) self.Session = _sqla_orm.sessionmaker(bind=self.engine) self.session = self.Session() self.ent_type = 'some_ent_type' self.props = { 'str_prop': 'str', 'int_prop': 1, 'bool_prop': True, 'mapping_prop': {'some': {'nested': 'prop'}}, 'sequence_prop': ['some', 'sequence'] } self.tags = {'tag_%s' % i for i in range(3)} def generate_ent(self, **kwargs): return models.Ent(**{ 'ent_type': self.ent_type, 'props': self.props, 'tags': self.tags, **kwargs }) class CreateEntTestCase(BaseTestCase): def setUp(self): super().setUp() self.ent = self.generate_ent() self.session.add(self.ent) self.session.commit() def test_has_timestamps(self): self.assertTrue(self.ent.created is not None) self.assertTrue(self.ent.modified is not None) def test_default_key_startswith_ent_ent_type(self): self.assertTrue(self.ent.key.startswith('ent:' + self.ent_type)) def test_has_props(self): self.assertTrue(self.ent.props, self.props) def test_has_tags(self): self.assertTrue(self.ent.tags, self.tags) class QueryEntTestCase(BaseTestCase): def test_filter_created(self): ents = [] for i in range(3): ent = self.generate_ent() self.session.add(ent) self.session.commit() ents.append(ent) time.sleep(1e-3) newer_than_ent_0 = (self.session.query(models.Ent) .filter(models.Ent.created > ents[0].created) .all()) self.assertEqual(newer_than_ent_0, ents[1:]) older_than_ent_2 = (self.session.query(models.Ent) .filter(models.Ent.created < ents[2].created) .all()) self.assertEqual(older_than_ent_2, ents[:2]) def test_filter_props(self): ents = [] for i in range(3): ent = self.generate_ent( props={'int_prop': i, 'str_prop': 'str_%s' % i} ) self.session.add(ent) self.session.commit() ents.append(ent) ents_w_int_eq_1 = ( self.session.query(models.Ent) .filter(models.Ent.props_set.any(key='int_prop', value=1)) .all() ) self.assertEqual(ents_w_int_eq_1, [ents[1]]) ents_w_int_gt_1 = ( self.session.query(models.Ent) .filter( models.Ent.props_set.any( (models.Ent.Prop.key == 'int_prop') & (models.Ent.Prop.value > 1) ) ) .all() ) self.assertEqual(ents_w_int_gt_1, ents[2:]) def test_filter_tags(self): ents = [ self.generate_ent(tags={'tag_1', 'tag_2'}), self.generate_ent(tags={'tag_2', 'tag_3'}), self.generate_ent(tags={'tag_1', 'tag_3'}), ] self.session.add_all(ents) self.session.commit() ents_w_tag_1 = ( self.session.query(models.Ent) .filter(models.Ent.tags_set.any(name='tag_1')) .all() ) self.assertEqual(set(ents_w_tag_1), set([ents[0], ents[2]])) ents_w_tag_2 = ( self.session.query(models.Ent) .filter(models.Ent.tags_set.any(name='tag_2')) .all() ) self.assertEqual(set(ents_w_tag_2), set([ents[0], ents[1]])) ents_w_nonexistent_tag = ( self.session.query(models.Ent) .filter(models.Ent.tags_set.any(name='nonexistent_tag')) .all() ) self.assertEqual(set(ents_w_nonexistent_tag), set()) class LineageTestCase(BaseTestCase): def setUp(self): super().setUp() self.families = self._create_families() def _create_families(self): families = {} for i in range(2): family_key = ('family_%s' % i) families[family_key] = self._create_family(family_key=family_key) return families def _create_family(self, family_key=None): common_props = {'family_key': family_key} grandparents = [ self.generate_ent( key=('%s:grandparent_%s' % (family_key, i)), props={**common_props, 'generation': 'grandparents'} ) for i in range(4) ] grandparent_pairs = [ [grandparents[0], grandparents[1]], [grandparents[2], grandparents[3]] ] parents = [] for i, grandparent_pair in enumerate(grandparent_pairs): parents.append( self.generate_ent( key=('%s:parent_%s' % (family_key, i)), props={**common_props, 'generation': 'parents'}, parents=grandparent_pair, ancestors=grandparent_pair ) ) children = [ self.generate_ent( key=('%s:child_%s' % (family_key, i)), props={**common_props, 'generation': 'children'}, parents=parents, ancestors=(grandparents + parents) ) for i in range(3) ] self.session.add_all(grandparents + parents + children) self.session.commit() family = { 'grandparents': grandparents, 'grandparent_pairs': grandparent_pairs, 'parents': parents, 'children': children } return family def test_parents(self): for family in self.families.values(): for child in family['children']: self.assertEqual(child.parents, family['parents']) for i, parent in enumerate(family['parents']): self.assertEqual( parent.parents, family['grandparent_pairs'][i] ) def test_children(self): for family in self.families.values(): for parent in family['parents']: self.assertEqual( set(parent.children), set(family['children']) ) for i, gp_pair in enumerate(family['grandparent_pairs']): for grandparent in gp_pair: self.assertEqual( set(grandparent.children), set([family['parents'][i]]) ) def test_ancestors(self): for family in self.families.values(): for child in family['children']: self.assertEqual( set(child.ancestors), set(family['grandparents'] + family['parents']) ) def test_descendants(self): for family in self.families.values(): for grandparent in family['grandparents']: self.assertEqual( set(grandparent.descendants), set(grandparent.children + family['children']) ) def test_query_on_parents(self): for family in self.families.values(): children_of_grandparent_pair_0 = ( self.session.query(models.Ent) .join(models.Ent.parents, aliased=True, from_joinpoint=True) .filter( models.Ent.key.in_([ grandparent.key for grandparent in family['grandparent_pairs'][0] ]) ) .reset_joinpoint() .all() ) self.assertEqual(children_of_grandparent_pair_0, [family['parents'][0]]) def test_query_on_ancestors(self): for family_key, family in self.families.items(): descendants = ( self.session.query(models.Ent) .filter( models.Ent.props_set.any( key='generation', value='children' ) ) .join(models.Ent.ancestors, aliased=True, from_joinpoint=True) .filter( models.Ent.props_set.any( key='family_key', value=family_key ) ) .reset_joinpoint() .all() ) self.assertEqual(set(descendants), set(family['children']))
8,166
65
601
d3994b6e31abc336d878a1cd54606f301a5aaddf
1,781
py
Python
main.py
jtprogru/bad-isp-twbot
79391396694265531049bb715437b35242f5aa46
[ "WTFPL" ]
2
2020-07-17T17:05:49.000Z
2020-07-24T16:41:46.000Z
main.py
jtprog/bad-isp-twbot
79391396694265531049bb715437b35242f5aa46
[ "WTFPL" ]
1
2021-09-03T14:40:42.000Z
2021-09-03T14:40:42.000Z
main.py
jtprog/bad-isp-twbot
79391396694265531049bb715437b35242f5aa46
[ "WTFPL" ]
null
null
null
#!/usr/bin/env python # coding=utf-8 # Created by JTProgru # Date: 2019-08-13 # https://jtprog.ru/ __author__ = 'jtprogru' __version__ = '0.0.1' __author_email__ = 'mail@jtprog.ru' import twitter import dotenv as d from pathlib import Path from speedtest import Speedtest import json env = d.get_variables(str(Path(__file__).parent / '.env')) servers = [] # If you want to test against a specific server # servers = [1234] threads = None # If you want to use a single threaded test # threads = 1 s = Speedtest() # s.get_servers(servers) s.get_best_server() s.download(threads=threads) s.upload(threads=threads) # s.results.json() resp = json.loads(s.results.json(pretty=True)) print(resp) print() print('%.2f' % (resp['bytes_received'] / 1024 / 1024)) # my_auth = twitter.OAuth(env['TOKEN'], env['TOKEN_KEY'], env['CON_SEC'], env['CON_SEC_KEY']) # twit = twitter.Twitter(auth=my_auth) # try to tweet if speedtest couldnt even connet. # probably wont work if the internet is down # if "Cannot" in resp: # try: # tweet_status = "WTF, что с моим интернетом? #JTProgru #" # twit.statuses.update(status=tweet_status) # except Exception as e: # print(str(e)) # pass # tweet if down speed is less than whatever I set # elif eval(resp['download']) < eval(env['ISP_PAYED_SPEED']): # print(eval(dowloadspeed)) # print(eval(uploadspeed)) # print(eval(env['ISP_PAYED_SPEED'])) # print("trying to tweet") # try: # i know there must be a better way than to do (str(int(eval()))) # tweet = str(float(eval(dowloadspeed))) + " down\\" + str(float(eval(uploadspeed))) + " up #speedtest" # twit.statuses.update(status='My speedtest now is: ' + tweet) # except Exception as e: # print(str(e))
26.984848
111
0.66648
#!/usr/bin/env python # coding=utf-8 # Created by JTProgru # Date: 2019-08-13 # https://jtprog.ru/ __author__ = 'jtprogru' __version__ = '0.0.1' __author_email__ = 'mail@jtprog.ru' import twitter import dotenv as d from pathlib import Path from speedtest import Speedtest import json env = d.get_variables(str(Path(__file__).parent / '.env')) servers = [] # If you want to test against a specific server # servers = [1234] threads = None # If you want to use a single threaded test # threads = 1 s = Speedtest() # s.get_servers(servers) s.get_best_server() s.download(threads=threads) s.upload(threads=threads) # s.results.json() resp = json.loads(s.results.json(pretty=True)) print(resp) print() print('%.2f' % (resp['bytes_received'] / 1024 / 1024)) # my_auth = twitter.OAuth(env['TOKEN'], env['TOKEN_KEY'], env['CON_SEC'], env['CON_SEC_KEY']) # twit = twitter.Twitter(auth=my_auth) # try to tweet if speedtest couldnt even connet. # probably wont work if the internet is down # if "Cannot" in resp: # try: # tweet_status = "WTF, что с моим интернетом? #JTProgru #" # twit.statuses.update(status=tweet_status) # except Exception as e: # print(str(e)) # pass # tweet if down speed is less than whatever I set # elif eval(resp['download']) < eval(env['ISP_PAYED_SPEED']): # print(eval(dowloadspeed)) # print(eval(uploadspeed)) # print(eval(env['ISP_PAYED_SPEED'])) # print("trying to tweet") # try: # i know there must be a better way than to do (str(int(eval()))) # tweet = str(float(eval(dowloadspeed))) + " down\\" + str(float(eval(uploadspeed))) + " up #speedtest" # twit.statuses.update(status='My speedtest now is: ' + tweet) # except Exception as e: # print(str(e))
0
0
0
e4114e3069a26efc84fae5bfd4804aeb08612c18
7,203
py
Python
mergecounts/utils/cache.py
adthrasher/merge-counts
87f41bec1c7fd3600e1fff52722ca6cc28509c0c
[ "MIT" ]
1
2022-03-10T02:09:47.000Z
2022-03-10T02:09:47.000Z
mergecounts/utils/cache.py
adthrasher/merge-counts
87f41bec1c7fd3600e1fff52722ca6cc28509c0c
[ "MIT" ]
3
2020-08-13T18:39:41.000Z
2021-06-18T15:12:21.000Z
mergecounts/utils/cache.py
adthrasher/merge-counts
87f41bec1c7fd3600e1fff52722ca6cc28509c0c
[ "MIT" ]
1
2021-02-18T16:20:58.000Z
2021-02-18T16:20:58.000Z
"""Caching utilities for the merge-counts command line tool.""" import glob import os import json import tempfile from pathlib import Path from typing import Dict, Optional from logzero import logger from . import errors CACHE_POINTER_LOCATION = Path.home() / ".mergecounts-cache" class DNAnexusFileCache: """A utility class for keeping up with cached DNAnexus objects.""" def __init__(self): """Creates a DNAnexusFileCache object to hold the list of known properties and describe calls for each DNAnexus file id. """ self.properties = {} self.describes = {} self.counts = {} def load_from_filesystem(self): """Loads any cached information from the filesystem.""" self.properties = load_cached_properties_from_filesystem() self.describes = load_cached_describes_from_filesystem() ############################## # Cache folder manipulations # ############################## def get_cache_folder() -> Optional[str]: """Gets the top level cache folder if it exists in the file at CACHE_POINTER_LOCATION. If that file does not exist, merge-counts has not instantiated a cache folder, so None is returned. Returns: Optional[str]: the cache folder directory or None if a cache has not been created by merge-counts. """ if not os.path.exists(CACHE_POINTER_LOCATION): return None # will always be the first line of the file cache_loc = [l.strip() for l in open(CACHE_POINTER_LOCATION, "r").readlines()][0] if not os.path.exists(cache_loc): errors.raise_error( f"Cache pointed to in {CACHE_POINTER_LOCATION} does not exist! {cache_loc}." ) return Path(cache_loc) def create_new_cache_folder() -> None: """Creates a new cache folder as a temporary dir (assumes that an existing cache instantiated by merge-counts does not exist and errors if it does). """ cache_folder_loc = get_cache_folder() if cache_folder_loc: errors.raise_error( f"Refusing to overwrite existing cache: {cache_folder_loc}", suggest_report=False, ) new_cache_loc = tempfile.mkdtemp() with open(CACHE_POINTER_LOCATION, "w") as cache_pointer: cache_pointer.writelines(new_cache_loc) logger.info( "Created new cache folder pointer at %s to %s.", CACHE_POINTER_LOCATION, new_cache_loc, ) def clean_cache() -> None: """Assuming a cache instantied by merge-counts exists, it will clean and remove the cache or silently succeed otherwise (e.g. if the cache folder does not exist). """ cache_folder_loc = get_cache_folder() if not cache_folder_loc or not os.path.exists(cache_folder_loc): logger.debug("No cache folder to delete.") else: logger.debug("Removing cache folder: %s.", cache_folder_loc) os.removedirs(cache_folder_loc) if os.path.exists(CACHE_POINTER_LOCATION): logger.debug("Removing cache folder pointer.") os.remove(CACHE_POINTER_LOCATION) def get_cached_properties_folder(silently_create: bool = True) -> Path: """Returns the subfolder within the cache that contains all DNAnexus properties for each dxid. In this folder, the filename is the dxid and the contents of each property are the DNAnexus properties as JSON objects. Arguments: silently_create (bool): if the subfolder does not exist, create before returning. Defaults to True. If False, this will error if the folder doesn't exist. Returns: Path: path to the subfolder containing the cached DNAnexus property files. """ properties_folder = get_cache_folder() / "properties" if not os.path.exists(properties_folder): if silently_create: os.makedirs(properties_folder) else: errors.raise_error( f"Properties subfolder in cache does not exist: {properties_folder}!" ) return properties_folder def get_cached_describes_folder(silently_create: bool = True) -> Path: """Returns the subfolder within the cache that contains all DNAnexus describe calls for each dxid. In this folder, the filename is the dxid and the contents of each property are the DNAnexus describe calls as JSON objects. Arguments: silently_create (bool): if the subfolder does not exist, create before returning. Defaults to True. If False, this will error if the folder doesn't exist. Returns: Path: path to the subfolder containing the cached DNAnexus property files. """ describes_folder = get_cache_folder() / "describes" if not os.path.exists(describes_folder): if silently_create: os.makedirs(describes_folder) else: errors.raise_error( f"Properties subfolder in cache does not exist: {describes_folder}!" ) return describes_folder def cache_properties_on_filesystem(dxid: str, properties: Dict) -> None: """Caches DNAnexus properties in the property subfolder of the cache. Args: dxid (str): DNAnexus id of the file in question. properties (Dict): DNAnexus properties as a dict. """ cache_filepath = get_cached_properties_folder() / dxid with open(cache_filepath, "w") as cache: json.dump(properties, cache) def cache_describes_on_filesystem(dxid: str, describe: Dict) -> None: """Caches DNAnexus describe calls in the describes subfolder of the cache. Args: dxid (str): DNAnexus id of the file in question. describe (Dict): DNAnexus describe call as a dict. """ cache_filepath = get_cached_describes_folder() / dxid with open(cache_filepath, "w") as cache: json.dump(describe, cache) def load_cached_properties_from_filesystem() -> Dict: """Loads the cached DNAnexus properties from the appropriate subfolder in the merge-counts cache. Returns: Dict: all cached properties where the key is the DNAnexus file id and the value is the DNAnexus properties as a dict. """ result = dict() path = str(get_cached_properties_folder() / "*") for filename in glob.glob(path): basename = os.path.basename(filename) result[basename] = json.load(open(filename, "r")) logger.info("Loaded %d entries from the properties cache.", len(result.items())) return result def load_cached_describes_from_filesystem() -> Dict: """Loads the cached DNAnexus describe calls from the appropriate subfolder in the merge-counts cache. Returns: Dict: all cached describes where the key is the DNAnexus file id and the value is the DNAnexus describe call as a dict. """ result = dict() for filename in glob.glob(str(get_cached_describes_folder() / "*")): basename = os.path.basename(filename) result[basename] = json.load(open(filename, "r")) logger.info("Loaded %d entries from the describes cache.", len(result.items())) return result
33.041284
106
0.670276
"""Caching utilities for the merge-counts command line tool.""" import glob import os import json import tempfile from pathlib import Path from typing import Dict, Optional from logzero import logger from . import errors CACHE_POINTER_LOCATION = Path.home() / ".mergecounts-cache" class DNAnexusFileCache: """A utility class for keeping up with cached DNAnexus objects.""" def __init__(self): """Creates a DNAnexusFileCache object to hold the list of known properties and describe calls for each DNAnexus file id. """ self.properties = {} self.describes = {} self.counts = {} def load_from_filesystem(self): """Loads any cached information from the filesystem.""" self.properties = load_cached_properties_from_filesystem() self.describes = load_cached_describes_from_filesystem() ############################## # Cache folder manipulations # ############################## def get_cache_folder() -> Optional[str]: """Gets the top level cache folder if it exists in the file at CACHE_POINTER_LOCATION. If that file does not exist, merge-counts has not instantiated a cache folder, so None is returned. Returns: Optional[str]: the cache folder directory or None if a cache has not been created by merge-counts. """ if not os.path.exists(CACHE_POINTER_LOCATION): return None # will always be the first line of the file cache_loc = [l.strip() for l in open(CACHE_POINTER_LOCATION, "r").readlines()][0] if not os.path.exists(cache_loc): errors.raise_error( f"Cache pointed to in {CACHE_POINTER_LOCATION} does not exist! {cache_loc}." ) return Path(cache_loc) def create_new_cache_folder() -> None: """Creates a new cache folder as a temporary dir (assumes that an existing cache instantiated by merge-counts does not exist and errors if it does). """ cache_folder_loc = get_cache_folder() if cache_folder_loc: errors.raise_error( f"Refusing to overwrite existing cache: {cache_folder_loc}", suggest_report=False, ) new_cache_loc = tempfile.mkdtemp() with open(CACHE_POINTER_LOCATION, "w") as cache_pointer: cache_pointer.writelines(new_cache_loc) logger.info( "Created new cache folder pointer at %s to %s.", CACHE_POINTER_LOCATION, new_cache_loc, ) def clean_cache() -> None: """Assuming a cache instantied by merge-counts exists, it will clean and remove the cache or silently succeed otherwise (e.g. if the cache folder does not exist). """ cache_folder_loc = get_cache_folder() if not cache_folder_loc or not os.path.exists(cache_folder_loc): logger.debug("No cache folder to delete.") else: logger.debug("Removing cache folder: %s.", cache_folder_loc) os.removedirs(cache_folder_loc) if os.path.exists(CACHE_POINTER_LOCATION): logger.debug("Removing cache folder pointer.") os.remove(CACHE_POINTER_LOCATION) def get_cached_properties_folder(silently_create: bool = True) -> Path: """Returns the subfolder within the cache that contains all DNAnexus properties for each dxid. In this folder, the filename is the dxid and the contents of each property are the DNAnexus properties as JSON objects. Arguments: silently_create (bool): if the subfolder does not exist, create before returning. Defaults to True. If False, this will error if the folder doesn't exist. Returns: Path: path to the subfolder containing the cached DNAnexus property files. """ properties_folder = get_cache_folder() / "properties" if not os.path.exists(properties_folder): if silently_create: os.makedirs(properties_folder) else: errors.raise_error( f"Properties subfolder in cache does not exist: {properties_folder}!" ) return properties_folder def get_cached_describes_folder(silently_create: bool = True) -> Path: """Returns the subfolder within the cache that contains all DNAnexus describe calls for each dxid. In this folder, the filename is the dxid and the contents of each property are the DNAnexus describe calls as JSON objects. Arguments: silently_create (bool): if the subfolder does not exist, create before returning. Defaults to True. If False, this will error if the folder doesn't exist. Returns: Path: path to the subfolder containing the cached DNAnexus property files. """ describes_folder = get_cache_folder() / "describes" if not os.path.exists(describes_folder): if silently_create: os.makedirs(describes_folder) else: errors.raise_error( f"Properties subfolder in cache does not exist: {describes_folder}!" ) return describes_folder def cache_properties_on_filesystem(dxid: str, properties: Dict) -> None: """Caches DNAnexus properties in the property subfolder of the cache. Args: dxid (str): DNAnexus id of the file in question. properties (Dict): DNAnexus properties as a dict. """ cache_filepath = get_cached_properties_folder() / dxid with open(cache_filepath, "w") as cache: json.dump(properties, cache) def cache_describes_on_filesystem(dxid: str, describe: Dict) -> None: """Caches DNAnexus describe calls in the describes subfolder of the cache. Args: dxid (str): DNAnexus id of the file in question. describe (Dict): DNAnexus describe call as a dict. """ cache_filepath = get_cached_describes_folder() / dxid with open(cache_filepath, "w") as cache: json.dump(describe, cache) def load_cached_properties_from_filesystem() -> Dict: """Loads the cached DNAnexus properties from the appropriate subfolder in the merge-counts cache. Returns: Dict: all cached properties where the key is the DNAnexus file id and the value is the DNAnexus properties as a dict. """ result = dict() path = str(get_cached_properties_folder() / "*") for filename in glob.glob(path): basename = os.path.basename(filename) result[basename] = json.load(open(filename, "r")) logger.info("Loaded %d entries from the properties cache.", len(result.items())) return result def load_cached_describes_from_filesystem() -> Dict: """Loads the cached DNAnexus describe calls from the appropriate subfolder in the merge-counts cache. Returns: Dict: all cached describes where the key is the DNAnexus file id and the value is the DNAnexus describe call as a dict. """ result = dict() for filename in glob.glob(str(get_cached_describes_folder() / "*")): basename = os.path.basename(filename) result[basename] = json.load(open(filename, "r")) logger.info("Loaded %d entries from the describes cache.", len(result.items())) return result
0
0
0
eecdfa932379a2cf4658c04955118aefa60f9289
13,522
py
Python
yahoo_surface_scraper.py
JECSand/yahoo_finance_stock_scraper
99efce789427a6bc16f874713ba43aed2e68e3ae
[ "MIT" ]
7
2018-04-11T05:30:55.000Z
2021-12-02T20:36:10.000Z
yahoo_surface_scraper.py
JECSand/yahoo_finance_stock_scraper
99efce789427a6bc16f874713ba43aed2e68e3ae
[ "MIT" ]
null
null
null
yahoo_surface_scraper.py
JECSand/yahoo_finance_stock_scraper
99efce789427a6bc16f874713ba43aed2e68e3ae
[ "MIT" ]
4
2020-07-14T21:03:02.000Z
2022-01-25T01:27:57.000Z
# Connor Sanders # 10/16/2017 # Yahoo Finance Web Scraper # Tested on python 2.7 and 3.5 # Returns a JSON File containing financial statement data for a given company or list of companies # How to use this script: # Make sure you have the PhantomJS Driver set up. If you need the manually add the path, go to line 150 # python yahoo_surface_scraper.py StockTicker StatementType JSONFilename Frequency # If running multiple stock tickers at once, separate them each by commas with no spaces in between # Examples: # python yahoo_surface_scraper.py AAPL Income test.json Annual # or # python3 yahoo_surface_scraper.py WFC Balance testfile Quarterly # or # python3 yahoo_surface_scraper.py WFC,AAPL Balance extracts.json Quarterly # Feel free to email connor@exceleri.com with any questions, concerns, or improvement ideas! import os import sys import re import pip from json import load, dump import signal import time import datetime # Package installer function to handle missing packages # Ensure beautifulsoup4 is installed try: from bs4 import BeautifulSoup except: install('beautifulsoup4') from bs4 import BeautifulSoup # Ensure selenium is installed try: from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By except: install('selenium') from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By # Declare datetime time stamp, and current working directory and file variables dt = datetime.datetime.today() c_dir = os.getcwd() # OS Specific Code for Cross Platform Purposes os_system = os.name if os_system == 'nt': json_local_dir = c_dir + '\\json_extracts\\' fields_dir = c_dir + '\\data_fields\\' else: json_local_dir = c_dir + '/json_extracts/' fields_dir = c_dir + '/data_fields/' # Function to check user inputs # Function to create JSON Extract File Name # Function to write JSON Data to Timestamped JSON Output File # Main Function # Main Process Handler for Script if __name__ == '__main__': check_inputs(sys.argv) if len(sys.argv) == 5: main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]) elif len(sys.argv) == 4: main(sys.argv[1], sys.argv[2], sys.argv[3])
42.25625
121
0.619139
# Connor Sanders # 10/16/2017 # Yahoo Finance Web Scraper # Tested on python 2.7 and 3.5 # Returns a JSON File containing financial statement data for a given company or list of companies # How to use this script: # Make sure you have the PhantomJS Driver set up. If you need the manually add the path, go to line 150 # python yahoo_surface_scraper.py StockTicker StatementType JSONFilename Frequency # If running multiple stock tickers at once, separate them each by commas with no spaces in between # Examples: # python yahoo_surface_scraper.py AAPL Income test.json Annual # or # python3 yahoo_surface_scraper.py WFC Balance testfile Quarterly # or # python3 yahoo_surface_scraper.py WFC,AAPL Balance extracts.json Quarterly # Feel free to email connor@exceleri.com with any questions, concerns, or improvement ideas! import os import sys import re import pip from json import load, dump import signal import time import datetime # Package installer function to handle missing packages def install(package): print(package + ' package for Python not found, pip installing now....') pip.main(['install', package]) print(package + ' package has been successfully installed for Python\n Continuing Process...') # Ensure beautifulsoup4 is installed try: from bs4 import BeautifulSoup except: install('beautifulsoup4') from bs4 import BeautifulSoup # Ensure selenium is installed try: from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By except: install('selenium') from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By # Declare datetime time stamp, and current working directory and file variables dt = datetime.datetime.today() c_dir = os.getcwd() # OS Specific Code for Cross Platform Purposes os_system = os.name if os_system == 'nt': json_local_dir = c_dir + '\\json_extracts\\' fields_dir = c_dir + '\\data_fields\\' else: json_local_dir = c_dir + '/json_extracts/' fields_dir = c_dir + '/data_fields/' class YahooFinanceFundamentals: def __init__(self, ticker): self.ticker = ticker # Yahoo Finance Base URL BASE_YAHOO_URL = 'https://finance.yahoo.com/quote/' FIELD_PARAM_FILE = 'yahoo_finance_fields.json' # Script Data Dictionary to map statement type to yahoo finance naming conventions _YAHOO_FINANCIAL_TYPES = { 'income': 'financials', 'balance': 'balance-sheet', 'cash': 'cash-flow', } # Private Static Method to determine if variable is an int or not @staticmethod def _determine_if_int(value): try: int(value) return True except ValueError: return False # Private Static Method to determine if variable is an int or not @staticmethod def _determine_quarterly_button(soup): for buttons in soup.find_all('button'): if 'Quarterly' in str(buttons): return buttons # Private Static Method to convert tem[ 0 placeholders back to '-' @staticmethod def _convert_null_data_to_str(data_value): re_value = data_value if str(data_value) == '0': re_value = '-' return re_value # Private Static Method to determine if data has 3 or 4 periods @staticmethod def _frequency_count(frequency): if frequency == 'annual': period_count = 3 elif frequency == 'quarterly': period_count = 4 else: print('Please enter a frequency value of either annual or quarterly') sys.exit(1) return period_count # Private Static Method to reformat json data fields to camel case @staticmethod def _reformat_field_json(field_string): if ' ' in field_string: split_field_str_list = list(field_string.replace('/', ' ').split(' ')) form_field = '' i = 0 for split_field in split_field_str_list: if i == 0: form_field += split_field.lower() i += 1 else: form_field += split_field.capitalize() else: form_field = field_string.lower() return form_field # Private Static Method to open and load field data from field json file def _get_json_file_fields(self, statement_type): with open(fields_dir + self.FIELD_PARAM_FILE) as json_data: json_field_file_data = load(json_data) return json_field_file_data[statement_type] # Private Method to scrap data from yahoo finance web page def _scrap_yahoo_data(self, ticker, statement_type, frequency): raw_data_list = [] YAHOO_URL = self.BASE_YAHOO_URL + ticker + '/' + self._YAHOO_FINANCIAL_TYPES[statement_type] + '?p=' + ticker driver = webdriver.PhantomJS() driver.implicitly_wait(5) driver.get(YAHOO_URL) html = driver.page_source soup = BeautifulSoup(html, "html.parser") if frequency == 'quarterly': q_button = self._determine_quarterly_button(soup) button_class = str(q_button.find_all('div')[0]).split('"')[1] button_xpath = '//*[@class="' + button_class + '"]/span' button = driver.find_element_by_xpath(button_xpath) i = 0 while i < 10: try: button.click() WebDriverWait(driver, 10).until(EC.invisibility_of_element_located((By.XPATH, button_xpath))) break except: i += 1 continue if i == 10: print('Please check your internet connection!\nUnable to connect to ' + YAHOO_URL + '! Exiting...') sys.exit(1) html = driver.page_source soup = BeautifulSoup(html, "html.parser") for table_data in soup.find_all('td'): raw_data_list.append(table_data) driver.service.process.send_signal(signal.SIGTERM) driver.quit() return raw_data_list # Private method to organized returned raw data from scrap into a semi organized state def _raw_data_organization(self, ticker, statement_type, frequency): num_of_periods = self._frequency_count(frequency) dates = [] financials_dict = {} raw_data_list = self._scrap_yahoo_data(ticker, statement_type, frequency) prev_val = '' cur_field = '' cur_values = [] i = 0 for raw_data in raw_data_list: if 'span' in str(raw_data): cleaned_value = str(raw_data.find_all('span')[0]).split('>')[1].split('<')[0]\ .replace("'", "").replace(',', '').replace('-', '0') else: cleaned_value = str(raw_data).split('>')[1].split('<')[0].replace("'", "").replace(',', '')\ .replace('-', '0') if len(cleaned_value.split('/')) == 3: dates.append(cleaned_value) else: if self._determine_if_int(cleaned_value) and self._determine_if_int(prev_val) is not True: cur_field = prev_val check_data = self._convert_null_data_to_str(cleaned_value) cur_values.append(check_data) i += 1 elif self._determine_if_int(cleaned_value) and self._determine_if_int(prev_val): check_data = self._convert_null_data_to_str(cleaned_value) cur_values.append(check_data) i += 1 if i == num_of_periods: dict_ent = {cur_field: cur_values} financials_dict.update(dict_ent) cur_field = '' cur_values = [] i = 0 prev_val = cleaned_value return [dates, financials_dict] # Private Method to build the data dict entries def _get_financial_data_dict_ent(self, ticker, statement_type, frequency): output_list = [] org_data = self._raw_data_organization(ticker, statement_type, frequency) date_list = org_data[0] finance_dict = org_data[1] data_fields = self._get_json_file_fields(statement_type) i = 0 for date in date_list: date_fin_dict = {} sub_list = [] for objs in data_fields: cat_data_dict = {} temp_data_dict = {} for r_column in list(objs.values())[0]: column = self._reformat_field_json(r_column) try: dict_ent = {column: int(finance_dict[r_column][i])} except: dict_ent = {column: finance_dict[r_column][i]} temp_data_dict.update(dict_ent) r_section_label = list(objs.keys())[0].split(',')[0] section_label = self._reformat_field_json(r_section_label) dict_ent = {section_label: temp_data_dict} cat_data_dict.update(dict_ent) sub_list.append(cat_data_dict) dict_ent = {date: sub_list} date_fin_dict.update(dict_ent) output_list.append(date_fin_dict) i += 1 dict_ent = {ticker + '-' + statement_type + '-' + frequency: output_list} return dict_ent # Public method for the user to call for financial data def pull_financial_fundamentals(self, statement_type, frequency): output_obj = {} if isinstance(self.ticker, str): dict_ent = self._get_financial_data_dict_ent(self.ticker.upper(), statement_type.lower(), frequency.lower()) output_obj.update(dict_ent) else: for tick in self.ticker: dict_ent = self._get_financial_data_dict_ent(tick.upper(), statement_type.lower(), frequency.lower()) output_obj.update(dict_ent) return output_obj # Function to check user inputs def check_inputs(script_args): if len(script_args) > 5: print('Please check your script parameters and try again!\n Make sure you if enter multiple ' 'tickers to have them in the following format without any spaces in between:\n') print('python yahoo_surface_scraper.py AAPL,WFC Income examplefile.json Quarterly') sys.exit(1) elif len(script_args) < 4: print('Please check your script parameters to ensure you are not missing any.\n' 'To run this script you will need to enter atleast a ticker symbol and a desired statement type!') print('python yahoo_surface_scraper.py AAPL,WFC Cash examplefile.json') # Function to create JSON Extract File Name def get_json_filename(json_filename_input, statement_type, frequency): clean_filename_input = json_filename_input.replace(' ', '-').replace('_', '-') dt_str = str(dt).replace(':', '-').replace(' ', '_').split('.')[0] if '.' in clean_filename_input: filename_list = list(clean_filename_input.split('.')) if len(filename_list) > 2: print("Incorrect JSON Extract File naming Convention, Please don't add any extra periods! Exiting...") sys.exit(1) json_file_pre = filename_list[0] else: json_file_pre = clean_filename_input json_filename = str(json_file_pre + '_' + statement_type + '-' + frequency + '_' + dt_str + '.json').lower() return json_filename # Function to write JSON Data to Timestamped JSON Output File def create_json_extract_file(json_filename, json_data): with open(json_local_dir + json_filename, 'w') as json_outfile: dump(json_data, json_outfile, indent=4) print(json_filename + ' has been successfully created and can be found in ' + json_local_dir) # Main Function def main(ticker, statement_type, json_filename_input, frequency="annual"): if ',' in ticker: ticker = list(ticker.replace(' ', '').split(',')) yahoo_fundamentals = YahooFinanceFundamentals(ticker) financial_data_extract = yahoo_fundamentals.pull_financial_fundamentals(statement_type, frequency) json_filename = get_json_filename(json_filename_input, statement_type, frequency) create_json_extract_file(json_filename, financial_data_extract) print(frequency.capitalize() + ' ' + statement_type.capitalize() + ' Data has been extracted and stored in for the following stocks: ') print(str(ticker).replace("['", "").replace("']", "").replace("', '", ", ")) print('Process Completed Successfully!') # Main Process Handler for Script if __name__ == '__main__': check_inputs(sys.argv) if len(sys.argv) == 5: main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]) elif len(sys.argv) == 4: main(sys.argv[1], sys.argv[2], sys.argv[3])
9,306
1,498
139
10967061082d22a1f1ea01e1906929512f9533e7
21,995
py
Python
src/nodes/gazebo_to_habitat_agent.py
ericchen321/ros_x_habitat
f256b62fe8dda059baaf9bad87cf53f7d769f2f9
[ "CC-BY-4.0" ]
24
2021-09-10T23:35:53.000Z
2022-03-31T18:12:20.000Z
src/nodes/gazebo_to_habitat_agent.py
ericchen321/ros_x_habitat
f256b62fe8dda059baaf9bad87cf53f7d769f2f9
[ "CC-BY-4.0" ]
4
2021-12-11T06:56:58.000Z
2022-02-23T03:05:00.000Z
src/nodes/gazebo_to_habitat_agent.py
ericchen321/ros_x_habitat
f256b62fe8dda059baaf9bad87cf53f7d769f2f9
[ "CC-BY-4.0" ]
7
2021-12-17T14:13:27.000Z
2022-03-31T16:39:28.000Z
#!/usr/bin/env python import argparse import numpy as np import rospy import message_filters from message_filters import TimeSynchronizer from ros_x_habitat.msg import PointGoalWithGPSCompass, DepthImage from sensor_msgs.msg import Image from cv_bridge import CvBridge import cv2 from PIL import Image as PILImage from nav_msgs.msg import Odometry from std_msgs.msg import Header, Int16 from geometry_msgs.msg import PoseStamped, Pose, Point import quaternion from habitat.tasks.utils import cartesian_to_polar from tf.transformations import euler_from_quaternion, rotation_matrix from visualization_msgs.msg import Marker, MarkerArray from threading import Lock from ros_x_habitat.srv import GetAgentPose from src.constants.constants import PACKAGE_NAME, ServiceNames from src.utils import utils_logging class GazeboToHabitatAgent: r""" A class to represent a ROS node which subscribes from Gazebo sensor topics and publishes to Habitat agent's sensor topics. """ def __init__( self, node_name: str, gazebo_rgb_topic_name: str, gazebo_depth_topic_name: str, gazebo_odom_topic_name: str, move_base_goal_topic_name: str, fetch_goal_from_move_base: bool=False, final_pointgoal_pos: np.ndarray = np.array([0.0, 0.0, 0.0]), ): r""" Instantiates the Gazebo->Habitat agent bridge. :param node_name: name of the bridge node :param gazebo_rgb_topic_name: name of the topic on which Gazebo publishes RGB observations :param gazebo_depth_topic_name: name of the topic on which Gazebo publishes depth observations :param gazebo_odom_topic_name: name of the topic on which Gazebo publishes odometry data :param move_base_goal_topic_name: name of the topic on which the move_base package publishes navigation goals :param fetch_goal_from_move_base: True if we fetch the goal position from topic <move_base_goal_topic_name> :param final_pointgoal_pos: goal location of navigation, measured in the world frame. If `fetch_goal_from_move_base` is True, this position is ignored """ # initialize the node self.node_name = node_name rospy.init_node(self.node_name) # bridge's publish and subscribe queue size # TODO: make them configurable by constructor argument self.sub_queue_size = 1 self.pub_queue_size = 1 # set up logger self.logger = utils_logging.setup_logger(self.node_name) # set max number of steps for navigation # TODO: make them configurable by constructor argument self.max_steps = 500 # last_action_done controls when to publish the next set # of observations self.last_action_lock = Lock() with self.last_action_lock: self.count_steps = 0 self.last_action_done = True # current pose of the agent self.curr_pose_lock = Lock() with self.curr_pose_lock: self.prev_pos = None # NOTE: self.prev_pos is for visualization only self.curr_pos = None self.curr_rotation = None # initialize pointogal_reached flag self.pointgoal_reached_lock = Lock() with self.pointgoal_reached_lock: self.pointgoal_reached = False # initialize final pointgoal position self.final_pointgoal_lock = Lock() with self.final_pointgoal_lock: self.final_pointgoal_pos = None self.pointgoal_set = False if fetch_goal_from_move_base: # subscribe from goal position topic and get # the point-goal from there self.sub_goal = rospy.Subscriber( move_base_goal_topic_name, PoseStamped, self.callback_register_goal, queue_size=self.sub_queue_size ) else: # get goal directly from constructor argument with self.final_pointgoal_lock: self.final_pointgoal_pos = final_pointgoal_pos self.logger.info(f"Final pointgoal position set to: {self.final_pointgoal_pos}") self.pointgoal_set = True # subscribe from Gazebo-facing sensor topics self.sub_rgb = message_filters.Subscriber(gazebo_rgb_topic_name, Image) self.sub_depth = message_filters.Subscriber(gazebo_depth_topic_name, Image) self.sub_odom = message_filters.Subscriber(gazebo_odom_topic_name, Odometry) self.ts = TimeSynchronizer( [self.sub_rgb, self.sub_depth, self.sub_odom], queue_size=self.sub_queue_size, ) self.ts.registerCallback(self.callback_obs_from_gazebo) # subscribe from `last_action_done/` self.sub_last_action_done = rospy.Subscriber( "last_action_done", Int16, self.callback_signal_last_action, queue_size=self.sub_queue_size ) # publish to Habitat-agent-facing sensor topics self.pub_rgb = rospy.Publisher( "rgb", Image, queue_size=self.pub_queue_size ) self.pub_depth = rospy.Publisher( "depth", DepthImage, queue_size=self.pub_queue_size ) self.pub_pointgoal_with_gps_compass = rospy.Publisher( "pointgoal_with_gps_compass", PointGoalWithGPSCompass, queue_size=self.pub_queue_size ) # establish get_agent_pose service server self.get_agent_pose_service = rospy.Service( f"{PACKAGE_NAME}/{node_name}/{ServiceNames.GET_AGENT_POSE}", GetAgentPose, self.get_agent_pose, ) # publish initial/goal position for visualization self.marker_array_lock = Lock() with self.marker_array_lock: self.marker_array = MarkerArray() self.pub_init_and_goal_pos = rospy.Publisher( "visualization_marker_array", MarkerArray, queue_size=self.pub_queue_size ) self.logger.info("gazebo -> habitat agent bridge initialized") def pos_to_point(self, pos): r""" Produce a ROS point from a position. :param pos: position as a (3, ) numpy array. :return a ROS point. """ point = Point() point.x = pos[0] point.y = pos[1] point.z = pos[2] return point def add_pos_to_marker_array(self, pos_type, pos_0, pos_1=None, rot=None): r""" Add position(s) to the marker array for visualization. Require: 1) self.marker_array_lock not being held by the calling thread 2) the lock guarding `pos_0` and `pos_1` being held by the calling thread 3) self.last_action_lock is being held by the calling thread :param pos_type: can only be one of the following: 1) "curr" - path from previous to current position of the agent 2) "init" - inital position of the agent 3) "goal" - final goal position :param pos_0: position to add marker to :param pos_1: second position for drawing line segment; Only used if `pos_type` is "curr" :param rot: orientation of the marker """ # precondition checks assert pos_type in ["curr", "init", "goal"] if pos_type == "curr": pos_1 is not None # code adapted from # https://answers.ros.org/question/11135/plotting-a-markerarray-of-spheres-with-rviz/ pos_marker = Marker() pos_marker.id = self.count_steps pos_marker.header.frame_id = "odom" pos_marker.action = pos_marker.ADD if pos_type == "curr": pos_marker.type = pos_marker.LINE_STRIP point_0 = self.pos_to_point(pos_0) point_1 = self.pos_to_point(pos_1) pos_marker.points.append(point_0) pos_marker.points.append(point_1) pos_marker.scale.x = 0.05 pos_marker.color.a = 1.0 pos_marker.color.g = 1.0 elif pos_type == "init": pos_marker.type = pos_marker.SPHERE pos_marker.pose.position.x = pos_0[0] pos_marker.pose.position.y = pos_0[1] pos_marker.pose.position.z = pos_0[2] pos_marker.scale.x = 0.4 pos_marker.scale.y = 0.4 pos_marker.scale.z = 0.4 pos_marker.color.a = 1.0 pos_marker.color.b = 1.0 elif pos_type == "goal": pos_marker.type = pos_marker.SPHERE pos_marker.pose.position.x = pos_0[0] pos_marker.pose.position.y = pos_0[1] pos_marker.pose.position.z = pos_0[2] pos_marker.scale.x = 0.4 pos_marker.scale.y = 0.4 pos_marker.scale.z = 0.4 pos_marker.color.a = 1.0 pos_marker.color.r = 1.0 with self.marker_array_lock: self.marker_array.markers.append(pos_marker) def publish_marker_array(self): r""" Publish the marker array. """ with self.marker_array_lock: self.pub_init_and_goal_pos.publish(self.marker_array) def compute_pointgoal(self): r""" Compute distance-to-goal and angle-to-goal. Modified upon habitat.task.nav.nav.PointGoalSensor._compute_pointgoal(). Require 1) `self.curr_pose_lock` and `self.final_pointgoal_lock` already acquired in the calling thread :return tuple 1) distance-to-goal, 2) angle-to-goal """ # get the yaw angle _, _, yaw = euler_from_quaternion(self.curr_rotation) # build local->world matrix local_to_world = rotation_matrix(yaw, (0, 0, 1)) # build world->local matrix world_to_local = np.linalg.inv(local_to_world) # compute direction vector in world frame direction_vector_world = np.zeros((4, )) direction_vector_world[0:3] = self.final_pointgoal_pos - self.curr_pos direction_vector_world[-1] = 0 # compute direction vector in local frame direction_vector_local = np.matmul(world_to_local, direction_vector_world)[0:3] rho, phi = cartesian_to_polar( direction_vector_local[0], direction_vector_local[1] ) return rho, phi def rgb_msg_to_img(self, rgb_msg, dim): r""" Extract RGB image from RGB message. Further compress the RGB image to size `dim` x `dim`. :param rgb_msg: RGB sensor reading from Gazebo :param dim: dimension of the RGB observation :return: RGB observation as a numpy array """ rgb_img = CvBridge().imgmsg_to_cv2(rgb_msg, desired_encoding="rgb8") rgb_img = cv2.resize(rgb_img, (dim, dim), interpolation = cv2.INTER_AREA) return rgb_img def depth_msg_to_img(self, depth_msg, dim): r""" Extract depth image from depth message. Further compress the depth image to size `dim` x `dim`. :param depth_msg: Depth sensor reading from Gazebo :param dim: dimension of the depth observation :return: Depth observation as a numpy array """ depth_img_original = np.copy(CvBridge().imgmsg_to_cv2( depth_msg, desired_encoding="passthrough")) # remove nan values by replacing with 0's # idea: https://github.com/stereolabs/zed-ros-wrapper/issues/67 for row in range(depth_img_original.shape[0]): for col in range(depth_img_original.shape[1]): if np.isnan(depth_img_original[row][col]): depth_img_original[row][col] = 0.0 #depth_img_normalized = cv2.normalize( # depth_img_original, # None, # alpha=0, # beta=255.0, # norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F #) #depth_img_resized = cv2.resize(depth_img_normalized, # (dim, dim), # interpolation = cv2.INTER_AREA #) depth_img_resized = cv2.resize(depth_img_original, (dim, dim), interpolation = cv2.INTER_AREA ) depth_img = np.array(depth_img_resized, dtype=np.float64) #depth_img_pil = PILImage.fromarray(depth_img) #depth_img_pil.save("gazebo_obs/depth.png", mode="L") return depth_img def update_pose(self, odom_msg): r""" Update current position, current rotation, previous position. Require `self.curr_pose_lock` already acquired by the calling thread :param odom_msg: Odometry data from Gazebo """ self.prev_pos = self.curr_pos self.curr_pos = np.array( [odom_msg.pose.pose.position.x, odom_msg.pose.pose.position.y, odom_msg.pose.pose.position.z ] ) self.curr_rotation = [ odom_msg.pose.pose.orientation.x, odom_msg.pose.pose.orientation.y, odom_msg.pose.pose.orientation.z, odom_msg.pose.pose.orientation.w ] def callback_obs_from_gazebo(self, rgb_msg, depth_msg, odom_msg): r""" Upon receiving a set of RGBD observations and odometry data from Gazebo, publishes 1) the observations to `rgb/` and `depth/` topic for a Habitat agent to read; 2) current GPS+Compass data. Only publishes iff all following conditions are satisfied: 1) on reset or after the last action has been completed, 2) pointogoal is set, 3) pointgoal not reached yet. :param rgb_msg: RGB sensor reading from Gazebo :param depth_msg: Depth sensor reading from Gazebo :param odom_msg: Odometry data from Gazebo """ with self.last_action_lock: with self.pointgoal_reached_lock: with self.final_pointgoal_lock: if ( self.last_action_done and self.pointgoal_set and not self.pointgoal_reached and not (self.count_steps >= self.max_steps) ): # publish a new set of observations if last action's done, # pointgoal's set and navigation not completed yet # get a header object and assign time h = Header() h.stamp = rospy.Time.now() # create RGB message for Habitat rgb_img = self.rgb_msg_to_img(rgb_msg, 720) rgb_msg_for_hab = CvBridge().cv2_to_imgmsg(rgb_img, encoding="rgb8") rgb_msg_for_hab.header = h # create depth message for Habitat depth_img = self.depth_msg_to_img(depth_msg, 720) depth_msg_for_hab = DepthImage() depth_msg_for_hab.height, depth_msg_for_hab.width = depth_img.shape depth_msg_for_hab.step = depth_msg_for_hab.width depth_msg_for_hab.data = np.ravel(depth_img) depth_msg_for_hab.header = h with self.curr_pose_lock: # update pose and compute current GPS+Compass info self.update_pose(odom_msg) distance_to_goal, angle_to_goal = self.compute_pointgoal() ptgoal_gps_msg = PointGoalWithGPSCompass() ptgoal_gps_msg.distance_to_goal = distance_to_goal ptgoal_gps_msg.angle_to_goal = angle_to_goal ptgoal_gps_msg.header = h # publish observations self.pub_rgb.publish(rgb_msg_for_hab) self.pub_depth.publish(depth_msg_for_hab) self.pub_pointgoal_with_gps_compass.publish(ptgoal_gps_msg) # block further sensor callbacks self.last_action_done = False # add the current position to the marker array for # visualization with self.curr_pose_lock: if self.count_steps == 0: self.logger.info(f"initial agent position: {self.curr_pos}") self.add_pos_to_marker_array( "init", self.curr_pos ) else: self.add_pos_to_marker_array( "curr", self.prev_pos, self.curr_pos, self.curr_rotation ) elif( self.last_action_done and self.pointgoal_set and ( self.pointgoal_reached or self.count_steps >= self.max_steps ) ): # if the navigation is completed, publish data # for visualization self.logger.info(f"navigation completed after {self.count_steps} steps") with self.curr_pose_lock: self.logger.info(f"final agent position: {self.curr_pos}") self.add_pos_to_marker_array( "goal", self.final_pointgoal_pos ) self.publish_marker_array() self.last_action_done = False else: # otherwise, drop the observations return def callback_register_goal(self, goal_msg): r""" Register point-goal position w.r.t. the world frame. :param goal_msg: point-goal position from move_base """ with self.final_pointgoal_lock: self.final_pointgoal_pos = np.array([ goal_msg.pose.position.x, goal_msg.pose.position.y, goal_msg.pose.position.z ]) self.pointgoal_set = True self.logger.info(f"Final pointgoal position set to: {self.final_pointgoal_pos}") def callback_signal_last_action(self, done_msg): r""" Signal the last action being done; toggle `pointgoal_reached` flag if the last action is `STOP`. """ if done_msg.data == 1: # last action is `STOP` with self.pointgoal_reached_lock: self.pointgoal_reached = True with self.last_action_lock: # increment step counter and signal last action being done self.count_steps += 1 self.last_action_done = True def get_agent_pose(self, request): r""" ROS service handler which returns the current pose of the agent. :param request: not used :returns: current pose of the agent """ pose = Pose() with self.curr_pose_lock: pose.position.x = self.curr_pos[0] pose.position.y = self.curr_pos[1] pose.position.z = self.curr_pos[2] pose.orientation.x = self.curr_rotation[0] pose.orientation.y = self.curr_rotation[1] pose.orientation.z = self.curr_rotation[2] pose.orientation.w = self.curr_rotation[3] return pose def spin_until_shutdown(self): r""" Let the node spin until shutdown. """ rospy.spin() if __name__ == "__main__": main()
39.702166
96
0.586815
#!/usr/bin/env python import argparse import numpy as np import rospy import message_filters from message_filters import TimeSynchronizer from ros_x_habitat.msg import PointGoalWithGPSCompass, DepthImage from sensor_msgs.msg import Image from cv_bridge import CvBridge import cv2 from PIL import Image as PILImage from nav_msgs.msg import Odometry from std_msgs.msg import Header, Int16 from geometry_msgs.msg import PoseStamped, Pose, Point import quaternion from habitat.tasks.utils import cartesian_to_polar from tf.transformations import euler_from_quaternion, rotation_matrix from visualization_msgs.msg import Marker, MarkerArray from threading import Lock from ros_x_habitat.srv import GetAgentPose from src.constants.constants import PACKAGE_NAME, ServiceNames from src.utils import utils_logging class GazeboToHabitatAgent: r""" A class to represent a ROS node which subscribes from Gazebo sensor topics and publishes to Habitat agent's sensor topics. """ def __init__( self, node_name: str, gazebo_rgb_topic_name: str, gazebo_depth_topic_name: str, gazebo_odom_topic_name: str, move_base_goal_topic_name: str, fetch_goal_from_move_base: bool=False, final_pointgoal_pos: np.ndarray = np.array([0.0, 0.0, 0.0]), ): r""" Instantiates the Gazebo->Habitat agent bridge. :param node_name: name of the bridge node :param gazebo_rgb_topic_name: name of the topic on which Gazebo publishes RGB observations :param gazebo_depth_topic_name: name of the topic on which Gazebo publishes depth observations :param gazebo_odom_topic_name: name of the topic on which Gazebo publishes odometry data :param move_base_goal_topic_name: name of the topic on which the move_base package publishes navigation goals :param fetch_goal_from_move_base: True if we fetch the goal position from topic <move_base_goal_topic_name> :param final_pointgoal_pos: goal location of navigation, measured in the world frame. If `fetch_goal_from_move_base` is True, this position is ignored """ # initialize the node self.node_name = node_name rospy.init_node(self.node_name) # bridge's publish and subscribe queue size # TODO: make them configurable by constructor argument self.sub_queue_size = 1 self.pub_queue_size = 1 # set up logger self.logger = utils_logging.setup_logger(self.node_name) # set max number of steps for navigation # TODO: make them configurable by constructor argument self.max_steps = 500 # last_action_done controls when to publish the next set # of observations self.last_action_lock = Lock() with self.last_action_lock: self.count_steps = 0 self.last_action_done = True # current pose of the agent self.curr_pose_lock = Lock() with self.curr_pose_lock: self.prev_pos = None # NOTE: self.prev_pos is for visualization only self.curr_pos = None self.curr_rotation = None # initialize pointogal_reached flag self.pointgoal_reached_lock = Lock() with self.pointgoal_reached_lock: self.pointgoal_reached = False # initialize final pointgoal position self.final_pointgoal_lock = Lock() with self.final_pointgoal_lock: self.final_pointgoal_pos = None self.pointgoal_set = False if fetch_goal_from_move_base: # subscribe from goal position topic and get # the point-goal from there self.sub_goal = rospy.Subscriber( move_base_goal_topic_name, PoseStamped, self.callback_register_goal, queue_size=self.sub_queue_size ) else: # get goal directly from constructor argument with self.final_pointgoal_lock: self.final_pointgoal_pos = final_pointgoal_pos self.logger.info(f"Final pointgoal position set to: {self.final_pointgoal_pos}") self.pointgoal_set = True # subscribe from Gazebo-facing sensor topics self.sub_rgb = message_filters.Subscriber(gazebo_rgb_topic_name, Image) self.sub_depth = message_filters.Subscriber(gazebo_depth_topic_name, Image) self.sub_odom = message_filters.Subscriber(gazebo_odom_topic_name, Odometry) self.ts = TimeSynchronizer( [self.sub_rgb, self.sub_depth, self.sub_odom], queue_size=self.sub_queue_size, ) self.ts.registerCallback(self.callback_obs_from_gazebo) # subscribe from `last_action_done/` self.sub_last_action_done = rospy.Subscriber( "last_action_done", Int16, self.callback_signal_last_action, queue_size=self.sub_queue_size ) # publish to Habitat-agent-facing sensor topics self.pub_rgb = rospy.Publisher( "rgb", Image, queue_size=self.pub_queue_size ) self.pub_depth = rospy.Publisher( "depth", DepthImage, queue_size=self.pub_queue_size ) self.pub_pointgoal_with_gps_compass = rospy.Publisher( "pointgoal_with_gps_compass", PointGoalWithGPSCompass, queue_size=self.pub_queue_size ) # establish get_agent_pose service server self.get_agent_pose_service = rospy.Service( f"{PACKAGE_NAME}/{node_name}/{ServiceNames.GET_AGENT_POSE}", GetAgentPose, self.get_agent_pose, ) # publish initial/goal position for visualization self.marker_array_lock = Lock() with self.marker_array_lock: self.marker_array = MarkerArray() self.pub_init_and_goal_pos = rospy.Publisher( "visualization_marker_array", MarkerArray, queue_size=self.pub_queue_size ) self.logger.info("gazebo -> habitat agent bridge initialized") def pos_to_point(self, pos): r""" Produce a ROS point from a position. :param pos: position as a (3, ) numpy array. :return a ROS point. """ point = Point() point.x = pos[0] point.y = pos[1] point.z = pos[2] return point def add_pos_to_marker_array(self, pos_type, pos_0, pos_1=None, rot=None): r""" Add position(s) to the marker array for visualization. Require: 1) self.marker_array_lock not being held by the calling thread 2) the lock guarding `pos_0` and `pos_1` being held by the calling thread 3) self.last_action_lock is being held by the calling thread :param pos_type: can only be one of the following: 1) "curr" - path from previous to current position of the agent 2) "init" - inital position of the agent 3) "goal" - final goal position :param pos_0: position to add marker to :param pos_1: second position for drawing line segment; Only used if `pos_type` is "curr" :param rot: orientation of the marker """ # precondition checks assert pos_type in ["curr", "init", "goal"] if pos_type == "curr": pos_1 is not None # code adapted from # https://answers.ros.org/question/11135/plotting-a-markerarray-of-spheres-with-rviz/ pos_marker = Marker() pos_marker.id = self.count_steps pos_marker.header.frame_id = "odom" pos_marker.action = pos_marker.ADD if pos_type == "curr": pos_marker.type = pos_marker.LINE_STRIP point_0 = self.pos_to_point(pos_0) point_1 = self.pos_to_point(pos_1) pos_marker.points.append(point_0) pos_marker.points.append(point_1) pos_marker.scale.x = 0.05 pos_marker.color.a = 1.0 pos_marker.color.g = 1.0 elif pos_type == "init": pos_marker.type = pos_marker.SPHERE pos_marker.pose.position.x = pos_0[0] pos_marker.pose.position.y = pos_0[1] pos_marker.pose.position.z = pos_0[2] pos_marker.scale.x = 0.4 pos_marker.scale.y = 0.4 pos_marker.scale.z = 0.4 pos_marker.color.a = 1.0 pos_marker.color.b = 1.0 elif pos_type == "goal": pos_marker.type = pos_marker.SPHERE pos_marker.pose.position.x = pos_0[0] pos_marker.pose.position.y = pos_0[1] pos_marker.pose.position.z = pos_0[2] pos_marker.scale.x = 0.4 pos_marker.scale.y = 0.4 pos_marker.scale.z = 0.4 pos_marker.color.a = 1.0 pos_marker.color.r = 1.0 with self.marker_array_lock: self.marker_array.markers.append(pos_marker) def publish_marker_array(self): r""" Publish the marker array. """ with self.marker_array_lock: self.pub_init_and_goal_pos.publish(self.marker_array) def compute_pointgoal(self): r""" Compute distance-to-goal and angle-to-goal. Modified upon habitat.task.nav.nav.PointGoalSensor._compute_pointgoal(). Require 1) `self.curr_pose_lock` and `self.final_pointgoal_lock` already acquired in the calling thread :return tuple 1) distance-to-goal, 2) angle-to-goal """ # get the yaw angle _, _, yaw = euler_from_quaternion(self.curr_rotation) # build local->world matrix local_to_world = rotation_matrix(yaw, (0, 0, 1)) # build world->local matrix world_to_local = np.linalg.inv(local_to_world) # compute direction vector in world frame direction_vector_world = np.zeros((4, )) direction_vector_world[0:3] = self.final_pointgoal_pos - self.curr_pos direction_vector_world[-1] = 0 # compute direction vector in local frame direction_vector_local = np.matmul(world_to_local, direction_vector_world)[0:3] rho, phi = cartesian_to_polar( direction_vector_local[0], direction_vector_local[1] ) return rho, phi def rgb_msg_to_img(self, rgb_msg, dim): r""" Extract RGB image from RGB message. Further compress the RGB image to size `dim` x `dim`. :param rgb_msg: RGB sensor reading from Gazebo :param dim: dimension of the RGB observation :return: RGB observation as a numpy array """ rgb_img = CvBridge().imgmsg_to_cv2(rgb_msg, desired_encoding="rgb8") rgb_img = cv2.resize(rgb_img, (dim, dim), interpolation = cv2.INTER_AREA) return rgb_img def depth_msg_to_img(self, depth_msg, dim): r""" Extract depth image from depth message. Further compress the depth image to size `dim` x `dim`. :param depth_msg: Depth sensor reading from Gazebo :param dim: dimension of the depth observation :return: Depth observation as a numpy array """ depth_img_original = np.copy(CvBridge().imgmsg_to_cv2( depth_msg, desired_encoding="passthrough")) # remove nan values by replacing with 0's # idea: https://github.com/stereolabs/zed-ros-wrapper/issues/67 for row in range(depth_img_original.shape[0]): for col in range(depth_img_original.shape[1]): if np.isnan(depth_img_original[row][col]): depth_img_original[row][col] = 0.0 #depth_img_normalized = cv2.normalize( # depth_img_original, # None, # alpha=0, # beta=255.0, # norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F #) #depth_img_resized = cv2.resize(depth_img_normalized, # (dim, dim), # interpolation = cv2.INTER_AREA #) depth_img_resized = cv2.resize(depth_img_original, (dim, dim), interpolation = cv2.INTER_AREA ) depth_img = np.array(depth_img_resized, dtype=np.float64) #depth_img_pil = PILImage.fromarray(depth_img) #depth_img_pil.save("gazebo_obs/depth.png", mode="L") return depth_img def update_pose(self, odom_msg): r""" Update current position, current rotation, previous position. Require `self.curr_pose_lock` already acquired by the calling thread :param odom_msg: Odometry data from Gazebo """ self.prev_pos = self.curr_pos self.curr_pos = np.array( [odom_msg.pose.pose.position.x, odom_msg.pose.pose.position.y, odom_msg.pose.pose.position.z ] ) self.curr_rotation = [ odom_msg.pose.pose.orientation.x, odom_msg.pose.pose.orientation.y, odom_msg.pose.pose.orientation.z, odom_msg.pose.pose.orientation.w ] def callback_obs_from_gazebo(self, rgb_msg, depth_msg, odom_msg): r""" Upon receiving a set of RGBD observations and odometry data from Gazebo, publishes 1) the observations to `rgb/` and `depth/` topic for a Habitat agent to read; 2) current GPS+Compass data. Only publishes iff all following conditions are satisfied: 1) on reset or after the last action has been completed, 2) pointogoal is set, 3) pointgoal not reached yet. :param rgb_msg: RGB sensor reading from Gazebo :param depth_msg: Depth sensor reading from Gazebo :param odom_msg: Odometry data from Gazebo """ with self.last_action_lock: with self.pointgoal_reached_lock: with self.final_pointgoal_lock: if ( self.last_action_done and self.pointgoal_set and not self.pointgoal_reached and not (self.count_steps >= self.max_steps) ): # publish a new set of observations if last action's done, # pointgoal's set and navigation not completed yet # get a header object and assign time h = Header() h.stamp = rospy.Time.now() # create RGB message for Habitat rgb_img = self.rgb_msg_to_img(rgb_msg, 720) rgb_msg_for_hab = CvBridge().cv2_to_imgmsg(rgb_img, encoding="rgb8") rgb_msg_for_hab.header = h # create depth message for Habitat depth_img = self.depth_msg_to_img(depth_msg, 720) depth_msg_for_hab = DepthImage() depth_msg_for_hab.height, depth_msg_for_hab.width = depth_img.shape depth_msg_for_hab.step = depth_msg_for_hab.width depth_msg_for_hab.data = np.ravel(depth_img) depth_msg_for_hab.header = h with self.curr_pose_lock: # update pose and compute current GPS+Compass info self.update_pose(odom_msg) distance_to_goal, angle_to_goal = self.compute_pointgoal() ptgoal_gps_msg = PointGoalWithGPSCompass() ptgoal_gps_msg.distance_to_goal = distance_to_goal ptgoal_gps_msg.angle_to_goal = angle_to_goal ptgoal_gps_msg.header = h # publish observations self.pub_rgb.publish(rgb_msg_for_hab) self.pub_depth.publish(depth_msg_for_hab) self.pub_pointgoal_with_gps_compass.publish(ptgoal_gps_msg) # block further sensor callbacks self.last_action_done = False # add the current position to the marker array for # visualization with self.curr_pose_lock: if self.count_steps == 0: self.logger.info(f"initial agent position: {self.curr_pos}") self.add_pos_to_marker_array( "init", self.curr_pos ) else: self.add_pos_to_marker_array( "curr", self.prev_pos, self.curr_pos, self.curr_rotation ) elif( self.last_action_done and self.pointgoal_set and ( self.pointgoal_reached or self.count_steps >= self.max_steps ) ): # if the navigation is completed, publish data # for visualization self.logger.info(f"navigation completed after {self.count_steps} steps") with self.curr_pose_lock: self.logger.info(f"final agent position: {self.curr_pos}") self.add_pos_to_marker_array( "goal", self.final_pointgoal_pos ) self.publish_marker_array() self.last_action_done = False else: # otherwise, drop the observations return def callback_register_goal(self, goal_msg): r""" Register point-goal position w.r.t. the world frame. :param goal_msg: point-goal position from move_base """ with self.final_pointgoal_lock: self.final_pointgoal_pos = np.array([ goal_msg.pose.position.x, goal_msg.pose.position.y, goal_msg.pose.position.z ]) self.pointgoal_set = True self.logger.info(f"Final pointgoal position set to: {self.final_pointgoal_pos}") def callback_signal_last_action(self, done_msg): r""" Signal the last action being done; toggle `pointgoal_reached` flag if the last action is `STOP`. """ if done_msg.data == 1: # last action is `STOP` with self.pointgoal_reached_lock: self.pointgoal_reached = True with self.last_action_lock: # increment step counter and signal last action being done self.count_steps += 1 self.last_action_done = True def get_agent_pose(self, request): r""" ROS service handler which returns the current pose of the agent. :param request: not used :returns: current pose of the agent """ pose = Pose() with self.curr_pose_lock: pose.position.x = self.curr_pos[0] pose.position.y = self.curr_pos[1] pose.position.z = self.curr_pos[2] pose.orientation.x = self.curr_rotation[0] pose.orientation.y = self.curr_rotation[1] pose.orientation.z = self.curr_rotation[2] pose.orientation.w = self.curr_rotation[3] return pose def spin_until_shutdown(self): r""" Let the node spin until shutdown. """ rospy.spin() def main(): # parse input arguments parser = argparse.ArgumentParser() parser.add_argument( "--node-name", default="gazebo_to_habitat_agent", type=str ) parser.add_argument( "--gazebo-rgb-topic-name", default="camera/rgb/image_raw", type=str ) parser.add_argument( "--gazebo-depth-topic-name", default="camera/depth/image_raw", type=str ) parser.add_argument( "--gazebo-odom-topic-name", default="odom", type=str ) parser.add_argument( "--move-base-goal-topic-name", default="/move_base_simple/goal", type=str ) parser.add_argument( "--fetch-goal-from-move-base", default=False, action="store_true" ) parser.add_argument( "--pointgoal-location", nargs="+", type=float ) args = parser.parse_args() # if the user is not providing pointgoal location, use the origin if args.pointgoal_location is None: pointgoal_list = [0.0, 0.0, 0.0] else: pointgoal_list = args.pointgoal_location # instantiate the bridge bridge = GazeboToHabitatAgent( node_name=args.node_name, gazebo_rgb_topic_name=args.gazebo_rgb_topic_name, gazebo_depth_topic_name=args.gazebo_depth_topic_name, gazebo_odom_topic_name=args.gazebo_odom_topic_name, move_base_goal_topic_name=args.move_base_goal_topic_name, fetch_goal_from_move_base=args.fetch_goal_from_move_base, final_pointgoal_pos=np.array(pointgoal_list), ) # spins until receiving the shutdown signal bridge.spin_until_shutdown() if __name__ == "__main__": main()
1,679
0
23
c9531b3c2f83920008aaf29bed3e2590a463efbf
2,265
py
Python
src/didery/controllers/static.py
SmithSamuelM/didery
8181cd2dd2aa711d0b559acdc8ba1c7e2e8ba2fb
[ "Apache-2.0" ]
8
2018-09-07T09:26:52.000Z
2021-01-16T12:22:07.000Z
src/didery/controllers/static.py
SmithSamuelM/didery
8181cd2dd2aa711d0b559acdc8ba1c7e2e8ba2fb
[ "Apache-2.0" ]
184
2018-04-19T17:46:02.000Z
2019-05-21T19:04:30.000Z
src/didery/controllers/static.py
SmithSamuelM/didery
8181cd2dd2aa711d0b559acdc8ba1c7e2e8ba2fb
[ "Apache-2.0" ]
3
2018-09-26T19:16:30.000Z
2018-12-18T18:50:40.000Z
# ================================================== # # DASHBOARD # # ================================================== # # Author: Brady Hammond # # Created: 05/04/2018 # # Last Edited: # # Last Edited By: # # ================================================== # # IMPORTS # # ================================================== # from __future__ import generator_stop import falcon import mimetypes import os # ================================================== # # CLASS DEFINITIONS # # ================================================== # class StaticSink(object): """ Class for Falcon sink endpoint serving static files. """ # ================================================== # # EOF # # ================================================== #
39.736842
80
0.381457
# ================================================== # # DASHBOARD # # ================================================== # # Author: Brady Hammond # # Created: 05/04/2018 # # Last Edited: # # Last Edited By: # # ================================================== # # IMPORTS # # ================================================== # from __future__ import generator_stop import falcon import mimetypes import os # ================================================== # # CLASS DEFINITIONS # # ================================================== # class StaticSink(object): """ Class for Falcon sink endpoint serving static files. """ def __init__(self, *pa, **kwa): super().__init__(*pa, **kwa) self.projectDirpath = os.path.dirname( os.path.dirname( os.path.abspath( os.path.expanduser(__file__)))) self.staticDirpath = os.path.join(self.projectDirpath, "static") def __call__(self, req, rep): path = req.path splits = path.split("/")[1:] if not splits[0]: splits = splits[1:] if splits and splits[0] == "static": splits = splits[1:] if not splits: filepath = "main.html" else: filepath = "/".join(splits) filepath = os.path.join(self.staticDirpath, filepath) if not os.path.exists(filepath): raise falcon.HTTPError(falcon.HTTP_NOT_FOUND, 'Missing Resource', 'File "{}" not found or forbidden'.format(filepath)) filetype = mimetypes.guess_type(filepath, strict=True)[0] rep.set_header("Content-Type", "{}; charset=UTF-8".format(filetype)) rep.status = falcon.HTTP_200 with open(filepath, 'rb') as f: rep.body = f.read() # ================================================== # # EOF # # ================================================== #
1,151
0
53
c72a4448e4129fda1ce176b0155b4e9ef10901e5
1,234
py
Python
app.py
jmuelbert/SciHubEVA
96c5f623d5710806d3ff224f2e6f6ba83e75de56
[ "MIT" ]
null
null
null
app.py
jmuelbert/SciHubEVA
96c5f623d5710806d3ff224f2e6f6ba83e75de56
[ "MIT" ]
5
2021-03-31T20:10:22.000Z
2022-03-12T00:54:40.000Z
app.py
jmuelbert/SciHubEVA
96c5f623d5710806d3ff224f2e6f6ba83e75de56
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import locale from PySide2.QtCore import Qt, QTranslator from PySide2.QtGui import QGuiApplication, QIcon, QFont from scihubeva.scihubeva_dialog import SciHubEVADialog from scihubeva.utils import * import scihubeva.resources if hasattr(Qt, 'AA_EnableHighDpiScaling'): QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True) if hasattr(Qt, 'AA_UseHighDpiPixmaps'): QGuiApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True) if __name__ == '__main__': app_path = os.path.abspath(os.path.dirname(sys.argv[0])) os.environ['QT_QUICK_CONTROLS_CONF'] = (CONF_DIR / 'qtquickcontrols2.conf').resolve().as_posix() app = QGuiApplication(sys.argv) lang = locale.getdefaultlocale()[0] lang_file_path = (TRANSLATION_DIR / 'SciHubEVA_{lang}.qm'.format(lang=lang)).resolve().as_posix() translator = QTranslator() translator.load(lang_file_path) app.installTranslator(translator) icon_file_path = (IMAGES_DIR / 'SciHubEVA-icon.png').resolve().as_posix() app.setWindowIcon(QIcon(icon_file_path)) if is_windows(): app.setFont(QFont('Microsoft YaHei')) eva = SciHubEVADialog() sys.exit(app.exec_())
29.380952
101
0.73906
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import locale from PySide2.QtCore import Qt, QTranslator from PySide2.QtGui import QGuiApplication, QIcon, QFont from scihubeva.scihubeva_dialog import SciHubEVADialog from scihubeva.utils import * import scihubeva.resources if hasattr(Qt, 'AA_EnableHighDpiScaling'): QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True) if hasattr(Qt, 'AA_UseHighDpiPixmaps'): QGuiApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True) if __name__ == '__main__': app_path = os.path.abspath(os.path.dirname(sys.argv[0])) os.environ['QT_QUICK_CONTROLS_CONF'] = (CONF_DIR / 'qtquickcontrols2.conf').resolve().as_posix() app = QGuiApplication(sys.argv) lang = locale.getdefaultlocale()[0] lang_file_path = (TRANSLATION_DIR / 'SciHubEVA_{lang}.qm'.format(lang=lang)).resolve().as_posix() translator = QTranslator() translator.load(lang_file_path) app.installTranslator(translator) icon_file_path = (IMAGES_DIR / 'SciHubEVA-icon.png').resolve().as_posix() app.setWindowIcon(QIcon(icon_file_path)) if is_windows(): app.setFont(QFont('Microsoft YaHei')) eva = SciHubEVADialog() sys.exit(app.exec_())
0
0
0
718fcbeaca7ad960cba411e1d228ff504c056497
531
py
Python
hass_ci_ignore.py
mikevansighem/homeassistant
40d1c89113c9bc5ff479bc7374d077027642401b
[ "MIT" ]
1
2021-09-12T17:51:38.000Z
2021-09-12T17:51:38.000Z
hass_ci_ignore.py
mikevansighem/homeassistant
40d1c89113c9bc5ff479bc7374d077027642401b
[ "MIT" ]
54
2021-09-19T08:20:53.000Z
2022-03-28T18:22:25.000Z
hass_ci_ignore.py
mikevansighem/homeassistant
40d1c89113c9bc5ff479bc7374d077027642401b
[ "MIT" ]
null
null
null
# A basic script to remove any part of the configuration that is described in "hassci" #Open the file with open(r'configuration.yaml', 'r') as file: data = file.read() # Open ignore file with open('.hass_ci') as ignore_file: # Open ignore file and replace matches line by line for search_text in ignore_file: data = data.replace(search_text, "#REDACTED") # Write to file with open(r'configuration.yaml', 'w') as file: file.write(data) print("configuration.yaml has been redacted.")
27.947368
86
0.681733
# A basic script to remove any part of the configuration that is described in "hassci" #Open the file with open(r'configuration.yaml', 'r') as file: data = file.read() # Open ignore file with open('.hass_ci') as ignore_file: # Open ignore file and replace matches line by line for search_text in ignore_file: data = data.replace(search_text, "#REDACTED") # Write to file with open(r'configuration.yaml', 'w') as file: file.write(data) print("configuration.yaml has been redacted.")
0
0
0
3189f2abd2559448f78a1d712c311f6a95570583
16,948
py
Python
test/urlobject_test.py
vartagg/urlblocks-new
b6c34ea9cd46ead2b0b1e5479b5b69e3a781cbfe
[ "Unlicense" ]
null
null
null
test/urlobject_test.py
vartagg/urlblocks-new
b6c34ea9cd46ead2b0b1e5479b5b69e3a781cbfe
[ "Unlicense" ]
null
null
null
test/urlobject_test.py
vartagg/urlblocks-new
b6c34ea9cd46ead2b0b1e5479b5b69e3a781cbfe
[ "Unlicense" ]
null
null
null
import platform import doctest import unittest from nose.tools import assert_raises from urlblocks import urlblocks as urlblocks_module from urlblocks import URL from urlblocks.six import text_type, u, print_ def dictsort(d): """``repr()`` a dictionary with sorted key/value pairs, for doctests.""" items = sorted(d.items()) print_('{' + ', '.join('%r: %r' % (k, v) for k, v in items) + '}')
44.020779
108
0.66645
import platform import doctest import unittest from nose.tools import assert_raises from urlblocks import urlblocks as urlblocks_module from urlblocks import URL from urlblocks.six import text_type, u, print_ def dictsort(d): """``repr()`` a dictionary with sorted key/value pairs, for doctests.""" items = sorted(d.items()) print_('{' + ', '.join('%r: %r' % (k, v) for k, v in items) + '}') class URLObjectTest(unittest.TestCase): def setUp(self): self.url_string = u("https://github.com/zacharyvoase/urlblocks?spam=eggs#foo") def test_urlblocks_preserves_equality_with_the_original_string(self): assert URL(self.url_string) == self.url_string def test_urlblocks_preserves_the_hash_of_the_original_string(self): assert hash(URL(self.url_string)) == hash(self.url_string) def test_calling_unicode_on_a_urlblocks_returns_a_normal_string(self): url = URL(self.url_string) # Normally `type(x) is Y` is a bad idea, but it's exactly what we want. assert type(text_type(url)) is text_type assert text_type(url) == self.url_string class SphinxDoctestsTest(unittest.TestCase): def test__doctest(self): result = doctest.testmod(urlblocks_module, extraglobs={'dictsort': dictsort}) if platform.python_version() < '3.2': # Don't run doctests on pre-3.2. return failed = result.failed attempted = result.attempted self.assertTrue(attempted > 0, "No doctests were found") self.assertEquals(failed, 0, "There are failed doctests") class URLObjectRelativeTest(unittest.TestCase): def setUp(self): self.url = URL("https://github.com/zacharyvoase/urlblocks?spam=eggs#foo") def test_relative_with_scheme_returns_the_given_URL(self): assert self.url.relative('http://example.com/abc') == 'http://example.com/abc' def test_relative_with_netloc_returns_the_given_URL_but_preserves_scheme(self): assert self.url.relative('//example.com/abc') == 'https://example.com/abc' def test_relative_with_path_replaces_path_and_removes_query_string_and_fragment(self): assert self.url.relative('another-project') == 'https://github.com/zacharyvoase/another-project' assert self.url.relative('.') == 'https://github.com/zacharyvoase/' assert self.url.relative('/dvxhouse/intessa') == 'https://github.com/dvxhouse/intessa' assert self.url.relative('/dvxhouse/intessa') == 'https://github.com/dvxhouse/intessa' def test_relative_with_empty_string_removes_fragment_but_preserves_query(self): # The empty string is treated as a path meaning 'the current location'. assert self.url.relative('') == self.url.without_fragment() def test_relative_with_query_string_removes_fragment(self): assert self.url.relative('?name=value') == self.url.without_fragment().with_query('name=value') def test_relative_with_fragment_removes_nothing(self): assert self.url.relative('#foobar') == self.url.with_fragment('foobar') def test_compound_relative_urls(self): assert self.url.relative('//example.com/a/b') == 'https://example.com/a/b' assert self.url.relative('//example.com/a/b#bar') == 'https://example.com/a/b#bar' assert self.url.relative('//example.com/a/b?c=d#bar') == 'https://example.com/a/b?c=d#bar' assert self.url.relative('/a/b?c=d#bar') == 'https://github.com/a/b?c=d#bar' assert self.url.relative('?c=d#bar') == 'https://github.com/zacharyvoase/urlblocks?c=d#bar' assert self.url.relative('#bar') == 'https://github.com/zacharyvoase/urlblocks?spam=eggs#bar' class URLObjectPropertyTest(unittest.TestCase): def setUp(self): self.url = URL("https://github.com/zacharyvoase/urlblocks?spam=eggs#foo") def test_scheme_returns_scheme(self): assert self.url.scheme == 'https' def test_netloc_returns_netloc(self): assert self.url.netloc == 'github.com' def test_hostname_returns_hostname(self): assert self.url.hostname == 'github.com' url = URL("https://user:pass@github.com:443") assert url.hostname == 'github.com' def test_port_returns_port_or_None(self): assert self.url.port is None assert URL("https://github.com:412").port == 412 def test_default_port_returns_default_port_when_none_specified(self): assert self.url.default_port == 443 def test_default_port_returns_given_port_when_one_is_specified(self): assert URL("https://github.com:412").default_port == 412 def test_path_returns_path(self): assert self.url.path == '/zacharyvoase/urlblocks' def test_query_returns_query(self): assert self.url.query == 'spam=eggs' def test_query_list_returns_a_list_of_query_params(self): assert self.url.query_list == [('spam', 'eggs')] def test_query_dict_returns_a_dict_of_query_params(self): assert self.url.query_dict == {'spam': 'eggs'} def test_query_multi_dict_returns_a_multi_dict_of_query_params(self): url = URL('https://example.com/?spam=eggs&spam=ham&foo=bar') assert url.query_multi_dict == {'spam': ['eggs', 'ham'], 'foo': ['bar']} def test_fragment_returns_fragment(self): assert self.url.fragment == 'foo' def test_fragment_is_decoded_correctly(self): url = URL('https://example.com/#frag%20ment') assert url.fragment == 'frag ment' def test_auth_properties_can_parse_username_and_password(self): url = URL('https://zack:12345@github.com/') assert url.username == 'zack' assert url.password == '12345' assert url.auth == ('zack', '12345') def test_auth_properties_can_parse_username(self): url = URL('https://zack@github.com/') assert url.username == 'zack' assert url.password is None assert url.auth == ('zack', None) def test_auth_properties_return_None_with_no_username_or_password(self): url = URL('https://github.com/') assert url.username is None assert url.password is None assert url.auth == (None, None) class URLObjectModificationTest(unittest.TestCase): def setUp(self): self.url = URL('https://github.com/zacharyvoase/urlblocks?spam=eggs#foo') def test_with_scheme_replaces_scheme(self): assert (self.url.with_scheme('http') == 'http://github.com/zacharyvoase/urlblocks?spam=eggs#foo') def test_with_netloc_replaces_netloc(self): assert (self.url.with_netloc('example.com') == 'https://example.com/zacharyvoase/urlblocks?spam=eggs#foo') def test_with_hostname_replaces_hostname(self): url = URL('https://user:pass@github.com/') assert (url.with_hostname('example.com') == 'https://user:pass@example.com/') def test_with_username_adds_username(self): url = URL('https://github.com/') assert url.with_username('zack') == 'https://zack@github.com/' def test_with_username_replaces_username(self): url = URL('https://zack@github.com/') assert url.with_username('alice') == 'https://alice@github.com/' def test_without_username_removes_username(self): url = URL('https://zack@github.com/') assert url.without_username() == 'https://github.com/' def test_with_password_adds_password(self): url = URL('https://zack@github.com/') assert url.with_password('1234') == 'https://zack:1234@github.com/' def test_with_password_raises_ValueError_when_there_is_no_username(self): url = URL('https://github.com/') assert_raises(ValueError, lambda: url.with_password('1234')) def test_with_password_replaces_password(self): url = URL('https://zack:1234@github.com/') assert url.with_password('5678') == 'https://zack:5678@github.com/' def test_without_password_removes_password(self): url = URL('https://zack:1234@github.com/') assert url.without_password() == 'https://zack@github.com/' def test_with_auth_with_one_arg_adds_username(self): url = URL('https://github.com/') assert url.with_auth('zack') == 'https://zack@github.com/' def test_with_auth_with_one_arg_replaces_whole_auth_string_with_username(self): url = URL('https://alice:1234@github.com/') assert url.with_auth('zack') == 'https://zack@github.com/' def test_with_auth_with_two_args_adds_username_and_password(self): url = URL('https://github.com/') assert url.with_auth('zack', '1234') == 'https://zack:1234@github.com/' def test_with_auth_with_two_args_replaces_whole_auth_string_with_username_and_password(self): # Replaces username-only auth string url = URL('https://alice@github.com/') assert url.with_auth('zack', '1234') == 'https://zack:1234@github.com/' # Replaces username and password. url = URL('https://alice:4567@github.com/') assert url.with_auth('zack', '1234') == 'https://zack:1234@github.com/' def test_without_auth_removes_entire_auth_string(self): # No username or password => no-op. url = URL('https://github.com/') assert url.without_auth() == 'https://github.com/' # Username-only. url = URL('https://alice@github.com/') assert url.without_auth() == 'https://github.com/' # Username and password. url = URL('https://alice:1234@github.com/') assert url.without_auth() == 'https://github.com/' def test_with_port_adds_port_number(self): assert (self.url.with_port(24) == 'https://github.com:24/zacharyvoase/urlblocks?spam=eggs#foo') def test_with_port_replaces_port_number(self): url = URL('https://github.com:59/') assert url.with_port(67) == 'https://github.com:67/' def test_without_port_removes_port_number(self): url = URL('https://github.com:59/') assert url.without_port() == 'https://github.com/' def test_with_path_replaces_path(self): assert (self.url.with_path('/dvxhouse/intessa') == 'https://github.com/dvxhouse/intessa?spam=eggs#foo') def test_root_goes_to_root_path(self): assert self.url.root == 'https://github.com/?spam=eggs#foo' def test_parent_jumps_up_one_level(self): url = URL('https://github.com/zacharyvoase/urlblocks') assert url.parent == 'https://github.com/zacharyvoase/' assert url.parent.parent == 'https://github.com/' def test_add_path_segment_adds_a_path_segment(self): url = URL('https://github.com/zacharyvoase/urlblocks') assert (url.add_path_segment('tree') == 'https://github.com/zacharyvoase/urlblocks/tree') assert (url.add_path_segment('tree/master') == 'https://github.com/zacharyvoase/urlblocks/tree%2Fmaster') def test_add_path_adds_a_partial_path(self): url = URL('https://github.com/zacharyvoase/urlblocks') assert (url.add_path('tree') == 'https://github.com/zacharyvoase/urlblocks/tree') assert (url.add_path('tree/master') == 'https://github.com/zacharyvoase/urlblocks/tree/master') def test_is_leaf(self): assert URL('https://github.com/zacharyvoase/urlblocks').is_leaf assert not URL('https://github.com/zacharyvoase/').is_leaf def test_with_query_replaces_query(self): assert (self.url.with_query('spam-ham-eggs') == 'https://github.com/zacharyvoase/urlblocks?spam-ham-eggs#foo') def test_without_query_removes_query(self): assert (self.url.without_query() == 'https://github.com/zacharyvoase/urlblocks#foo') def test_add_query_param_adds_one_query_parameter(self): assert (self.url.add_query_param('spam', 'ham') == 'https://github.com/zacharyvoase/urlblocks?spam=eggs&spam=ham#foo') def test_add_query_params_adds_multiple_query_parameters(self): assert (self.url.add_query_params([('spam', 'ham'), ('foo', 'bar')]) == 'https://github.com/zacharyvoase/urlblocks?spam=eggs&spam=ham&foo=bar#foo') def test_add_query_params_with_multiple_values_adds_the_same_query_parameter_multiple_times(self): assert (self.url.add_query_params({'foo': ['bar', 'baz']}) == 'https://github.com/zacharyvoase/urlblocks?spam=eggs&foo=bar&foo=baz#foo') def test_set_query_param_adds_or_replaces_one_query_parameter(self): assert (self.url.set_query_param('spam', 'ham') == 'https://github.com/zacharyvoase/urlblocks?spam=ham#foo') def test_set_query_params_adds_or_replaces_multiple_query_parameters(self): assert (self.url.set_query_params({'foo': 'bar'}, spam='ham') == 'https://github.com/zacharyvoase/urlblocks?foo=bar&spam=ham#foo') def test_set_query_params_with_multiple_values_adds_or_replaces_the_same_parameter_multiple_times(self): assert (self.url.set_query_params({'spam': ['bar', 'baz']}) == 'https://github.com/zacharyvoase/urlblocks?spam=bar&spam=baz#foo') assert (self.url.set_query_params({'foo': ['bar', 'baz']}) == 'https://github.com/zacharyvoase/urlblocks?spam=eggs&foo=bar&foo=baz#foo') # Ensure it removes all appearances of an existing name before adding # the new ones. url = URL('https://github.com/zacharyvoase/urlblocks?foo=bar&foo=baz#foo') assert (url.set_query_params({'foo': ['spam', 'ham']}) == 'https://github.com/zacharyvoase/urlblocks?foo=spam&foo=ham#foo') def test_del_query_param_removes_one_query_parameter(self): assert (self.url.del_query_param('spam') == 'https://github.com/zacharyvoase/urlblocks#foo') def test_del_query_params_removes_multiple_query_parameters(self): url = URL('https://github.com/zacharyvoase/urlblocks?foo=bar&baz=spam#foo') assert (url.del_query_params(['foo', 'baz']) == 'https://github.com/zacharyvoase/urlblocks#foo') def test_with_fragment_replaces_fragment(self): assert (self.url.with_fragment('part') == 'https://github.com/zacharyvoase/urlblocks?spam=eggs#part') def test_with_fragment_encodes_fragment_correctly(self): assert (self.url.with_fragment('foo bar#baz') == 'https://github.com/zacharyvoase/urlblocks?spam=eggs#foo%20bar%23baz') def test_without_fragment_removes_fragment(self): assert (self.url.without_fragment() == 'https://github.com/zacharyvoase/urlblocks?spam=eggs') class IRITest(unittest.TestCase): def test_encode_hostname_idna(self): assert (URL.from_iri(u('https://\xe9xample.com/')) == 'https://xn--xample-9ua.com/') def test_port_maintained(self): assert (URL.from_iri(u('https://\xe9xample.com:80/')) == 'https://xn--xample-9ua.com:80/') def test_encode_path(self): assert (URL.from_iri(u('https://example.com/p\xe5th/path2')) == 'https://example.com/p%C3%A5th/path2') def test_encode_query(self): assert (URL.from_iri(u('https://example.com/?k\xe9y=v\xe5l&key2=val2')) == 'https://example.com/?k%C3%A9y=v%C3%A5l&key2=val2') def test_encode_fragment(self): assert (URL.from_iri(u('https://example.com/#fr\xe5gment')) == 'https://example.com/#fr%C3%A5gment') def test_path_params(self): assert (URL.from_iri(u('https://example.com/foo;p\xe5rameter')) == 'https://example.com/foo;p%C3%A5rameter') def test_quoted_iri(self): """ If an IRI already has some quoted characters, they will be maintained as is. """ assert (URL.from_iri(u('https://example.com/foo%20b\xe5r/')) == 'https://example.com/foo%20b%C3%A5r/') def test_quote_other_special_characters(self): assert (URL.from_iri(u('https://example.com/foo bar/')) == 'https://example.com/foo%20bar/') class URLObjectIntegrityCheckingTestCase(unittest.TestCase): def test_self_existing_checking(self): self.assertRaises(URL.IsEmpty, lambda: URL('')) self.assertRaises(URL.IsEmpty, lambda: URL()) def test_scheme_existing_checking(self): self.assertRaises(URL.SchemeDoesNotExist, lambda: URL('example.com')) self.assertRaises(URL.SchemeDoesNotExist, lambda: URL('//example.com')) def test_hostname_existing_checking(self): self.assertRaises(URL.HostnameDoesNotExist, lambda: URL('http://')) self.assertRaises(URL.HostnameDoesNotExist, lambda: URL('http://.com')) self.assertRaises(URL.HostnameDoesNotExist, lambda: URL('http://com'))
13,827
630
2,077
aaf71fd1397197fd34773671ae32662cb1dc84cb
7,974
py
Python
toapi/api.py
davidthewatson/toapi
5f77ffa7a53692bcf9f14919a1aa435bf0152bd4
[ "Apache-2.0" ]
null
null
null
toapi/api.py
davidthewatson/toapi
5f77ffa7a53692bcf9f14919a1aa435bf0152bd4
[ "Apache-2.0" ]
null
null
null
toapi/api.py
davidthewatson/toapi
5f77ffa7a53692bcf9f14919a1aa435bf0152bd4
[ "Apache-2.0" ]
null
null
null
import json import re from collections import OrderedDict, defaultdict import cchardet import requests from colorama import Fore from selenium import webdriver from toapi.cache import CacheSetting from toapi.log import logger from toapi.server import Server from toapi.settings import Settings from toapi.storage import Storage class Api: """Api handle the routes dispatch""" def register(self, item): """Register items""" if item in self.item_classes: logger.error('Register', 'Repeat register item <%s>' % (item.__name__)) exit() self.item_classes.append(item) item.__base_url__ = item.__base_url__ or self.base_url for define_alias, define_route in OrderedDict(item.Meta.route).items(): alias = '^' + define_alias.replace('?', '\?') + '$' _alias_re = re.compile(re.sub(':(?P<params>[a-z_]+)', lambda m: '(?P<{}>[A-Za-z0-9_?&/=\s\-\u4e00-\u9fa5]+)'.format( m.group('params')), alias)) self.alias_re.append((define_alias, _alias_re)) self.items[define_alias].append({ 'item': item, 'alias_re': _alias_re, 'alias': define_alias, 'route': item.__base_url__ + define_route }) logger.info(Fore.GREEN, 'Register', '<%s>' % (item.__name__)) item_with_ajax = getattr(item.Meta, 'web', {}).get('with_ajax', False) if self.browser is None and item_with_ajax: self.browser = self.get_browser(settings=self.settings, item_with_ajax=item_with_ajax) def parse(self, path, params=None, **kwargs): """Parse items from a url""" items = self.prepare_parsing_items(path) if items is None: return None results = OrderedDict() cached_html = {} for index, item in enumerate(items): converted_path = item['converted_path'] html = cached_html.get(converted_path) or self.get_storage(converted_path) or self.fetch_page_source( converted_path, item=item['item'], params=params, **kwargs) if html is not None: cached_html[converted_path] = html parsed_item = self.parse_item(html, item['item']) results[item['item'].__name__] = parsed_item return json.dumps(results) if results else None def fetch_page_source(self, url, item, params=None, **kwargs): """Fetch the html of given url""" self.update_status('_status_sent') if getattr(item.Meta, 'web', {}).get('with_ajax', False) and self.browser is not None: self.browser.get(url) text = self.browser.page_source if text != '': logger.info(Fore.GREEN, 'Sent', '%s %s 200' % (url, len(text))) else: logger.error('Sent', '%s %s' % (url, len(text))) result = text else: request_config = getattr(item.Meta, 'web', {}).get('request_config', {}) or self.web.get( 'request_config', {}) response = requests.get(url, params=params, timeout=15, **request_config) content = response.content charset = cchardet.detect(content) text = content.decode(charset['encoding'] or 'utf-8') if response.status_code != 200: logger.error('Sent', '%s %s %s' % (url, len(text), response.status_code)) else: logger.info(Fore.GREEN, 'Sent', '%s %s %s' % (url, len(text), response.status_code)) result = text self.set_storage(url, result) return result def get_browser(self, settings, item_with_ajax=False): """Get browser""" if not getattr(self.settings, 'web', {}).get('with_ajax', False) and not item_with_ajax: return None if getattr(settings, 'headers', None) is not None: for key, value in settings.headers.items(): capability_key = 'phantomjs.page.customHeaders.{}'.format(key) webdriver.DesiredCapabilities.PHANTOMJS[capability_key] = value phantom_options = [] phantom_options.append('--load-images=false') return webdriver.PhantomJS(service_args=phantom_options) def update_status(self, key): """Increment Status""" self.cache.incr(key) def get_status(self, key): """Get Status""" return int(self.cache.get(key, 0)) def set_cache(self, key, value): """Set cache""" if self.cache.get(key) is None and self.cache.set(key, value): logger.info(Fore.YELLOW, 'Cache', 'Set<%s>' % key) self.update_status('_status_cache_set') return True return False def get_cache(self, key, default=None): """Set cache""" result = self.cache.get(key) if result is not None: logger.info(Fore.YELLOW, 'Cache', 'Get<%s>' % key) self.update_status('_status_cache_get') return result return default def set_storage(self, key, value): """Set storage""" try: if self.storage.get(key) is None and self.storage.save(key, value): logger.info(Fore.BLUE, 'Storage', 'Set<%s>' % key) self.update_status('_status_storage_set') return True return False except Exception as e: logger.error('Storage', 'Set<{}>'.format(str(e))) return False def get_storage(self, key, default=None): """Set storage""" result = self.storage.get(key) if result is not None: logger.info(Fore.BLUE, 'Storage', 'Get<%s>' % key) self.update_status('_status_storage_get') return result return default def parse_item(self, html, item): """Parse item from html""" result = item.parse(html) if len(result) == 0: logger.error('Parsed', 'Item<%s[%s]>' % (item.__name__.title(), len(result))) else: logger.info(Fore.CYAN, 'Parsed', 'Item<%s[%s]>' % (item.__name__.title(), len(result))) return result
40.272727
113
0.561951
import json import re from collections import OrderedDict, defaultdict import cchardet import requests from colorama import Fore from selenium import webdriver from toapi.cache import CacheSetting from toapi.log import logger from toapi.server import Server from toapi.settings import Settings from toapi.storage import Storage class Api: """Api handle the routes dispatch""" def __init__(self, base_url=None, settings=None, *args, **kwargs): self.base_url = base_url self.settings = settings or Settings self.storage = Storage(settings=self.settings) self.cache = CacheSetting(settings=self.settings) self.server = Server(self, settings=self.settings) self.browser = self.get_browser(settings=self.settings) self.web = getattr(self.settings, 'web', {}) self.item_classes = [] self.items = defaultdict(list) self.alias_re = [] def register(self, item): """Register items""" if item in self.item_classes: logger.error('Register', 'Repeat register item <%s>' % (item.__name__)) exit() self.item_classes.append(item) item.__base_url__ = item.__base_url__ or self.base_url for define_alias, define_route in OrderedDict(item.Meta.route).items(): alias = '^' + define_alias.replace('?', '\?') + '$' _alias_re = re.compile(re.sub(':(?P<params>[a-z_]+)', lambda m: '(?P<{}>[A-Za-z0-9_?&/=\s\-\u4e00-\u9fa5]+)'.format( m.group('params')), alias)) self.alias_re.append((define_alias, _alias_re)) self.items[define_alias].append({ 'item': item, 'alias_re': _alias_re, 'alias': define_alias, 'route': item.__base_url__ + define_route }) logger.info(Fore.GREEN, 'Register', '<%s>' % (item.__name__)) item_with_ajax = getattr(item.Meta, 'web', {}).get('with_ajax', False) if self.browser is None and item_with_ajax: self.browser = self.get_browser(settings=self.settings, item_with_ajax=item_with_ajax) def serve(self, ip='127.0.0.1', port=5000, **options): try: logger.info(Fore.WHITE, 'Serving', 'http://%s:%s' % (ip, port)) self.server.run(ip, port, **options) except Exception as e: logger.error('Serving', '%s' % str(e)) exit() def parse(self, path, params=None, **kwargs): """Parse items from a url""" items = self.prepare_parsing_items(path) if items is None: return None results = OrderedDict() cached_html = {} for index, item in enumerate(items): converted_path = item['converted_path'] html = cached_html.get(converted_path) or self.get_storage(converted_path) or self.fetch_page_source( converted_path, item=item['item'], params=params, **kwargs) if html is not None: cached_html[converted_path] = html parsed_item = self.parse_item(html, item['item']) results[item['item'].__name__] = parsed_item return json.dumps(results) if results else None def fetch_page_source(self, url, item, params=None, **kwargs): """Fetch the html of given url""" self.update_status('_status_sent') if getattr(item.Meta, 'web', {}).get('with_ajax', False) and self.browser is not None: self.browser.get(url) text = self.browser.page_source if text != '': logger.info(Fore.GREEN, 'Sent', '%s %s 200' % (url, len(text))) else: logger.error('Sent', '%s %s' % (url, len(text))) result = text else: request_config = getattr(item.Meta, 'web', {}).get('request_config', {}) or self.web.get( 'request_config', {}) response = requests.get(url, params=params, timeout=15, **request_config) content = response.content charset = cchardet.detect(content) text = content.decode(charset['encoding'] or 'utf-8') if response.status_code != 200: logger.error('Sent', '%s %s %s' % (url, len(text), response.status_code)) else: logger.info(Fore.GREEN, 'Sent', '%s %s %s' % (url, len(text), response.status_code)) result = text self.set_storage(url, result) return result def get_browser(self, settings, item_with_ajax=False): """Get browser""" if not getattr(self.settings, 'web', {}).get('with_ajax', False) and not item_with_ajax: return None if getattr(settings, 'headers', None) is not None: for key, value in settings.headers.items(): capability_key = 'phantomjs.page.customHeaders.{}'.format(key) webdriver.DesiredCapabilities.PHANTOMJS[capability_key] = value phantom_options = [] phantom_options.append('--load-images=false') return webdriver.PhantomJS(service_args=phantom_options) def update_status(self, key): """Increment Status""" self.cache.incr(key) def get_status(self, key): """Get Status""" return int(self.cache.get(key, 0)) def set_cache(self, key, value): """Set cache""" if self.cache.get(key) is None and self.cache.set(key, value): logger.info(Fore.YELLOW, 'Cache', 'Set<%s>' % key) self.update_status('_status_cache_set') return True return False def get_cache(self, key, default=None): """Set cache""" result = self.cache.get(key) if result is not None: logger.info(Fore.YELLOW, 'Cache', 'Get<%s>' % key) self.update_status('_status_cache_get') return result return default def set_storage(self, key, value): """Set storage""" try: if self.storage.get(key) is None and self.storage.save(key, value): logger.info(Fore.BLUE, 'Storage', 'Set<%s>' % key) self.update_status('_status_storage_set') return True return False except Exception as e: logger.error('Storage', 'Set<{}>'.format(str(e))) return False def get_storage(self, key, default=None): """Set storage""" result = self.storage.get(key) if result is not None: logger.info(Fore.BLUE, 'Storage', 'Get<%s>' % key) self.update_status('_status_storage_get') return result return default def parse_item(self, html, item): """Parse item from html""" result = item.parse(html) if len(result) == 0: logger.error('Parsed', 'Item<%s[%s]>' % (item.__name__.title(), len(result))) else: logger.info(Fore.CYAN, 'Parsed', 'Item<%s[%s]>' % (item.__name__.title(), len(result))) return result def prepare_parsing_items(self, path): results = [] for define_alias, alias_re in self.alias_re: matched = alias_re.match(path) if not matched: continue result_dict = matched.groupdict() converted_items = self.items.get(define_alias) for index, item in enumerate(converted_items): if item['item'] not in [i['item'] for i in results]: item['converted_path'] = re.sub(':(?P<params>[a-z_]+)', lambda m: '{}'.format(result_dict.get(m.group('params'))), item['route']) results.append(item) return results
1,519
0
81
f05f80d6e34a297a39e3d791591e9a691c17b6ec
572
py
Python
src/Chapter11/Exercise2.py
djeada/Python-For-Informatics
fc93cb60b6c81ee98b82b76934d39930a0c323d0
[ "MIT" ]
null
null
null
src/Chapter11/Exercise2.py
djeada/Python-For-Informatics
fc93cb60b6c81ee98b82b76934d39930a0c323d0
[ "MIT" ]
null
null
null
src/Chapter11/Exercise2.py
djeada/Python-For-Informatics
fc93cb60b6c81ee98b82b76934d39930a0c323d0
[ "MIT" ]
null
null
null
""" Exercise 2 Write a program to look for lines of the form New Revision: 39772 And extract the number from each of the lines using a regular expression and the findall() method. Compute the average of the numbers and print out the average. Enter file:mbox.txt 38549.7949721 Enter file:mbox-short.txt 39756.9259259 """ import re file = open("mbox-short.txt") lines = [line.strip("\n") for line in file] total = 0 count = 0 for line in lines: if re.findall("New Revision: 397*", line): count += 1 total += float(line[14:19]) print(total / count)
21.185185
76
0.701049
""" Exercise 2 Write a program to look for lines of the form New Revision: 39772 And extract the number from each of the lines using a regular expression and the findall() method. Compute the average of the numbers and print out the average. Enter file:mbox.txt 38549.7949721 Enter file:mbox-short.txt 39756.9259259 """ import re file = open("mbox-short.txt") lines = [line.strip("\n") for line in file] total = 0 count = 0 for line in lines: if re.findall("New Revision: 397*", line): count += 1 total += float(line[14:19]) print(total / count)
0
0
0
6dfb198298ffa10c994027b9895b4b8eb50d0e0c
11,218
py
Python
circle_vp.py
Prajwal-Prathiksh/Panel_Methods
387275a2791f616e5cd53e1713c409acc47f8f0a
[ "MIT" ]
null
null
null
circle_vp.py
Prajwal-Prathiksh/Panel_Methods
387275a2791f616e5cd53e1713c409acc47f8f0a
[ "MIT" ]
null
null
null
circle_vp.py
Prajwal-Prathiksh/Panel_Methods
387275a2791f616e5cd53e1713c409acc47f8f0a
[ "MIT" ]
null
null
null
########################################################################### # Imports ########################################################################### # Standard library imports import argparse import time as time import numpy as np import math as math import matplotlib.pyplot as plt from matplotlib import path # Local imports from helper_funcs import * ########################################################################### # Code ########################################################################### # KNOWNS args = cli_parser() Vinf = args.Vinf AoA = args.AoA numB = args.numB # Convert AoA to radians [rad] AoAR = AoA * (np.pi / 180) # Plotting flags flagPlot = [1, # Shape polygon with panel normal vectors 1, # Geometry boundary pts, control pts, first panel 1, # Analytical and SPM pressure coefficient plot 1, # Streamline plot 1] # Pressure coefficient contour plot # Grid parameters # X & Y grid for streamlines and contours nGridX = nGridY = 150 # X-grid extents [min, max] xVals = [-2, 2] # Y-grid extents [min, max] yVals = [-2, 2] # %% FUNCTIONS XB, YB, numPan = create_elliptical_panels( numB=numB, a=args.ellipse_a, b=args.ellipse_b ) XB, YB = correct_panels_orientation(numPan, XB, YB) XC, YC, S, beta, delta, phi = compute_panel_geometries(numPan, XB, YB, AoA) K, L = compute_kl_vpm(XC, YC, XB, YB, phi, S) A, b = populate_matrices_vpm(numPan, K, beta, Vinf) A, b = satisfy_kutta_condition_vpm(numPan, A, b, pct=args.replacement_pct) gamma = np.linalg.solve(A, b) print("Sum of gamma: ", sum(gamma * S)) Vt, Cp = compute_panel_velocities(numPan, gamma, beta, L, Vinf) # Analytical angles and pressure coefficients # Analytical theta angles [rad] analyticTheta = np.linspace(0, 2 * np.pi, 200) # Analytical pressure coefficient [] analyticCP = 1 - 4 * np.sin(analyticTheta)**2 CN, CA, CL, CD, CM = compute_force_coefficients(XC, phi, beta, AoAR, Cp, S) # Print the results to the Console print("\n======= RESULTS =======") print("Lift Coefficient (CL)") # From Kutta-Joukowski lift equation print(f" K-J : {2*sum(gamma*S)}") # From this VPM code print(f" VPM : {CL}") print("\nMoment Coefficient (CM)") print(f" VPM : {CM}") # %% COMPUTE STREAMLINES - REF [4] if (flagPlot[3] == 1 or flagPlot[4] == 1): # Streamline parameters # Percentage of streamlines of the grid slPct = 25 # Create array of Y streamline starting points Ysl = np.linspace(yVals[0], yVals[1], int((slPct / 100) * nGridY)) # Create array of X streamline starting points Xsl = xVals[0] * np.ones(len(Ysl)) # Concatenate X and Y streamline starting points XYsl = np.vstack((Xsl.T, Ysl.T)).T # Generate the grid points # X-values in evenly spaced grid Xgrid = np.linspace(xVals[0], xVals[1], nGridX) # Y-values in evenly spaced grid Ygrid = np.linspace(yVals[0], yVals[1], nGridY) # Create meshgrid from X and Y grid arrays XX, YY = np.meshgrid(Xgrid, Ygrid) # Initialize velocities # Initialize X velocity matrix Vx = np.zeros([nGridX, nGridY]) # Initialize Y velocity matrix Vy = np.zeros([nGridX, nGridY]) # Path to figure out if grid point is inside polygon or not # Concatenate XB and YB geometry points AF = np.vstack((XB.T, YB.T)).T # Create a path for the geometry afPath = path.Path(AF) # Solve for grid point X and Y velocities tic = time.perf_counter() # Loop over X-grid points for m in range(nGridX): # Loop over Y-grid points for n in range(nGridY): # Current iteration's X grid point XP = XX[m, n] # Current iteration's Y grid point YP = YY[m, n] # Compute Nx and Ny geometric integrals Nx, Ny = streamline_vpn(XP, YP, XB, YB, phi, S) # Check if grid points are in object # - If they are, assign a velocity of zero # If (XP,YP) is in the body if afPath.contains_points([(XP, YP)]): # Set X-velocity equal to zero Vx[m, n] = 0 # Set Y-velocity equal to zero Vy[m, n] = 0 else: # Compute X-velocity Vx[m, n] = Vinf * np.cos(AoAR) + sum(-gamma * Nx / (2 * np.pi)) # Compute Y-velocity Vy[m, n] = Vinf * np.sin(AoAR) + sum(-gamma * Ny / (2 * np.pi)) toc = time.perf_counter() print("\n\nSTREAMLINE_VPM: %.2f seconds" % (toc - tic)) # Compute grid point velocity magnitude and pressure coefficient # Compute magnitude of velocity vector [] Vxy = np.sqrt(Vx**2 + Vy**2) # Pressure coefficient [] CpXY = 1 - (Vxy / Vinf)**2 # %% PLOTTING # FIGURE: Shape polygon with panel normal vectors if (flagPlot[0] == 1): # Angles for "perfect" circle angCirc = np.linspace(0, 2 * np.pi, 1000) # "Perfect" circle X values xCirc = np.cos(angCirc) # "Perfect" circle Y values yCirc = np.sin(angCirc) # Create figure fig = plt.figure(1) # Clear the axes plt.cla() # Plot the circle that polygon is approximating plt.plot(xCirc, yCirc, 'k--') # Plot the paneled circle plt.fill(XB, YB, 'k') # Initialize 'X' X = np.zeros(2) # Initialize 'Y' Y = np.zeros(2) # Loop over all panels for i in range(numPan): # Set X start of panel orientation vector X[0] = XC[i] # Set X end of panel orientation vector X[1] = XC[i] + S[i] * np.cos(delta[i]) # Set Y start of panel orientation vector Y[0] = YC[i] # Set Y end of panel orientation vector Y[1] = YC[i] + S[i] * np.sin(delta[i]) # If it's the first panel index if (i == 0): # Plot the first panel plt.plot(X, Y, 'b-', label='First Panel') # If it's the second panel index elif (i == 1): # Plot the second panel plt.plot(X, Y, 'g-', label='Second Panel') # If it's neither the first nor second panel index else: # Plot the rest of the panels plt.plot(X, Y, 'r-') # Set X-label plt.xlabel('X-Axis') # Set Y-label plt.ylabel('Y-Axis') # Set title plt.title('Panel Geometry') # Set axes equal plt.axis('equal') # Show legend plt.legend() fname = os.path.join('figs', 'ellipses', 'panel_geometry.png') plt.savefig(fname, dpi=args.dpi, bbox_inches='tight') # FIGURE: Geometry with the following indicated: # - Boundary points, control points, first panel, second panel if (flagPlot[1] == 1): # Create figure fig = plt.figure(2) # Get ready for plotting plt.cla() # Plot polygon plt.plot(XB, YB, 'k-', label='Panels') plt.plot([XB[0], XB[1]], [YB[0], YB[1]], 'b-', label='First Panel') # Plot first panel plt.plot([XB[1], XB[2]], [YB[1], YB[2]], 'g-', label='Second Panel') # Plot second panel # Plot boundary points plt.plot( XB, YB, 'ko', markerfacecolor='k', label='Boundary Points' ) # Plot control points plt.plot( XC, YC, 'ko', markerfacecolor='r', label='Control Points' ) # Set X-label plt.xlabel('X-Axis') # Set Y-label plt.ylabel('Y-Axis') # Set title plt.title('Panel Geometry 2') # Set axes equal plt.axis('equal') # Show legend plt.legend() fname = os.path.join('figs', 'ellipses', 'panel_geometry2.png') plt.savefig(fname, dpi=args.dpi, bbox_inches='tight') # FIGURE: Analytical and SPM pressure coefficient if (flagPlot[2] == 1): # Create figure fig = plt.figure(3) # Get ready for plotting plt.cla() # Plot analytical pressure coefficient plt.plot( analyticTheta * (180 / np.pi), analyticCP, 'b-', label='Analytical' ) # Plot panel method pressure coefficient plt.plot( beta * (180 / np.pi), Cp, 'ks', markerfacecolor='r', label='VPM' ) # Set X-label plt.xlabel('Angle [deg]') # Set Y-label plt.ylabel('Pressure Coefficient') # Set title plt.title('Pressure Coefficient Comparison') # Set X-limits plt.xlim(0, 360) # Set Y-limits plt.ylim(-3.5, 1.5) # Show legend plt.legend() fname = os.path.join('figs', 'ellipses', 'pressure_coefficient_comparison.png') plt.savefig(fname, dpi=args.dpi, bbox_inches='tight') # FIGURE: Streamlines if (flagPlot[3] == 1): # Create figure fig = plt.figure(5) # Get ready for plotting plt.cla() # Ignore underflow error message np.seterr(under="ignore") # Plot streamlines plt.streamplot( XX, YY, Vx, Vy, linewidth=0.5, density=40, color='r', arrowstyle='-', start_points=XYsl ) plt.clim(vmin=0, vmax=2) # Plot airfoil as black polygon plt.fill(XB, YB, 'k') # Set X-label plt.xlabel('X Units') # Set Y-label plt.ylabel('Y Units') # Set axes equal plt.gca().set_aspect('equal') # Set X-limits plt.xlim(xVals) # Set Y-limits plt.ylim(yVals) fname = os.path.join('figs', 'ellipses', 'streamlines.png') plt.savefig(fname, dpi=args.dpi, bbox_inches='tight') # FIGURE: Pressure coefficient contours if (flagPlot[4] == 1): # Create figure fig = plt.figure(6) # Get ready for plotting plt.cla() # Plot contour plt.contourf(XX, YY, CpXY, 500, cmap='jet') # Plot airfoil as black polygon plt.fill(XB, YB, 'k') # Set X-label plt.xlabel('X Units') # Set Y-label plt.ylabel('Y Units') # Set axes equal plt.gca().set_aspect('equal') # Set X-limits plt.xlim(xVals) # Set Y-limits plt.ylim(yVals) plt.colorbar() fname = os.path.join('figs', 'ellipses', 'pressure_coefficient_contours.png') plt.savefig(fname, dpi=args.dpi, bbox_inches='tight')
30.734247
83
0.584953
########################################################################### # Imports ########################################################################### # Standard library imports import argparse import time as time import numpy as np import math as math import matplotlib.pyplot as plt from matplotlib import path # Local imports from helper_funcs import * ########################################################################### # Code ########################################################################### def cli_parser(): parser = argparse.ArgumentParser( allow_abbrev=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( '-n', '--numb', action='store', dest='numB', type=int, required=True, help='Number of boundary points (including endpoint).' ) parser.add_argument( '-v', '--vinf', action='store', dest='Vinf', type=float, default=1., help='Free stream velocity.' ) parser.add_argument( '-A', '--aoa', action='store', dest='AoA', type=float, default=0., help='Angle of attack.' ) parser.add_argument( '-a', '--ellipse-a', action='store', dest='ellipse_a', type=float, default=1., help='Semi-major axis of ellipse.' ) parser.add_argument( '-b', '--ellipse-b', action='store', dest='ellipse_b', type=float, default=1., help='Semi-minor axis of ellipse.' ) parser.add_argument( '--pct', action='store', dest='replacement_pct', type=float, default=100., help='Panel replacement percentage.' ) parser.add_argument( '--dpi', action='store', dest='dpi', type=int, default=300., help='DPI of output image.' ) args = parser.parse_args() return args # KNOWNS args = cli_parser() Vinf = args.Vinf AoA = args.AoA numB = args.numB # Convert AoA to radians [rad] AoAR = AoA * (np.pi / 180) # Plotting flags flagPlot = [1, # Shape polygon with panel normal vectors 1, # Geometry boundary pts, control pts, first panel 1, # Analytical and SPM pressure coefficient plot 1, # Streamline plot 1] # Pressure coefficient contour plot # Grid parameters # X & Y grid for streamlines and contours nGridX = nGridY = 150 # X-grid extents [min, max] xVals = [-2, 2] # Y-grid extents [min, max] yVals = [-2, 2] # %% FUNCTIONS XB, YB, numPan = create_elliptical_panels( numB=numB, a=args.ellipse_a, b=args.ellipse_b ) XB, YB = correct_panels_orientation(numPan, XB, YB) XC, YC, S, beta, delta, phi = compute_panel_geometries(numPan, XB, YB, AoA) K, L = compute_kl_vpm(XC, YC, XB, YB, phi, S) A, b = populate_matrices_vpm(numPan, K, beta, Vinf) A, b = satisfy_kutta_condition_vpm(numPan, A, b, pct=args.replacement_pct) gamma = np.linalg.solve(A, b) print("Sum of gamma: ", sum(gamma * S)) Vt, Cp = compute_panel_velocities(numPan, gamma, beta, L, Vinf) # Analytical angles and pressure coefficients # Analytical theta angles [rad] analyticTheta = np.linspace(0, 2 * np.pi, 200) # Analytical pressure coefficient [] analyticCP = 1 - 4 * np.sin(analyticTheta)**2 CN, CA, CL, CD, CM = compute_force_coefficients(XC, phi, beta, AoAR, Cp, S) # Print the results to the Console print("\n======= RESULTS =======") print("Lift Coefficient (CL)") # From Kutta-Joukowski lift equation print(f" K-J : {2*sum(gamma*S)}") # From this VPM code print(f" VPM : {CL}") print("\nMoment Coefficient (CM)") print(f" VPM : {CM}") # %% COMPUTE STREAMLINES - REF [4] if (flagPlot[3] == 1 or flagPlot[4] == 1): # Streamline parameters # Percentage of streamlines of the grid slPct = 25 # Create array of Y streamline starting points Ysl = np.linspace(yVals[0], yVals[1], int((slPct / 100) * nGridY)) # Create array of X streamline starting points Xsl = xVals[0] * np.ones(len(Ysl)) # Concatenate X and Y streamline starting points XYsl = np.vstack((Xsl.T, Ysl.T)).T # Generate the grid points # X-values in evenly spaced grid Xgrid = np.linspace(xVals[0], xVals[1], nGridX) # Y-values in evenly spaced grid Ygrid = np.linspace(yVals[0], yVals[1], nGridY) # Create meshgrid from X and Y grid arrays XX, YY = np.meshgrid(Xgrid, Ygrid) # Initialize velocities # Initialize X velocity matrix Vx = np.zeros([nGridX, nGridY]) # Initialize Y velocity matrix Vy = np.zeros([nGridX, nGridY]) # Path to figure out if grid point is inside polygon or not # Concatenate XB and YB geometry points AF = np.vstack((XB.T, YB.T)).T # Create a path for the geometry afPath = path.Path(AF) # Solve for grid point X and Y velocities tic = time.perf_counter() # Loop over X-grid points for m in range(nGridX): # Loop over Y-grid points for n in range(nGridY): # Current iteration's X grid point XP = XX[m, n] # Current iteration's Y grid point YP = YY[m, n] # Compute Nx and Ny geometric integrals Nx, Ny = streamline_vpn(XP, YP, XB, YB, phi, S) # Check if grid points are in object # - If they are, assign a velocity of zero # If (XP,YP) is in the body if afPath.contains_points([(XP, YP)]): # Set X-velocity equal to zero Vx[m, n] = 0 # Set Y-velocity equal to zero Vy[m, n] = 0 else: # Compute X-velocity Vx[m, n] = Vinf * np.cos(AoAR) + sum(-gamma * Nx / (2 * np.pi)) # Compute Y-velocity Vy[m, n] = Vinf * np.sin(AoAR) + sum(-gamma * Ny / (2 * np.pi)) toc = time.perf_counter() print("\n\nSTREAMLINE_VPM: %.2f seconds" % (toc - tic)) # Compute grid point velocity magnitude and pressure coefficient # Compute magnitude of velocity vector [] Vxy = np.sqrt(Vx**2 + Vy**2) # Pressure coefficient [] CpXY = 1 - (Vxy / Vinf)**2 # %% PLOTTING # FIGURE: Shape polygon with panel normal vectors if (flagPlot[0] == 1): # Angles for "perfect" circle angCirc = np.linspace(0, 2 * np.pi, 1000) # "Perfect" circle X values xCirc = np.cos(angCirc) # "Perfect" circle Y values yCirc = np.sin(angCirc) # Create figure fig = plt.figure(1) # Clear the axes plt.cla() # Plot the circle that polygon is approximating plt.plot(xCirc, yCirc, 'k--') # Plot the paneled circle plt.fill(XB, YB, 'k') # Initialize 'X' X = np.zeros(2) # Initialize 'Y' Y = np.zeros(2) # Loop over all panels for i in range(numPan): # Set X start of panel orientation vector X[0] = XC[i] # Set X end of panel orientation vector X[1] = XC[i] + S[i] * np.cos(delta[i]) # Set Y start of panel orientation vector Y[0] = YC[i] # Set Y end of panel orientation vector Y[1] = YC[i] + S[i] * np.sin(delta[i]) # If it's the first panel index if (i == 0): # Plot the first panel plt.plot(X, Y, 'b-', label='First Panel') # If it's the second panel index elif (i == 1): # Plot the second panel plt.plot(X, Y, 'g-', label='Second Panel') # If it's neither the first nor second panel index else: # Plot the rest of the panels plt.plot(X, Y, 'r-') # Set X-label plt.xlabel('X-Axis') # Set Y-label plt.ylabel('Y-Axis') # Set title plt.title('Panel Geometry') # Set axes equal plt.axis('equal') # Show legend plt.legend() fname = os.path.join('figs', 'ellipses', 'panel_geometry.png') plt.savefig(fname, dpi=args.dpi, bbox_inches='tight') # FIGURE: Geometry with the following indicated: # - Boundary points, control points, first panel, second panel if (flagPlot[1] == 1): # Create figure fig = plt.figure(2) # Get ready for plotting plt.cla() # Plot polygon plt.plot(XB, YB, 'k-', label='Panels') plt.plot([XB[0], XB[1]], [YB[0], YB[1]], 'b-', label='First Panel') # Plot first panel plt.plot([XB[1], XB[2]], [YB[1], YB[2]], 'g-', label='Second Panel') # Plot second panel # Plot boundary points plt.plot( XB, YB, 'ko', markerfacecolor='k', label='Boundary Points' ) # Plot control points plt.plot( XC, YC, 'ko', markerfacecolor='r', label='Control Points' ) # Set X-label plt.xlabel('X-Axis') # Set Y-label plt.ylabel('Y-Axis') # Set title plt.title('Panel Geometry 2') # Set axes equal plt.axis('equal') # Show legend plt.legend() fname = os.path.join('figs', 'ellipses', 'panel_geometry2.png') plt.savefig(fname, dpi=args.dpi, bbox_inches='tight') # FIGURE: Analytical and SPM pressure coefficient if (flagPlot[2] == 1): # Create figure fig = plt.figure(3) # Get ready for plotting plt.cla() # Plot analytical pressure coefficient plt.plot( analyticTheta * (180 / np.pi), analyticCP, 'b-', label='Analytical' ) # Plot panel method pressure coefficient plt.plot( beta * (180 / np.pi), Cp, 'ks', markerfacecolor='r', label='VPM' ) # Set X-label plt.xlabel('Angle [deg]') # Set Y-label plt.ylabel('Pressure Coefficient') # Set title plt.title('Pressure Coefficient Comparison') # Set X-limits plt.xlim(0, 360) # Set Y-limits plt.ylim(-3.5, 1.5) # Show legend plt.legend() fname = os.path.join('figs', 'ellipses', 'pressure_coefficient_comparison.png') plt.savefig(fname, dpi=args.dpi, bbox_inches='tight') # FIGURE: Streamlines if (flagPlot[3] == 1): # Create figure fig = plt.figure(5) # Get ready for plotting plt.cla() # Ignore underflow error message np.seterr(under="ignore") # Plot streamlines plt.streamplot( XX, YY, Vx, Vy, linewidth=0.5, density=40, color='r', arrowstyle='-', start_points=XYsl ) plt.clim(vmin=0, vmax=2) # Plot airfoil as black polygon plt.fill(XB, YB, 'k') # Set X-label plt.xlabel('X Units') # Set Y-label plt.ylabel('Y Units') # Set axes equal plt.gca().set_aspect('equal') # Set X-limits plt.xlim(xVals) # Set Y-limits plt.ylim(yVals) fname = os.path.join('figs', 'ellipses', 'streamlines.png') plt.savefig(fname, dpi=args.dpi, bbox_inches='tight') # FIGURE: Pressure coefficient contours if (flagPlot[4] == 1): # Create figure fig = plt.figure(6) # Get ready for plotting plt.cla() # Plot contour plt.contourf(XX, YY, CpXY, 500, cmap='jet') # Plot airfoil as black polygon plt.fill(XB, YB, 'k') # Set X-label plt.xlabel('X Units') # Set Y-label plt.ylabel('Y Units') # Set axes equal plt.gca().set_aspect('equal') # Set X-limits plt.xlim(xVals) # Set Y-limits plt.ylim(yVals) plt.colorbar() fname = os.path.join('figs', 'ellipses', 'pressure_coefficient_contours.png') plt.savefig(fname, dpi=args.dpi, bbox_inches='tight')
1,251
0
23
e9be790eafe58cf7aaa0017314b055dd2bdf4ea4
79
py
Python
core/devices/__init__.py
kisonho/torchmanager
ac01c61a132238bc0d39bf2173dfd37f44dbbf30
[ "BSD-2-Clause" ]
null
null
null
core/devices/__init__.py
kisonho/torchmanager
ac01c61a132238bc0d39bf2173dfd37f44dbbf30
[ "BSD-2-Clause" ]
null
null
null
core/devices/__init__.py
kisonho/torchmanager
ac01c61a132238bc0d39bf2173dfd37f44dbbf30
[ "BSD-2-Clause" ]
null
null
null
from .devices import data_parallel, empty_cache, find, move_to_device, CPU, GPU
79
79
0.822785
from .devices import data_parallel, empty_cache, find, move_to_device, CPU, GPU
0
0
0
30d5b7f4cd7dad7609afa473bd961873ddbb194d
4,674
py
Python
msldap/authentication/kerberos/multiplexor.py
blshkv/msldap
435601df85faa407793555ed0da582aa709e3be1
[ "MIT" ]
1
2021-11-08T09:11:22.000Z
2021-11-08T09:11:22.000Z
msldap/authentication/kerberos/multiplexor.py
blshkv/msldap
435601df85faa407793555ed0da582aa709e3be1
[ "MIT" ]
null
null
null
msldap/authentication/kerberos/multiplexor.py
blshkv/msldap
435601df85faa407793555ed0da582aa709e3be1
[ "MIT" ]
null
null
null
## ## ## Interface to allow remote kerberos authentication via Multiplexor ## ## ## ## ## ## TODO: RPC auth type is not implemented or tested!!!! from msldap.authentication.spnego.asn1_structs import KRB5Token from msldap.authentication.kerberos.gssapi import get_gssapi, GSSWrapToken, KRB5_MECH_INDEP_TOKEN from minikerberos.protocol.asn1_structs import AP_REQ, AP_REP, TGS_REP from minikerberos.protocol.encryption import Enctype, Key, _enctype_table from multiplexor.operator.external.sspi import KerberosSSPIClient from multiplexor.operator import MultiplexorOperator import enum # mutual auth not supported # encryption is always on # we dont get the output flags back (lack of time to do the multiplexor protocol... TODO
29.961538
116
0.735344
## ## ## Interface to allow remote kerberos authentication via Multiplexor ## ## ## ## ## ## TODO: RPC auth type is not implemented or tested!!!! from msldap.authentication.spnego.asn1_structs import KRB5Token from msldap.authentication.kerberos.gssapi import get_gssapi, GSSWrapToken, KRB5_MECH_INDEP_TOKEN from minikerberos.protocol.asn1_structs import AP_REQ, AP_REP, TGS_REP from minikerberos.protocol.encryption import Enctype, Key, _enctype_table from multiplexor.operator.external.sspi import KerberosSSPIClient from multiplexor.operator import MultiplexorOperator import enum # mutual auth not supported # encryption is always on # we dont get the output flags back (lack of time to do the multiplexor protocol... TODO class ISC_REQ(enum.IntFlag): DELEGATE = 1 MUTUAL_AUTH = 2 REPLAY_DETECT = 4 SEQUENCE_DETECT = 8 CONFIDENTIALITY = 16 USE_SESSION_KEY = 32 PROMPT_FOR_CREDS = 64 USE_SUPPLIED_CREDS = 128 ALLOCATE_MEMORY = 256 USE_DCE_STYLE = 512 DATAGRAM = 1024 CONNECTION = 2048 CALL_LEVEL = 4096 FRAGMENT_SUPPLIED = 8192 EXTENDED_ERROR = 16384 STREAM = 32768 INTEGRITY = 65536 IDENTIFY = 131072 NULL_SESSION = 262144 MANUAL_CRED_VALIDATION = 524288 RESERVED1 = 1048576 FRAGMENT_TO_FIT = 2097152 HTTP = 0x10000000 class MSLDAPKerberosMultiplexor: def __init__(self, settings): self.iterations = 0 self.settings = settings self.mode = 'CLIENT' self.ksspi = None self.client = None self.target = None self.gssapi = None self.etype = None self.session_key = None self.seq_number = 0 self.flags = ISC_REQ.CONNECTION self.setup() def setup(self): if self.settings.encrypt is True: self.flags = \ ISC_REQ.CONFIDENTIALITY |\ ISC_REQ.INTEGRITY |\ ISC_REQ.REPLAY_DETECT |\ ISC_REQ.SEQUENCE_DETECT def get_seq_number(self): """ Fetches the starting sequence number. This is either zero or can be found in the authenticator field of the AP_REQ structure. As windows uses a random seq number AND a subkey as well, we can't obtain it by decrypting the AP_REQ structure. Insead under the hood we perform an encryption operation via EncryptMessage API which will yield the start sequence number """ return self.seq_number async def encrypt(self, data, message_no): return self.gssapi.GSS_Wrap(data, message_no) async def decrypt(self, data, message_no, direction='init', auth_data=None): return self.gssapi.GSS_Unwrap(data, message_no, direction=direction, auth_data=auth_data) def signing_needed(self): """ Checks if integrity protection was negotiated """ return ISC_REQ.INTEGRITY in self.flags def encryption_needed(self): """ Checks if confidentiality flag was negotiated """ return ISC_REQ.CONFIDENTIALITY in self.flags def get_session_key(self): return self.session_key async def authenticate(self, authData = None, flags = None, seq_number = 0, cb_data=None): #authdata is only for api compatibility reasons is_rpc = False if self.ksspi is None: await self.start_remote_kerberos() try: apreq, res = await self.ksspi.authenticate(self.settings.target.to_target_string(), flags=str(self.flags.value)) #print('MULTIPLEXOR KERBEROS SSPI, APREQ: %s ERROR: %s' % (apreq, res)) if res is not None: return None, None, res # here it seems like we get the full token not just the apreq data... # so we need to discard the layers self.session_key, err = await self.ksspi.get_session_key() if err is not None: return None, None, err unwrap = KRB5_MECH_INDEP_TOKEN.from_bytes(apreq) aprep = AP_REQ.load(unwrap.data[2:]).native subkey = Key(aprep['ticket']['enc-part']['etype'], self.session_key) self.gssapi = get_gssapi(subkey) if aprep['ticket']['enc-part']['etype'] != 23: raw_seq_data, err = await self.ksspi.get_seq_number() if err is not None: return None, None, err self.seq_number = GSSWrapToken.from_bytes(raw_seq_data[16:]).SND_SEQ return unwrap.data[2:], False, res except Exception as e: return None, None, e async def start_remote_kerberos(self): try: #print(self.settings.get_url()) #print(self.settings.agent_id) self.operator = MultiplexorOperator(self.settings.get_url()) await self.operator.connect() #creating virtual sspi server server_info = await self.operator.start_sspi(self.settings.agent_id) #print(server_info) sspi_url = 'ws://%s:%s' % (server_info['listen_ip'], server_info['listen_port']) #print(sspi_url) self.ksspi = KerberosSSPIClient(sspi_url) await self.ksspi.connect() except Exception as e: import traceback traceback.print_exc() return None
2,505
1,388
46
38fce3bd5985202b03c539465a04b5355411b99c
6,739
py
Python
plugins/modules/firewall_rule.py
tnaganawa/ansible-collections-tungstenfabric
548f5233e7ffb9dd19373963ecd79765c6cdd1db
[ "Apache-2.0" ]
2
2020-10-26T10:49:19.000Z
2021-02-04T10:02:40.000Z
plugins/modules/firewall_rule.py
tnaganawa/ansible-collections-tungstenfabric
548f5233e7ffb9dd19373963ecd79765c6cdd1db
[ "Apache-2.0" ]
3
2021-02-04T11:40:31.000Z
2021-02-13T18:27:18.000Z
plugins/modules/firewall_rule.py
tnaganawa/ansible-collections-tungstenfabric
548f5233e7ffb9dd19373963ecd79765c6cdd1db
[ "Apache-2.0" ]
1
2021-02-04T10:02:46.000Z
2021-02-04T10:02:46.000Z
#!/usr/bin/python # Copyright: (c) 2020, Tatsuya Naganawa <tatsuyan201101@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: firewall_rule short_description: create tungstenfabirc firewall-rule version_added: "2.9" description: - "create / delete tungstenfabric firewall-rule" options: name: description: - firewall-rule name required: true controller_ip: description: - tungstenfabric controller ip required: true project: description: - project name (if it is defined, firewall-rule will be project scoped rule) required: false firewall_rule: description: - rule of this firewall-rule (see EXAMPLES) required: false author: - Tatsuya Naganawa (@tnaganawa) ''' EXAMPLES = ''' - name: create firewall_rule tungstenfabric.networking.firewall_rule: name: firewall_rule1 controller_ip: x.x.x.x state: present endpoint_1: {virtual_network: default-domain:admin:vn1} endpoint_2: {virtual_network: default-domain:admin:vn2} service: {protocol: any} action_list: {simple_action: pass} - name: create project-scope firewall_rule tungstenfabric.networking.firewall_rule: name: firewall_rule1 controller_ip: x.x.x.x state: present project: admin endpoint_1: {virtual_network: default-domain:admin:vn1} endpoint_2: {virtual_network: default-domain:admin:vn2} service: {protocol: any} action_list: {simple_action: pass} - name: delete firewall_rule tungstenfabric.networking.firewall_rule: name: firewall_rule1 controller_ip: x.x.x.x state: absent ''' RETURN = ''' message: description: The output message that this module generates type: str returned: always ''' import sys import json import requests from ansible.module_utils.basic import AnsibleModule from ansible_collections.tungstenfabric.networking.plugins.module_utils.common import login_and_check_id, crud if __name__ == '__main__': main()
30.493213
150
0.630657
#!/usr/bin/python # Copyright: (c) 2020, Tatsuya Naganawa <tatsuyan201101@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: firewall_rule short_description: create tungstenfabirc firewall-rule version_added: "2.9" description: - "create / delete tungstenfabric firewall-rule" options: name: description: - firewall-rule name required: true controller_ip: description: - tungstenfabric controller ip required: true project: description: - project name (if it is defined, firewall-rule will be project scoped rule) required: false firewall_rule: description: - rule of this firewall-rule (see EXAMPLES) required: false author: - Tatsuya Naganawa (@tnaganawa) ''' EXAMPLES = ''' - name: create firewall_rule tungstenfabric.networking.firewall_rule: name: firewall_rule1 controller_ip: x.x.x.x state: present endpoint_1: {virtual_network: default-domain:admin:vn1} endpoint_2: {virtual_network: default-domain:admin:vn2} service: {protocol: any} action_list: {simple_action: pass} - name: create project-scope firewall_rule tungstenfabric.networking.firewall_rule: name: firewall_rule1 controller_ip: x.x.x.x state: present project: admin endpoint_1: {virtual_network: default-domain:admin:vn1} endpoint_2: {virtual_network: default-domain:admin:vn2} service: {protocol: any} action_list: {simple_action: pass} - name: delete firewall_rule tungstenfabric.networking.firewall_rule: name: firewall_rule1 controller_ip: x.x.x.x state: absent ''' RETURN = ''' message: description: The output message that this module generates type: str returned: always ''' import sys import json import requests from ansible.module_utils.basic import AnsibleModule from ansible_collections.tungstenfabric.networking.plugins.module_utils.common import login_and_check_id, crud def run_module(): module_args = dict( name=dict(type='str', required=True), controller_ip=dict(type='str', required=True), username=dict(type='str', required=False, default='admin'), password=dict(type='str', required=False, default='contrail123'), state=dict(type='str', required=False, default='present', choices=['absent', 'present']), uuid=dict(type='str', required=False), domain=dict(type='str', required=False, default='default-domain'), project=dict(type='str', required=False), endpoint_1=dict(type='dict', required=False), endpoint_2=dict(type='dict', required=False), service=dict(type='dict', required=False), action_list=dict(type='dict', required=False), ) result = dict( changed=False, message='' ) required_if_args = [ ["state", "present", ["endpoint_1", "endpoint_2", "action_list"]] ] module = AnsibleModule( argument_spec=module_args, supports_check_mode=True, required_if=required_if_args ) name = module.params.get("name") controller_ip = module.params.get("controller_ip") username = module.params.get("username") password = module.params.get("password") state = module.params.get("state") domain = module.params.get("domain") project = module.params.get("project") endpoint_1 = module.params.get("endpoint_1") endpoint_2 = module.params.get("endpoint_2") service = module.params.get("service") action_list = module.params.get("action_list") if module.check_mode: module.exit_json(**result) obj_type='firewall-rule' (web_api, update, uuid, js) = login_and_check_id(module, name, obj_type, controller_ip, username, password, state, domain=domain, project=project) if update and state=='present': pass else: ## create payload and call API if project: js=json.loads ( ''' { "firewall-rule": { "fq_name": ["%s", "%s", "%s"], "parent_type": "project" } } ''' % (domain, project, name) ) else: js=json.loads ( ''' { "firewall-rule": { "fq_name": ["%s"], "parent_type": "policy-management" } } ''' % (name) ) ## begin: object specific if (endpoint_1): js["firewall-rule"]["endpoint_1"]=endpoint_1 if (endpoint_2): js["firewall-rule"]["endpoint_2"]=endpoint_2 if (action_list): js["firewall-rule"]["action_list"]=action_list # set default values for webui if js["firewall-rule"]["endpoint_1"].get("address_group") == None: js["firewall-rule"]["endpoint_1"]["address_group"] = None if js["firewall-rule"]["endpoint_1"].get("any") == None: js["firewall-rule"]["endpoint_1"]["any"] = None if js["firewall-rule"]["endpoint_1"].get("tags") == None: js["firewall-rule"]["endpoint_1"]["tags"] = [] if js["firewall-rule"]["endpoint_2"].get("address_group") == None: js["firewall-rule"]["endpoint_2"]["address_group"] = None if js["firewall-rule"]["endpoint_2"].get("any") == None: js["firewall-rule"]["endpoint_2"]["any"] = None if js["firewall-rule"]["endpoint_2"].get("tags") == None: js["firewall-rule"]["endpoint_2"]["tags"] = [] if js["firewall-rule"].get("direction") == None: js["firewall-rule"]["direction"]="<>" if js["firewall-rule"].get("match_tag_types") == None: js["firewall-rule"]["match_tag_types"]= {"tag_type": []} if (service): js["firewall-rule"]["service"] = service if js["firewall-rule"].get("service") == None: js["firewall-rule"]["service"] = {} if js["firewall-rule"]["service"].get("protocol") == None: js["firewall-rule"]["service"]["protocol"]="any" if js["firewall-rule"]["service"].get("src_ports") == None: js["firewall-rule"]["service"]["src_ports"]={"start_port": 0, "end_port": 65535} if js["firewall-rule"]["service"].get("dst_ports") == None: js["firewall-rule"]["service"]["dst_ports"]={"start_port": 0, "end_port": 65535} ## end: object specific payload=json.dumps(js) failed = crud (web_api, controller_ip, update, state, result, payload=payload, obj_type=obj_type, uuid=uuid) if failed: module.fail_json(msg='failure message', **result) module.exit_json(**result) def main(): run_module() if __name__ == '__main__': main()
4,462
0
46
98c88d01d58e03405eb7ae9a6afce512ca4d2ba3
3,404
py
Python
tests/unit/bokeh/models/test_axes.py
g-parki/bokeh
664ead5306bba64609e734d4105c8aa8cfb76d81
[ "BSD-3-Clause" ]
null
null
null
tests/unit/bokeh/models/test_axes.py
g-parki/bokeh
664ead5306bba64609e734d4105c8aa8cfb76d81
[ "BSD-3-Clause" ]
null
null
null
tests/unit/bokeh/models/test_axes.py
g-parki/bokeh
664ead5306bba64609e734d4105c8aa8cfb76d81
[ "BSD-3-Clause" ]
null
null
null
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import annotations # isort:skip import pytest ; pytest #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from bokeh.models import ( FixedTicker, MathText, PlainText, TeX, ) # Module under test import bokeh.models.axes as bma # isort:skip #----------------------------------------------------------------------------- # Setup #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
38.247191
86
0.439189
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import annotations # isort:skip import pytest ; pytest #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from bokeh.models import ( FixedTicker, MathText, PlainText, TeX, ) # Module under test import bokeh.models.axes as bma # isort:skip #----------------------------------------------------------------------------- # Setup #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- def test_ticker_accepts_number_sequences() -> None: a = bma.Axis(ticker=[-10, 0, 10, 20.7]) assert isinstance(a.ticker, FixedTicker) assert a.ticker.ticks == [-10, 0, 10, 20.7] a = bma.Axis() a.ticker = [-10, 0, 10, 20.7] assert isinstance(a.ticker, FixedTicker) assert a.ticker.ticks == [-10, 0, 10, 20.7] def test_axis_label_with_delimiters_do_not_convert_to_math_text_model() -> None: a = bma.Axis(axis_label=r"$$\sin(x+1)$$") assert isinstance(a.axis_label, str) assert a.axis_label == r"$$\sin(x+1)$$" def test_axis_label_accepts_math_text_with_declaration() -> None: a = bma.Axis(axis_label=TeX(text=r"\sin(x+2)")) assert isinstance(a.axis_label, MathText) assert a.axis_label.text == r"\sin(x+2)" def test_axis_label_accepts_math_text_with_declaration_and_dollar_signs() -> None: a = bma.Axis(axis_label=TeX(text=r"$\sin(x+3)$")) assert isinstance(a.axis_label, MathText) assert a.axis_label.text == r"$\sin(x+3)$" def test_axis_label_accepts_math_text_with_constructor_arg() -> None: a = bma.Axis(axis_label=TeX(r"\sin(x+4)")) assert isinstance(a.axis_label, MathText) assert a.axis_label.text == r"\sin(x+4)" def test_axis_label_accepts_math_text_with_constructor_arg_and_dollar_signs() -> None: a = bma.Axis(axis_label=TeX(r"$\sin(x+4)$")) assert isinstance(a.axis_label, MathText) assert a.axis_label.text == r"$\sin(x+4)$" def test_axis_label_accepts_string_with_dollar_signs() -> None: a = bma.Axis(axis_label=PlainText(r"$\sin(x+6)$")) assert isinstance(a.axis_label, PlainText) assert a.axis_label.text == r"$\sin(x+6)$" #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
1,483
0
161
a478619e6914d1e1305e3507e52c36a7ab9360ac
887
py
Python
swarms/test/test_results.py
swarms/python-client
d5b39b5304143266da48c9900c1b605e37e96912
[ "MIT" ]
5
2017-11-07T19:34:57.000Z
2017-11-15T12:07:29.000Z
swarms/test/test_results.py
swarms/python-client
d5b39b5304143266da48c9900c1b605e37e96912
[ "MIT" ]
5
2017-11-22T12:24:37.000Z
2018-02-10T15:31:21.000Z
swarms/test/test_results.py
swarms/python-client
d5b39b5304143266da48c9900c1b605e37e96912
[ "MIT" ]
2
2018-02-10T15:14:10.000Z
2018-04-17T08:11:52.000Z
import unittest from ..sdk import Client, Results from . import config if __name__ == '__main__': unittest.main()
22.175
70
0.461105
import unittest from ..sdk import Client, Results from . import config class ResultsTest(unittest.TestCase): client = Client(config.base_url, config.username, config.password) results = Results(client) def test_approve(self): self.results.approve({ "_links": { "approve": { "href": "/results/3/approve" } } }) def test_reject(self): self.results.reject({ "_links": { "reject": { "href": "/results/3/reject" } } }) def test_soft_reject(self): self.results.soft_reject({ "_links": { "softReject": { "href": "/results/3/soft-reject" } } }) if __name__ == '__main__': unittest.main()
545
198
23
51d11f001a852af14d3dbe85f4af50ccec0ddb61
343
py
Python
tests/ozpiwc/test_model_access.py
emosher/ozp-backend
d31d00bb8a28a8d0c999813f616b398f41516244
[ "Apache-2.0" ]
1
2018-10-05T17:03:01.000Z
2018-10-05T17:03:01.000Z
tests/ozpiwc/test_model_access.py
emosher/ozp-backend
d31d00bb8a28a8d0c999813f616b398f41516244
[ "Apache-2.0" ]
1
2017-01-06T19:20:32.000Z
2017-01-06T19:20:32.000Z
tests/ozpiwc/test_model_access.py
emosher/ozp-backend
d31d00bb8a28a8d0c999813f616b398f41516244
[ "Apache-2.0" ]
7
2016-12-16T15:42:05.000Z
2020-09-05T01:11:27.000Z
from django.test import TestCase from django.test import override_settings @override_settings(ES_ENABLED=False)
19.055556
61
0.688047
from django.test import TestCase from django.test import override_settings @override_settings(ES_ENABLED=False) class DataTest(TestCase): @classmethod def setUpTestData(cls): pass def setUp(self): pass def test_get_all_keys(self): # model_access.get_all_keys('wsmith') # flake8: noqa pass
105
102
22
de655777ca8f445cac9d75d319feab564d472995
4,942
py
Python
src/core/utils.py
Viewly/alpha-2
6b6d827197489164d8c4bde4f4d591dcec5a2163
[ "MIT" ]
null
null
null
src/core/utils.py
Viewly/alpha-2
6b6d827197489164d8c4bde4f4d591dcec5a2163
[ "MIT" ]
1
2021-05-07T06:26:16.000Z
2021-05-07T06:26:16.000Z
src/core/utils.py
Viewly/alpha-2
6b6d827197489164d8c4bde4f4d591dcec5a2163
[ "MIT" ]
null
null
null
import hashlib import os import shutil from concurrent.futures import ThreadPoolExecutor, as_completed from contextlib import suppress from functools import wraps from typing import List, Any, Union from funcy import contextmanager from toolz import keyfilter logger = None def ensure_directory(directory, force_recreate=True): """ Ensure directory will nuke provided path, and create a fresh directory. Args: directory (str): A nested path we want to ensure. force_recreate (bool): If True, it will always nuke the path and re-create it. Otherwise, it checks and returns if path already exists first. """ if not force_recreate: with suppress(Exception): if os.path.isdir(directory): return with suppress(FileNotFoundError): shutil.rmtree(directory) os.makedirs(directory) @contextmanager def changewd(path, is_child=False): """ This is a workaround function to make ipfs api work. If relative path is /foo/bar/baz, and global path is /x/foo/bar/baz, we change the current directory to /x/foo/bar, then we add baz to ipfs. After that, we change the directory back to the original (/x/). """ current_dir = os.getcwd() parent_dir = "/".join(path.split('/')[:-1]).lstrip('/') if is_child: change_to_dir = os.path.join(current_dir, parent_dir) else: change_to_dir = os.path.join('/', parent_dir) os.chdir(change_to_dir) yield os.chdir(current_dir) def cleanup_after(fn): """ A decorator to be used on methods that finalize actions on temporary directory. The temporary directory is destroyed when wrapped function returns. """ @wraps(fn) return wrapper # logging # ------- def log_exception(): """ Log to sentry.io. Alternatively, fallback to stdout stacktrace dump.""" global logger dsn = os.getenv('SENTRY_DSN') if dsn: import raven logger = raven.Client(dsn) if logger: logger.captureException() else: import traceback print(traceback.format_exc()) @contextmanager # toolz # ----- # --------------- # Multi-Threading # --------------- def dependency_injection(fn_args, dep_args): """ >>> dependency_injection([1, None, None], [2,3]) [1, 2, 3] """ fn_args = ensure_list(fn_args) dep_args = ensure_list(dep_args)[::-1] args = [] for fn_arg in fn_args: next_arg = fn_arg if fn_arg is not None else dep_args.pop() args.append(next_arg) return args def thread_multi( fn, fn_args: List[Any], dep_args: List[Union[Any, List[Any]]], fn_kwargs=None, max_workers=100, re_raise_errors=True): """ Run a function /w variable inputs concurrently. Args: fn: A pointer to the function that will be executed in parallel. fn_args: A list of arguments the function takes. None arguments will be displaced trough `dep_args`. dep_args: A list of lists of arguments to displace in `fn_args`. fn_kwargs: Keyword arguments that `fn` takes. max_workers: A cap of threads to run in parallel. re_raise_errors: Throw exceptions that happen in the worker pool. """ if not fn_kwargs: fn_kwargs = dict() fn_args = ensure_list(fn_args) with ThreadPoolExecutor(max_workers=max_workers) as executor: futures = (executor.submit(fn, *dependency_injection(fn_args, args), **fn_kwargs) for args in dep_args) for future in as_completed(futures): try: yield future.result() except Exception as e: log_exception() if re_raise_errors: raise e
26.427807
89
0.630716
import hashlib import os import shutil from concurrent.futures import ThreadPoolExecutor, as_completed from contextlib import suppress from functools import wraps from typing import List, Any, Union from funcy import contextmanager from toolz import keyfilter logger = None def sha1sum(filename): BLOCKSIZE = 65536 hasher = hashlib.sha1() with open(filename, 'rb') as f: buf = f.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = f.read(BLOCKSIZE) return hasher.hexdigest() def ensure_directory(directory, force_recreate=True): """ Ensure directory will nuke provided path, and create a fresh directory. Args: directory (str): A nested path we want to ensure. force_recreate (bool): If True, it will always nuke the path and re-create it. Otherwise, it checks and returns if path already exists first. """ if not force_recreate: with suppress(Exception): if os.path.isdir(directory): return with suppress(FileNotFoundError): shutil.rmtree(directory) os.makedirs(directory) @contextmanager def changewd(path, is_child=False): """ This is a workaround function to make ipfs api work. If relative path is /foo/bar/baz, and global path is /x/foo/bar/baz, we change the current directory to /x/foo/bar, then we add baz to ipfs. After that, we change the directory back to the original (/x/). """ current_dir = os.getcwd() parent_dir = "/".join(path.split('/')[:-1]).lstrip('/') if is_child: change_to_dir = os.path.join(current_dir, parent_dir) else: change_to_dir = os.path.join('/', parent_dir) os.chdir(change_to_dir) yield os.chdir(current_dir) def cleanup(files): if type(files) == str: files = [files] with suppress(Exception): for f in files: if os.path.isfile(f): os.unlink(f) elif os.path.isdir(f): shutil.rmtree(f) def cleanup_after(fn): """ A decorator to be used on methods that finalize actions on temporary directory. The temporary directory is destroyed when wrapped function returns. """ @wraps(fn) def wrapper(tmp_directory, *args, **kwargs): result = fn(tmp_directory, *args, **kwargs) cleanup([tmp_directory]) return result return wrapper def allowed_extension(filename, whitelist): return '.' in filename and filename.rsplit('.', 1)[-1] in whitelist # logging # ------- def log_exception(): """ Log to sentry.io. Alternatively, fallback to stdout stacktrace dump.""" global logger dsn = os.getenv('SENTRY_DSN') if dsn: import raven logger = raven.Client(dsn) if logger: logger.captureException() else: import traceback print(traceback.format_exc()) @contextmanager def log_exceptions(): try: yield except: log_exception() # toolz # ----- def keep(d, whitelist): return keyfilter(lambda k: k in whitelist, d) def omit(d, blacklist): return keyfilter(lambda k: k not in blacklist, d) # --------------- # Multi-Threading # --------------- def ensure_list(parameter): return parameter if type(parameter) in (list, tuple, set) else [parameter] def dependency_injection(fn_args, dep_args): """ >>> dependency_injection([1, None, None], [2,3]) [1, 2, 3] """ fn_args = ensure_list(fn_args) dep_args = ensure_list(dep_args)[::-1] args = [] for fn_arg in fn_args: next_arg = fn_arg if fn_arg is not None else dep_args.pop() args.append(next_arg) return args def thread_multi( fn, fn_args: List[Any], dep_args: List[Union[Any, List[Any]]], fn_kwargs=None, max_workers=100, re_raise_errors=True): """ Run a function /w variable inputs concurrently. Args: fn: A pointer to the function that will be executed in parallel. fn_args: A list of arguments the function takes. None arguments will be displaced trough `dep_args`. dep_args: A list of lists of arguments to displace in `fn_args`. fn_kwargs: Keyword arguments that `fn` takes. max_workers: A cap of threads to run in parallel. re_raise_errors: Throw exceptions that happen in the worker pool. """ if not fn_kwargs: fn_kwargs = dict() fn_args = ensure_list(fn_args) with ThreadPoolExecutor(max_workers=max_workers) as executor: futures = (executor.submit(fn, *dependency_injection(fn_args, args), **fn_kwargs) for args in dep_args) for future in as_completed(futures): try: yield future.result() except Exception as e: log_exception() if re_raise_errors: raise e
954
0
184
b5426ce03c25d2c3db0c7b7a3b82a01b4e548c15
2,495
py
Python
refactor/query_testing_back_end/subtle/defaults.py
joschout/tilde
1403b50842b83f2edd6b16b1fbe24b9bec2d0048
[ "Apache-2.0" ]
16
2019-03-06T06:11:33.000Z
2022-02-07T21:30:25.000Z
refactor/query_testing_back_end/subtle/defaults.py
joschout/tilde
1403b50842b83f2edd6b16b1fbe24b9bec2d0048
[ "Apache-2.0" ]
4
2019-10-08T14:48:23.000Z
2020-03-26T00:31:57.000Z
refactor/query_testing_back_end/subtle/defaults.py
krishnangovindraj/tilde
5243a02d92f375d56ffc49ab8c3d1a87e31e99b9
[ "Apache-2.0" ]
4
2019-08-14T05:40:47.000Z
2020-08-05T13:21:16.000Z
from refactor.default_interface import DefaultHandler from refactor.tilde_essentials.example import Example from refactor.tilde_essentials.leaf_strategy import LeafBuilder from refactor.tilde_essentials.splitter import Splitter from refactor.tilde_essentials.stop_criterion import StopCriterion from refactor.tilde_essentials.tree_builder import TreeBuilder from refactor.query_testing_back_end.subtle.clause_handling import build_clause from refactor.query_testing_back_end.subtle.evaluation import SubtleQueryEvaluator from refactor.query_testing_back_end.subtle.test_generation import SubtleTestGeneratorBuilder from refactor.representation.example_collection import ExampleCollection from tilde_config import subtle_path, split_criterion
51.979167
111
0.771543
from refactor.default_interface import DefaultHandler from refactor.tilde_essentials.example import Example from refactor.tilde_essentials.leaf_strategy import LeafBuilder from refactor.tilde_essentials.splitter import Splitter from refactor.tilde_essentials.stop_criterion import StopCriterion from refactor.tilde_essentials.tree_builder import TreeBuilder from refactor.query_testing_back_end.subtle.clause_handling import build_clause from refactor.query_testing_back_end.subtle.evaluation import SubtleQueryEvaluator from refactor.query_testing_back_end.subtle.test_generation import SubtleTestGeneratorBuilder from refactor.representation.example_collection import ExampleCollection from tilde_config import subtle_path, split_criterion class SubtleDefaultHandler(DefaultHandler): @staticmethod def get_default_decision_tree_builder(language, prediction_goal) -> TreeBuilder: test_evaluator = SubtleQueryEvaluator.build(subtle_path()) test_generator_builder = SubtleTestGeneratorBuilder(language=language, query_head_if_keys_format=prediction_goal) splitter = Splitter(split_criterion_str=split_criterion(), test_evaluator=test_evaluator, test_generator_builder=test_generator_builder) leaf_builder = LeafBuilder() stop_criterion = StopCriterion() tree_builder = TreeBuilder(splitter=splitter, leaf_builder=leaf_builder, stop_criterion=stop_criterion) return tree_builder @staticmethod def get_transformed_example_list(training_examples_collection: ExampleCollection): examples = [] for ex_wr_sp in training_examples_collection.get_example_wrappers_sp(): example_clause = build_clause(ex_wr_sp) example = Example(data=example_clause, label=ex_wr_sp.label) example.classification_term = ex_wr_sp.classification_term examples.append(example) return examples @staticmethod def get_transformed_test_example_list(simple_example_wrapper_list, training=False): test_examples_reformed = [] for ex_wr_sp in simple_example_wrapper_list: example_clause = build_clause(ex_wr_sp, training=False) example = Example(data=example_clause, label=ex_wr_sp.label) example.classification_term = ex_wr_sp.classification_term test_examples_reformed.append(example) return test_examples_reformed
1,572
157
23
c9b09a107304ec5a2d9596197ed6710b0ee8f7e4
998
py
Python
identixone/api/utility/v1/utility.py
identixone/identixone-python
232e5dfcf98ebe91a3ed433a265be161ee965a5e
[ "MIT" ]
2
2019-03-07T11:57:27.000Z
2022-01-21T20:24:01.000Z
identixone/api/utility/v1/utility.py
identixone/identixone-python
232e5dfcf98ebe91a3ed433a265be161ee965a5e
[ "MIT" ]
215
2019-02-18T15:28:09.000Z
2022-03-31T18:47:03.000Z
identixone/api/utility/v1/utility.py
identixone/identixone-python
232e5dfcf98ebe91a3ed433a265be161ee965a5e
[ "MIT" ]
1
2019-06-19T11:07:49.000Z
2019-06-19T11:07:49.000Z
from identixone.base.choices import Conf
32.193548
76
0.618236
from identixone.base.choices import Conf class Utility(object): def __init__(self, http_client): self.http_client = http_client def asm(self, photo): files = {'photo': photo} return self.http_client.post('v1/utility/asm/', files=files) def liveness(self, photo): files = {'photo': photo} return self.http_client.post('v1/utility/liveness/', files=files) def compare(self, photo1, photo2, liveness_photo1=False, liveness_photo2=False, conf=Conf.HA): files = {'photo1': photo1, 'photo2': photo2} data = { 'liveness_photo1': liveness_photo1, 'liveness_photo2': liveness_photo2, 'conf': conf } return self.http_client.post( 'v1/utility/compare/', files=files, data=data) def customer(self, source, offset=10): params = {'source': source, 'offset': offset} return self.http_client.get('v1/utility/customer/', params=params)
797
1
158
574ec9c1bd4120bbf01ba6b4f5112f48fc81ba49
7,059
py
Python
tools/convert_settings.py
sharvil/basis
58c4c88c69d42ed00082f9b3a9b032603caf5f06
[ "Apache-2.0" ]
2
2016-04-25T06:48:53.000Z
2021-05-06T20:24:49.000Z
tools/convert_settings.py
sharvil/basis
58c4c88c69d42ed00082f9b3a9b032603caf5f06
[ "Apache-2.0" ]
null
null
null
tools/convert_settings.py
sharvil/basis
58c4c88c69d42ed00082f9b3a9b032603caf5f06
[ "Apache-2.0" ]
5
2015-01-21T05:23:29.000Z
2019-04-05T00:16:53.000Z
#!/usr/bin/python import argparse import collections import json import math import os import struct import sys ANGLE_FACTOR = 2 * math.pi / 40000.0 SPEED_FACTOR = 1 / 1000.0 if __name__ == '__main__': main()
42.017857
125
0.702791
#!/usr/bin/python import argparse import collections import json import math import os import struct import sys ANGLE_FACTOR = 2 * math.pi / 40000.0 SPEED_FACTOR = 1 / 1000.0 def parseConfig(settingsFile): settings = {} curSection = None lines = [x.strip() for x in settingsFile.readlines()] for line in lines: if line.startswith('['): curSection = line[1:-1] settings[curSection] = {} elif line.find('=') != -1: key, value = line.split('=') settings[curSection][key] = value return settings def convertPrizeWeights(prizeSettings): prizeWeights = [] prizeWeights.append(0) # PrizeType.NONE prizeWeights.append(int(prizeSettings['Gun'])) prizeWeights.append(int(prizeSettings['Bomb'])) prizeWeights.append(int(prizeSettings['QuickCharge'])) prizeWeights.append(int(prizeSettings['BouncingBullets'])) prizeWeights.append(int(prizeSettings['MultiFire'])) return prizeWeights def convertShip(name, settings): radius = int(settings[name]['Radius']) if radius == 0: radius = 14 jsonSettings = collections.OrderedDict() jsonSettings['name'] = name jsonSettings['radius'] = radius jsonSettings['bounceFactor'] = 16.0 / int(settings['Misc']['BounceFactor']) jsonSettings['rotationRadiansPerTick'] = int(settings[name]['InitialRotation']) * ANGLE_FACTOR jsonSettings['speedPixelsPerTick'] = int(settings[name]['InitialSpeed']) * SPEED_FACTOR jsonSettings['maxEnergy'] = int(settings[name]['InitialEnergy']) jsonSettings['accelerationPerTick'] = int(settings[name]['InitialThrust']) / 1000.0 jsonSettings['afterburnerMaxSpeed'] = int(settings[name]['MaximumSpeed']) * SPEED_FACTOR jsonSettings['afterburnerAcceleration'] = int(settings[name]['MaximumThrust']) / 1000.0 jsonSettings['afterburnerEnergy'] = int(settings[name]['AfterburnerEnergy']) / 1000.0 jsonSettings['rechargeRate'] = int(settings[name]['InitialRecharge']) / 1000.0 jsonSettings['respawnDelay'] = int(settings['Kill']['EnterDelay']) bullet = collections.OrderedDict() bullet['fireEnergy'] = int(settings[name]['BulletFireEnergy']) bullet['speed'] = int(settings[name]['BulletSpeed']) * SPEED_FACTOR bullet['fireDelay'] = int(settings[name]['BulletFireDelay']) bullet['lifetime'] = int(settings['Bullet']['BulletAliveTime']) bullet['damage'] = int(settings['Bullet']['BulletDamageLevel']) bullet['damageUpgrade'] = int(settings['Bullet']['BulletDamageUpgrade']) bullet['initialLevel'] = int(settings[name]['InitialGuns']) - 1 bullet['maxLevel'] = int(settings[name]['MaxGuns']) - 1 bullet['bounces'] = True bullet['doubleBarrel'] = int(settings[name]['DoubleBarrel']) != 0 if int(settings[name]['MultiFireAngle']) != 0: bullet['multifire'] = collections.OrderedDict() bullet['multifire']['fireEnergy'] = int(settings[name]['MultiFireEnergy']) bullet['multifire']['fireDelay'] = int(settings[name]['MultiFireDelay']) bullet['multifire']['angle'] = int(settings[name]['MultiFireAngle']) * ANGLE_FACTOR bomb = collections.OrderedDict() bomb['fireEnergy'] = int(settings[name]['BombFireEnergy']) bomb['fireEnergyUpgrade'] = int(settings[name]['BombFireEnergyUpgrade']) bomb['speed'] = int(settings[name]['BombSpeed']) * SPEED_FACTOR bomb['fireDelay'] = int(settings[name]['BombFireDelay']) bomb['lifetime'] = int(settings['Bomb']['BombAliveTime']) bomb['damage'] = int(settings['Bomb']['BombDamageLevel']) bomb['damageUpgrade'] = int(settings['Bomb']['BombDamageLevel']) bomb['initialLevel'] = int(settings[name]['InitialBombs']) - 1 bomb['maxLevel'] = int(settings[name]['MaxBombs']) - 1 bomb['blastRadius'] = int(settings['Bomb']['BombExplodePixels']) bomb['blastRadiusUpgrade'] = int(settings['Bomb']['BombExplodePixels']) bomb['proxRadius'] = int(settings['Bomb']['ProximityDistance']) bomb['proxRadiusUpgrade'] = int(settings['Bomb']['ProximityDistance']) bomb['bounceCount'] = int(settings[name]['BombBounceCount']) bomb['recoilAcceleration'] = int(settings[name]['BombThrust']) / 1000.0 burst = collections.OrderedDict() burst['fireDelay'] = int(settings[name]['BulletFireDelay']) # Assume burst fire delay is the same as the bullet fire delay burst['lifetime'] = int(settings['Bullet']['BulletAliveTime']) # Assume burst lifetime is the same as a regular bullet burst['damage'] = int(settings['Bullet']['BulletDamageLevel']) + 4 * int(settings['Bullet']['BulletDamageUpgrade']) burst['speed'] = int(settings[name]['BurstSpeed']) * SPEED_FACTOR burst['shrapnelCount'] = int(settings[name]['BurstShrapnel']) burst['initialCount'] = int(settings[name]['InitialBurst']) burst['maxCount'] = int(settings[name]['BurstMax']) decoy = collections.OrderedDict() decoy['fireDelay'] = bullet['fireDelay'] # Assume decoy fire delay is the same as the bullet fire delay decoy['lifetime'] = int(settings['Misc']['DecoyAliveTime']) decoy['initialCount'] = int(settings[name]['InitialDecoy']) decoy['maxCount'] = int(settings[name]['DecoyMax']) repel = collections.OrderedDict() repel['fireDelay'] = 50 # TODO: figure out what this should be repel['initialCount'] = int(settings[name]['InitialRepel']) repel['maxCount'] = int(settings[name]['RepelMax']) repel['lifetime'] = int(settings['Repel']['RepelTime']) repel['distance'] = int(settings['Repel']['RepelDistance']) repel['speed'] = int(settings['Repel']['RepelSpeed']) * SPEED_FACTOR jsonSettings['bullet'] = bullet jsonSettings['bomb'] = bomb jsonSettings['burst'] = burst jsonSettings['decoy'] = decoy jsonSettings['repel'] = repel return jsonSettings def convertToJson(settings): jsonSettings = collections.OrderedDict() jsonSettings['game'] = collections.OrderedDict({ 'killPoints': 20, 'maxTeams': 2 }) jsonSettings['network'] = collections.OrderedDict({ 'sendPositionDelay': int(settings['Misc']['SendPositionDelay']), 'fastSendPositionDelay': max(1, int(settings['Misc']['SendPositionDelay']) / 4) }) jsonSettings['map'] = collections.OrderedDict({ 'width': 1024, 'height': 1024, 'tileWidth': 16, 'tileHeight': 16, 'spawnRadius': 500 }) jsonSettings['prize'] = collections.OrderedDict({ 'decayTime': 18000, 'count': 50, 'radius': 128, 'weights': convertPrizeWeights(settings['PrizeWeight']) }) jsonSettings['ships'] = [ convertShip('Warbird', settings), convertShip('Javelin', settings), convertShip('Spider', settings), convertShip('Leviathan', settings), convertShip('Terrier', settings), convertShip('Weasel', settings), convertShip('Lancaster', settings), convertShip('Shark', settings) ] return jsonSettings def main(): parser = argparse.ArgumentParser(description = 'Converts a SubSpace server.cfg file to a dotproduct settings file.') parser.add_argument('settingsFile', type=argparse.FileType('rb')) args = parser.parse_args() settings = parseConfig(args.settingsFile) jsonSettings = convertToJson(settings) print json.dumps(jsonSettings, indent = 2) if __name__ == '__main__': main()
6,730
0
115
a197e0534d286fb5df7f6e049547cd6674633bc9
7,596
py
Python
.kokoro/trampoline_windows.py
directionless/google-cloud-ruby
bb7c09406b23de5223897d92edc63c21cd44f471
[ "Apache-2.0" ]
8
2021-04-24T02:35:09.000Z
2022-01-29T03:05:45.000Z
.kokoro/trampoline_windows.py
directionless/google-cloud-ruby
bb7c09406b23de5223897d92edc63c21cd44f471
[ "Apache-2.0" ]
1
2019-10-18T15:31:34.000Z
2019-10-18T17:25:07.000Z
.kokoro/trampoline_windows.py
directionless/google-cloud-ruby
bb7c09406b23de5223897d92edc63c21cd44f471
[ "Apache-2.0" ]
3
2017-07-20T20:10:34.000Z
2022-03-31T03:17:01.000Z
#!/usr/env/bin python3 # Copyright 2017 Google Inc. # # 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Trampoline handles launching into a docker container for running tests.""" import errno import os import shutil import subprocess import sys import tempfile from subprocess import Popen, PIPE ENV_BLACKLIST = ["ALIASES", "ALLUSERSPROFILE", "ANDROID_HOME", "ANSICON", "ANSICON_DEF", "ANT_HOME", "APPDATA", "ARCHITECTURE", "ARCHITECTURE_BITS", "CCALL", "CEXEC", "CHOCOLATEYINSTALL", "CHOCOLATEYLASTPATHUPDATE", "CHOCOLATEYTOOLSLOCATION", "CLASSPATH", "CLIENTNAME", "CLOUDSDK_CONFIG", "CLOUD_SDK_VERSION", "CMDER_ALIASES", "CMDER_CLINK", "CMDER_CONFIGURED", "CMDER_INIT_END", "CMDER_INIT_START", "CMDER_ROOT", "CMDER_SHELL", "CMDER_USER_FLAGS", "COMPUTERNAME", "CONEMUANSI", "CONEMUARGS", "CONEMUBACKHWND", "CONEMUBASEDIR", "CONEMUBASEDIRSHORT", "CONEMUBUILD", "CONEMUCFGDIR", "CONEMUDIR", "CONEMUDRAWHWND", "CONEMUDRIVE", "CONEMUHOOKS", "CONEMUHWND", "CONEMUPALETTE", "CONEMUPID", "CONEMUSERVERPID", "CONEMUTASK", "CONEMUWORKDIR", "CONEMUWORKDRIVE", "CUDA_PATH", "CUDA_PATH_V9_0", "CUDA_PATH_V9_1", "ComSpec", "CommonProgramFiles", "CommonProgramFiles(x86)", "CommonProgramW6432", "DEBUG_OUTPUT", "DERBY_HOME", "FAST_INIT", "FEFLAGNAME", "FSHARPINSTALLDIR", "GIT_INSTALL_ROOT", "GOOGETROOT", "GOPATH", "GOROOT", "GRADLE_HOME", "GRADLE_USER_HOME", "HOME", "HOMEDRIVE", "HOMEPATH", "J2REDIR", "J2SDKDIR", "JAVA_HOME", "LANG", "LIB_BASE", "LIB_CONSOLE", "LIB_GIT", "LIB_PATH", "LIB_PROFILE", "LOCALAPPDATA", "LOGNAME", "LOGONSERVER", "M2", "M2_HOME", "M2_REPO", "MAIL", "MAVEN_OPTS", "MAX_DEPTH", "MSMPI_BIN", "NIX_TOOLS", "NUMBER_OF_PROCESSORS", "NVCUDASAMPLES9_0_ROOT", "NVCUDASAMPLES9_1_ROOT", "NVCUDASAMPLES_ROOT", "OS", "PATH", "PATHEXT", "PLINK_PROTOCOL", "PROCESSOR_ARCHITECTURE", "PROCESSOR_IDENTIFIER", "PROCESSOR_LEVEL", "PROCESSOR_REVISION", "PROMPT", "PSModulePath", "PUBLIC", "PWD", "PYENV_DIR", "PYENV_HOOK_PATH", "PYENV_ROOT", "PYENV_SHELL", "PYENV_VERSION", "PYENV_VIRTUALENV_INIT", "Path", "ProgramData", "ProgramFiles", "ProgramFiles(x86)", "ProgramW6432", "QT_QPA_PLATFORMTHEME", "SESSIONNAME", "SHELL", "SHLVL", "SSH_CLIENT", "SSH_CONNECTION", "SVN_SSH", "SystemDrive", "SystemRoot", "TEMP", "TERM", "TIME_INIT", "TMP", "TMPDIR", "TRAMPOLINE_BUILD_FILE", "TRAMPOLINE_IMAGE", "USER", "USERDOMAIN", "USERDOMAIN_ROAMINGPROFILE", "USERNAME", "USERPROFILE", "USER_ALIASES", "VERBOSE_OUTPUT", "VS110COMNTOOLS", "VS120COMNTOOLS", "VS140COMNTOOLS", "VSSDK140INSTALL", "XDG_RUNTIME_DIR", "XDG_SESSION_COOKIE", "XDG_SESSION_ID", "_system_arch" "_system_name", "_system_type", "_system_version", "rvm_bin_path", "rvm_path", "rvm_prefix", "rvm_version", "windir"] if __name__ == '__main__': main()
42.674157
117
0.640864
#!/usr/env/bin python3 # Copyright 2017 Google Inc. # # 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Trampoline handles launching into a docker container for running tests.""" import errno import os import shutil import subprocess import sys import tempfile from subprocess import Popen, PIPE ENV_BLACKLIST = ["ALIASES", "ALLUSERSPROFILE", "ANDROID_HOME", "ANSICON", "ANSICON_DEF", "ANT_HOME", "APPDATA", "ARCHITECTURE", "ARCHITECTURE_BITS", "CCALL", "CEXEC", "CHOCOLATEYINSTALL", "CHOCOLATEYLASTPATHUPDATE", "CHOCOLATEYTOOLSLOCATION", "CLASSPATH", "CLIENTNAME", "CLOUDSDK_CONFIG", "CLOUD_SDK_VERSION", "CMDER_ALIASES", "CMDER_CLINK", "CMDER_CONFIGURED", "CMDER_INIT_END", "CMDER_INIT_START", "CMDER_ROOT", "CMDER_SHELL", "CMDER_USER_FLAGS", "COMPUTERNAME", "CONEMUANSI", "CONEMUARGS", "CONEMUBACKHWND", "CONEMUBASEDIR", "CONEMUBASEDIRSHORT", "CONEMUBUILD", "CONEMUCFGDIR", "CONEMUDIR", "CONEMUDRAWHWND", "CONEMUDRIVE", "CONEMUHOOKS", "CONEMUHWND", "CONEMUPALETTE", "CONEMUPID", "CONEMUSERVERPID", "CONEMUTASK", "CONEMUWORKDIR", "CONEMUWORKDRIVE", "CUDA_PATH", "CUDA_PATH_V9_0", "CUDA_PATH_V9_1", "ComSpec", "CommonProgramFiles", "CommonProgramFiles(x86)", "CommonProgramW6432", "DEBUG_OUTPUT", "DERBY_HOME", "FAST_INIT", "FEFLAGNAME", "FSHARPINSTALLDIR", "GIT_INSTALL_ROOT", "GOOGETROOT", "GOPATH", "GOROOT", "GRADLE_HOME", "GRADLE_USER_HOME", "HOME", "HOMEDRIVE", "HOMEPATH", "J2REDIR", "J2SDKDIR", "JAVA_HOME", "LANG", "LIB_BASE", "LIB_CONSOLE", "LIB_GIT", "LIB_PATH", "LIB_PROFILE", "LOCALAPPDATA", "LOGNAME", "LOGONSERVER", "M2", "M2_HOME", "M2_REPO", "MAIL", "MAVEN_OPTS", "MAX_DEPTH", "MSMPI_BIN", "NIX_TOOLS", "NUMBER_OF_PROCESSORS", "NVCUDASAMPLES9_0_ROOT", "NVCUDASAMPLES9_1_ROOT", "NVCUDASAMPLES_ROOT", "OS", "PATH", "PATHEXT", "PLINK_PROTOCOL", "PROCESSOR_ARCHITECTURE", "PROCESSOR_IDENTIFIER", "PROCESSOR_LEVEL", "PROCESSOR_REVISION", "PROMPT", "PSModulePath", "PUBLIC", "PWD", "PYENV_DIR", "PYENV_HOOK_PATH", "PYENV_ROOT", "PYENV_SHELL", "PYENV_VERSION", "PYENV_VIRTUALENV_INIT", "Path", "ProgramData", "ProgramFiles", "ProgramFiles(x86)", "ProgramW6432", "QT_QPA_PLATFORMTHEME", "SESSIONNAME", "SHELL", "SHLVL", "SSH_CLIENT", "SSH_CONNECTION", "SVN_SSH", "SystemDrive", "SystemRoot", "TEMP", "TERM", "TIME_INIT", "TMP", "TMPDIR", "TRAMPOLINE_BUILD_FILE", "TRAMPOLINE_IMAGE", "USER", "USERDOMAIN", "USERDOMAIN_ROAMINGPROFILE", "USERNAME", "USERPROFILE", "USER_ALIASES", "VERBOSE_OUTPUT", "VS110COMNTOOLS", "VS120COMNTOOLS", "VS140COMNTOOLS", "VSSDK140INSTALL", "XDG_RUNTIME_DIR", "XDG_SESSION_COOKIE", "XDG_SESSION_ID", "_system_arch" "_system_name", "_system_type", "_system_version", "rvm_bin_path", "rvm_path", "rvm_prefix", "rvm_version", "windir"] def setup_isolated_gcloud_config(tmpdir): os.environ['CLOUDSDK_CONFIG'] = os.path.join(tmpdir, 'cloudsdk') def setup_gcloud_auth(service_account_key_file): subprocess.check_output([ 'gcloud', 'auth', 'activate-service-account', '--key-file', service_account_key_file], shell=True) try: # Attempt to the use the GA command, fall back to beta if Cloud SDK # is too old. subprocess.check_call([ 'gcloud', 'auth', 'configure-docker', '--quiet'], shell=True) except subprocess.CalledProcessError: subprocess.check_call([ 'gcloud', 'beta', 'auth', 'configure-docker', '--quiet'], shell=True) def pull_docker_image(image): # Retry pulling the image up to three time. for n in range(3): try: subprocess.check_call(['docker', 'pull', image], shell=True) return except subprocess.CalledProcessError: print( "Failed to pull docker image, attempt {} out of 3.".format(n)) raise RuntimeError("Failed to pull image {}.".format(image)) def create_docker_envfile(tmpdir): exported_env_keys = ( key for key in os.environ.keys() if key not in ENV_BLACKLIST) env_file_name = os.path.join(tmpdir, 'envfile') with open(env_file_name, 'w') as env_file: for key in exported_env_keys: os.environ[key] = os.environ[key].replace( 'T:', 'C:').replace('t:', 'c:') env_file.write('{}\n'.format(key)) return env_file_name def copy(src, dest): delete(dest) try: shutil.copytree(src, dest, symlinks=True) except OSError as e: # If the error was caused because the source wasn't a directory if e.errno == errno.ENOTDIR: shutil.copy(src, dest) else: print('Directory not copied. Error: %s' % e) def delete(src): try: shutil.rmtree(src) except: e = sys.exc_info()[0] print('Error while deleting {}: {}'.format(src, e)) def run_docker(image, env_file, kokoro_artifacts_dir, build_file): docker_args = [ 'docker', 'run', '--rm', '--interactive', # Attach stdin. '--volume="C:\\src:C:\\src"', # Set the working directory to the workspace. '--workdir={}'.format(kokoro_artifacts_dir), # Run the test script. '--entrypoint="C:\\src\\{}"'.format(build_file), '--env-file={}'.format(env_file) ] # exec_args = ['"{}"'.format(shutil.which('docker'))] + docker_args + [image] exec_args = docker_args + ['{}:latest'.format(image)] print('Executing: {}'.format(' '.join(exec_args))) sys.stdout.flush() sys.stderr.flush() p = Popen(" ".join(exec_args), stdout=PIPE, encoding="utf-8", stderr=PIPE) output, err = p.communicate() print(output) if p.returncode != 0: print(err) raise RuntimeError(err) def main(): # Windows docker containers do not like non-C:\\ drives old_kokoro_artifacts_dir = os.environ['KOKORO_ARTIFACTS_DIR'] kokoro_artifacts_dir = old_kokoro_artifacts_dir.replace( "T:\\", "C:\\").replace("t:\\", "C:\\") copy(old_kokoro_artifacts_dir, kokoro_artifacts_dir) old_kokoro_gfile_dir = os.environ['KOKORO_GFILE_DIR'] kokoro_gfile_dir = old_kokoro_gfile_dir.replace( "T:\\", "C:\\").replace("t:\\", "C:\\") copy(old_kokoro_gfile_dir, kokoro_gfile_dir) service_account_key_file = os.path.join( kokoro_gfile_dir, 'kokoro-trampoline.service-account.json') image = os.environ['TRAMPOLINE_IMAGE'] build_file = os.environ['TRAMPOLINE_BUILD_FILE'] tmpdir = tempfile.mkdtemp() setup_isolated_gcloud_config(tmpdir) setup_gcloud_auth(service_account_key_file) pull_docker_image(image) env_file = create_docker_envfile(tmpdir) run_docker(image, env_file, kokoro_artifacts_dir, build_file) if __name__ == '__main__': main()
3,746
0
185