id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
156226
import random def pick_random_move(board): """Takes in an array_board and returns a random index in that board that contains None.""" possible_moves = get_available_moves(board) number_of_possible_moves = len(possible_moves) if number_of_possible_moves < 1: return -1 random_index_into_possible_moves = random.randint(0, number_of_possible_moves-1) return possible_moves[random_index_into_possible_moves] def get_available_moves(board): """Return an array of board positions/indices that contain "None".""" possible_moves = [] for i, board_position in enumerate(board): if board_position == None: possible_moves.append(i) return possible_moves
StarcoderdataPython
1778779
<filename>elmo-chainer/bilm/elmo.py<gh_stars>100-1000 import json import logging # from typing import Union, List, Dict, Any import warnings import numpy import h5py import tqdm import chainer from chainer import cuda from chainer import functions as F from chainer import links as L from chainer import Variable from .data import UnicodeCharsVocabulary, Batcher from .elmo_lstm import ElmoLstm from .file_utils import cached_path from .highway import Highway from .scalar_mix import ScalarMix ConfigurationError = ValueError logger = logging.getLogger(__name__) DTYPE = 'float32' def add_sentence_boundary_token_ids(tensor, mask, sentence_begin_token, sentence_end_token): """ Add begin/end of sentence tokens to the batch of sentences. Given a batch of sentences with size ``(batch_size, timesteps)`` or ``(batch_size, timesteps, dim)`` this returns a tensor of shape ``(batch_size, timesteps + 2)`` or ``(batch_size, timesteps + 2, dim)`` respectively. Returns both the new tensor and updated mask. Parameters ---------- tensor : ``torch.Tensor`` A tensor of shape ``(batch_size, timesteps)`` or ``(batch_size, timesteps, dim)`` mask : ``torch.Tensor`` A tensor of shape ``(batch_size, timesteps)`` sentence_begin_token: Any (anything that can be broadcast in torch for assignment) For 2D input, a scalar with the <S> id. For 3D input, a tensor with length dim. sentence_end_token: Any (anything that can be broadcast in torch for assignment) For 2D input, a scalar with the </S> id. For 3D input, a tensor with length dim. Returns ------- tensor_with_boundary_tokens : ``torch.Tensor`` The tensor with the appended and prepended boundary tokens. If the input was 2D, it has shape (batch_size, timesteps + 2) and if the input was 3D, it has shape (batch_size, timesteps + 2, dim). new_mask : ``torch.Tensor`` The new mask for the tensor, taking into account the appended tokens marking the beginning and end of the sentence. """ xp = cuda.get_array_module(mask) # TODO: matthewp, profile this transfer sequence_lengths = cuda.to_cpu(mask.sum(axis=1)) tensor_shape = list(tensor.shape) new_shape = list(tensor_shape) new_shape[1] = tensor_shape[1] + 2 tensor_with_boundary_tokens = xp.zeros(new_shape).astype('i') # TODO: gpu change if len(tensor_shape) == 2: tensor_with_boundary_tokens[:, 1:-1] = \ tensor tensor_with_boundary_tokens[:, 0] = \ xp.asarray(sentence_begin_token) for i, j in enumerate(sequence_lengths): tensor_with_boundary_tokens[i, j + 1] = \ xp.asarray(sentence_end_token) new_mask = (tensor_with_boundary_tokens != 0).astype('i') elif len(tensor_shape) == 3: tensor_with_boundary_tokens[:, 1:-1, :] = tensor for i, j in enumerate(sequence_lengths): tensor_with_boundary_tokens[i, 0, :] = \ xp.asarray(sentence_begin_token) tensor_with_boundary_tokens[i, j + 1, :] = \ xp.asarray(sentence_end_token) new_mask = ((tensor_with_boundary_tokens > 0).sum(axis=-1) > 0)\ .astype('i') else: raise ValueError( "add_sentence_boundary_token_ids only accepts 2D and 3D input") return tensor_with_boundary_tokens, new_mask def remove_sentence_boundaries(tensor, mask): """ Remove begin/end of sentence embeddings from the batch of sentences. Given a batch of sentences with size ``(batch_size, timesteps, dim)`` this returns a tensor of shape ``(batch_size, timesteps - 2, dim)`` after removing the beginning and end sentence markers. The sentences are assumed to be padded on the right, with the beginning of each sentence assumed to occur at index 0 (i.e., ``mask[:, 0]`` is assumed to be 1). Returns both the new tensor and updated mask. This function is the inverse of ``add_sentence_boundary_token_ids``. Parameters ---------- tensor : ``torch.Tensor`` A tensor of shape ``(batch_size, timesteps, dim)`` mask : ``torch.Tensor`` A tensor of shape ``(batch_size, timesteps)`` Returns ------- tensor_without_boundary_tokens : ``torch.Tensor`` The tensor after removing the boundary tokens of shape ``(batch_size, timesteps - 2, dim)`` new_mask : ``torch.Tensor`` The new mask for the tensor of shape ``(batch_size, timesteps - 2)``. """ xp = cuda.get_array_module(mask) # TODO: matthewp, profile this transfer sequence_lengths = mask.sum(axis=1) tensor_shape = list(tensor.array.shape) new_shape = list(tensor_shape) new_shape[1] = tensor_shape[1] - 2 tensor_without_boundary_tokens = xp.zeros(new_shape, 'f') new_mask = xp.zeros((new_shape[0], new_shape[1]), 'i') for i, j in enumerate(sequence_lengths): if j > 2: tensor_without_boundary_tokens[i, :(j - 2), :] = \ tensor.array[i, 1:(j - 1), :] new_mask[i, :(j - 2)] = 1 return tensor_without_boundary_tokens, new_mask def remove_sentence_boundaries_for_variable(tensor, mask): """ Variable's propagation is kept. Remove begin/end of sentence embeddings from the batch of sentences. Given a batch of sentences with size ``(batch_size, timesteps, dim)`` this returns a tensor of shape ``(batch_size, timesteps - 2, dim)`` after removing the beginning and end sentence markers. The sentences are assumed to be padded on the right, with the beginning of each sentence assumed to occur at index 0 (i.e., ``mask[:, 0]`` is assumed to be 1). Returns both the new tensor and updated mask. This function is the inverse of ``add_sentence_boundary_token_ids``. Parameters ---------- tensor : ``torch.Tensor`` A tensor of shape ``(batch_size, timesteps, dim)`` mask : ``torch.Tensor`` A tensor of shape ``(batch_size, timesteps)`` Returns ------- tensor_without_boundary_tokens : ``torch.Tensor`` The tensor after removing the boundary tokens of shape ``(batch_size, timesteps - 2, dim)`` new_mask : ``torch.Tensor`` The new mask for the tensor of shape ``(batch_size, timesteps - 2)``. """ xp = cuda.get_array_module(mask) # TODO: matthewp, profile this transfer sequence_lengths = mask.sum(axis=1) tensor_shape = list(tensor.array.shape) new_shape = list(tensor_shape) new_shape[1] = tensor_shape[1] - 2 # tensor_without_boundary_tokens = xp.zeros(new_shape, 'f') tensor_without_boundary_tokens = [] new_mask = xp.zeros((new_shape[0], new_shape[1]), 'i') for i, j in enumerate(sequence_lengths): if j > 2: new_mask[i, :(j - 2)] = 1 tensor_without_bos = tensor[:, 1:] tensor_without_bos_and_tailone = tensor_without_bos[:, :-1] wide_new_mask = xp.broadcast_to( new_mask[:, :, None], tensor_without_bos_and_tailone.shape) tensor_without_bos_and_eos = tensor_without_bos_and_tailone * wide_new_mask # test xp.testing.assert_array_almost_equal( tensor_without_bos_and_eos.array, remove_sentence_boundaries(tensor, mask)[0], decimal=6) tensor_without_boundary_tokens = tensor_without_bos_and_eos return tensor_without_boundary_tokens, new_mask class Elmo(chainer.Chain): """ Compute ELMo representations using a pre-trained bidirectional language model. See "Deep contextualized word representations", Peters et al. for details. This module takes character id input and computes ``num_output_representations`` different layers of ELMo representations. Typically ``num_output_representations`` is 1 or 2. For example, in the case of the SRL model in the above paper, ``num_output_representations=1`` where ELMo was included at the input token representation layer. In the case of the SQuAD model, ``num_output_representations=2`` as ELMo was also included at the GRU output layer. In the implementation below, we learn separate scalar weights for each output layer, but only run the biLM once on each input sequence for efficiency. Parameters ---------- options_file : ``str``, required. ELMo JSON options file weight_file : ``str``, required. ELMo hdf5 weight file num_output_representations: ``int``, required. The number of ELMo representation layers to output. requires_grad: ``bool``, optional If True, compute gradient of ELMo parameters for fine tuning. do_layer_norm : ``bool``, optional, (default=False). Should we apply layer normalization (passed to ``ScalarMix``)? dropout : ``float``, optional, (default = 0.5). The dropout to be applied to the ELMo representations. module : ``torch.nn.Module``, optional, (default = None). If provided, then use this module instead of the pre-trained ELMo biLM. If using this option, then pass ``None`` for both ``options_file`` and ``weight_file``. The module must provide a public attribute ``num_layers`` with the number of internal layers and its ``forward`` method must return a ``dict`` with ``activations`` and ``mask`` keys (see `_ElmoBilm`` for an example). Note that ``requires_grad`` is also ignored with this option. """ def __init__(self, options_file, weight_file, token_embedding_file=None, token_batcher=None, num_output_representations=1, requires_grad=False, do_layer_norm=False, dropout=0.5): super(Elmo, self).__init__() logging.info("Initializing ELMo") with self.init_scope(): self._elmo_lstm = _ElmoBiLm( options_file, weight_file, token_embedding_file=token_embedding_file, token_batcher=token_batcher, requires_grad=requires_grad) self._dropout_ratio = dropout self.use_character_inputs = (token_embedding_file is None) self._scalar_mixes = [] for k in range(num_output_representations): scalar_mix = ScalarMix( self._elmo_lstm.num_layers, do_layer_norm=do_layer_norm) setattr(self, 'scalar_mix_{}'.format(k), scalar_mix) self._scalar_mixes.append(scalar_mix) def get_output_dim(self): return self._elmo_lstm.get_output_dim() def forward(self, inputs): """ Parameters ---------- inputs : ``torch.autograd.Variable`` Shape ``(batch_size, timesteps, 50)`` of character ids representing the current batch. We also accept tensors with additional optional dimensions: ``(batch_size, dim0, dim1, ..., dimn, timesteps, 50)`` Returns ------- Dict with keys: ``'elmo_representations'``: ``List[torch.autograd.Variable]`` A ``num_output_representations`` list of ELMo representations for the input sequence. Each representation is shape ``(batch_size, timesteps, embedding_dim)`` ``'mask'``: ``torch.autograd.Variable`` Shape ``(batch_size, timesteps)`` long tensor with sequence mask. """ if self.use_character_inputs: # reshape the input if needed original_shape = inputs.shape timesteps, num_characters = original_shape[-2:] if len(original_shape) > 3: reshaped_inputs = inputs.reshape( (-1, timesteps, num_characters)) else: reshaped_inputs = inputs else: # reshape the input if needed original_shape = inputs.shape timesteps = original_shape[-1] if len(original_shape) > 2: warnings.warn( 'It is not tested to use input with shape (batch_size, dim0, ..., timesteps) to token-input Elmo.\n' 'Input with shape (batch_size, timesteps) is recommended.') reshaped_inputs = inputs.reshape((-1, timesteps)) else: reshaped_inputs = inputs # run the biLM # no backprop through bilstm for lightening computations with chainer.using_config("train", False), \ chainer.no_backprop_mode(): bilm_output = self._elmo_lstm.forward(reshaped_inputs) layer_activations = bilm_output['activations'] mask_with_bos_eos = bilm_output['mask'] # compute the elmo representations representations = [] for i in range(len(self._scalar_mixes)): scalar_mix = getattr(self, 'scalar_mix_{}'.format(i)) representation_with_bos_eos = scalar_mix.forward( layer_activations, mask_with_bos_eos) representation_without_bos_eos, mask_without_bos_eos = remove_sentence_boundaries( representation_with_bos_eos, mask_with_bos_eos ) representations.append(F.dropout( representation_without_bos_eos, ratio=self._dropout_ratio)) if self.use_character_inputs: # reshape if necessary if len(original_shape) > 3: mask = mask_without_bos_eos.reshape(original_shape[:-1]) elmo_representations = [representation.reshape(original_shape[:-1] + (-1, )) for representation in representations] else: mask = mask_without_bos_eos elmo_representations = representations else: if len(original_shape) > 2: mask = mask_without_bos_eos.reshape(original_shape) elmo_representations = [representation.reshape(original_shape + (-1, )) for representation in representations] else: mask = mask_without_bos_eos elmo_representations = representations layer_activations_without_bos_eos = [ remove_sentence_boundaries_for_variable( a_layer_activation, mask_with_bos_eos)[0] for a_layer_activation in layer_activations] return {'elmo_representations': elmo_representations, 'mask': mask, 'elmo_layers': layer_activations_without_bos_eos} @classmethod def from_params(cls, params): # def from_params(cls, params: Params) -> 'Elmo': # Add files to archive params.add_file_to_archive('options_file') params.add_file_to_archive('weight_file') options_file = params.pop('options_file') weight_file = params.pop('weight_file') requires_grad = params.pop('requires_grad', False) num_output_representations = params.pop('num_output_representations') do_layer_norm = params.pop_bool('do_layer_norm', False) params.assert_empty(cls.__name__) return cls(options_file, weight_file, num_output_representations, requires_grad=requires_grad, do_layer_norm=do_layer_norm) class _ElmoTokenEmbedder(chainer.Chain): def __init__(self, options_file, token_embedding_file, token_batcher, requires_grad=False): super(_ElmoTokenEmbedder, self).__init__() with open(cached_path(options_file), 'r') as fin: self._options = json.load(fin) self._token_embedding_file = token_embedding_file self.output_dim = self._options['lstm']['projection_dim'] self.requires_grad = requires_grad self._load_weights() """ # Cache the arrays for use in forward -- +1 due to masking. self._beginning_of_sentence_characters = self.xp.asarray( numpy.array(UnicodeCharsVocabulary.bos_chars) + 1 ) self._end_of_sentence_characters = self.xp.asarray( numpy.array(UnicodeCharsVocabulary.eos_chars) + 1 ) """ # Cache the arrays for use in forward -- +1 due to masking. self._beginning_of_sentence_token = token_batcher._lm_vocab.bos + 1 self._end_of_sentence_token = token_batcher._lm_vocab.eos + 1 def get_output_dim(self): return self.output_dim def forward(self, inputs): """ Compute context insensitive token embeddings for ELMo representations. Parameters ---------- inputs: ``torch.autograd.Variable`` Shape ``(batch_size, sequence_length)`` of token ids representing the current batch. Returns ------- Dict with keys: ``'token_embedding'``: ``torch.autograd.Variable`` Shape ``(batch_size, sequence_length + 2, embedding_dim)`` tensor with context insensitive token representations. ``'mask'``: ``torch.autograd.Variable`` Shape ``(batch_size, sequence_length + 2)`` long tensor with sequence mask. """ # Add BOS/EOS # mask = ((inputs > 0).sum(axis=-1) > 0) mask = (inputs > 0) token_ids_with_bos_eos, mask_with_bos_eos = add_sentence_boundary_token_ids( inputs, mask, self._beginning_of_sentence_token, self._end_of_sentence_token ) token_embedding = F.embed_id( token_ids_with_bos_eos, self._token_embedding_weights ) # (batch_size, sequence_length, embedding_dim) return { 'mask': mask_with_bos_eos, 'token_embedding': token_embedding } def _load_weights(self): self._load_token_embedding() def _load_token_embedding(self): with h5py.File(cached_path(self._token_embedding_file), 'r') as fin: token_embed_weights = fin['embedding'][...] weights = numpy.zeros( (token_embed_weights.shape[0] + 1, token_embed_weights.shape[1]), dtype=DTYPE) weights[1:, :] = token_embed_weights with self.init_scope(): self._token_embedding_weights = chainer.Parameter(weights) self._token_embedding_weights._requires_grad = self.requires_grad # TODO(sosk): add assert for batcher vocab and embedding class _ElmoCharacterEncoder(chainer.Chain): """ Compute context sensitive token representation using pretrained biLM. This embedder has input character ids of size (batch_size, sequence_length, 50) and returns (batch_size, sequence_length + 2, embedding_dim), where embedding_dim is specified in the options file (typically 512). We add special entries at the beginning and end of each sequence corresponding to <S> and </S>, the beginning and end of sentence tokens. Note: this is a lower level class useful for advanced usage. Most users should use ``ElmoTokenEmbedder`` or ``allennlp.modules.Elmo`` instead. Parameters ---------- options_file : ``str`` ELMo JSON options file weight_file : ``str`` ELMo hdf5 weight file requires_grad: ``bool``, optional If True, compute gradient of ELMo parameters for fine tuning. The relevant section of the options file is something like: .. example-code:: .. code-block:: python {'char_cnn': { 'activation': 'relu', 'embedding': {'dim': 4}, 'filters': [[1, 4], [2, 8], [3, 16], [4, 32], [5, 64]], 'max_characters_per_token': 50, 'n_characters': 262, 'n_highway': 2 } } """ def __init__(self, options_file, weight_file, requires_grad=False): super(_ElmoCharacterEncoder, self).__init__() with open(cached_path(options_file), 'r') as fin: self._options = json.load(fin) self._weight_file = weight_file self.output_dim = self._options['lstm']['projection_dim'] self.requires_grad = requires_grad self._load_weights() # Cache the arrays for use in forward -- +1 due to masking. self._beginning_of_sentence_characters = self.xp.asarray( numpy.array(UnicodeCharsVocabulary.bos_chars) + 1 ) self._end_of_sentence_characters = self.xp.asarray( numpy.array(UnicodeCharsVocabulary.eos_chars) + 1 ) def get_output_dim(self): return self.output_dim def forward(self, inputs): """ Compute context insensitive token embeddings for ELMo representations. Parameters ---------- inputs: ``torch.autograd.Variable`` Shape ``(batch_size, sequence_length, 50)`` of character ids representing the current batch. Returns ------- Dict with keys: ``'token_embedding'``: ``torch.autograd.Variable`` Shape ``(batch_size, sequence_length + 2, embedding_dim)`` tensor with context insensitive token representations. ``'mask'``: ``torch.autograd.Variable`` Shape ``(batch_size, sequence_length + 2)`` long tensor with sequence mask. """ # Add BOS/EOS mask = ((inputs > 0).sum(axis=-1) > 0) character_ids_with_bos_eos, mask_with_bos_eos = add_sentence_boundary_token_ids( inputs, mask, self._beginning_of_sentence_characters, self._end_of_sentence_characters ) # the character id embedding max_chars_per_token = self._options['char_cnn']['max_characters_per_token'] # (batch_size * sequence_length, max_chars_per_token, embed_dim) character_embedding = F.embed_id( character_ids_with_bos_eos.reshape((-1, max_chars_per_token)), self._char_embedding_weights ) # run convolutions cnn_options = self._options['char_cnn'] if cnn_options['activation'] == 'tanh': activation = F.tanh elif cnn_options['activation'] == 'relu': activation = F.relu else: raise ConfigurationError("Unknown activation") # (batch_size * sequence_length, embed_dim, max_chars_per_token) character_embedding = F.transpose(character_embedding, (0, 2, 1)) character_embedding = character_embedding[:, :, :, None] convs = [] for i in range(len(self._convolutions)): conv = getattr(self, 'char_conv_{}'.format(i)) convolved = conv(character_embedding) # (batch_size * sequence_length, n_filters for this width) convolved = F.max(convolved, axis=(2, 3)) convolved = activation(convolved) convs.append(convolved) # (batch_size * sequence_length, n_filters) token_embedding = F.concat(convs, axis=-1) # apply the highway layers (batch_size * sequence_length, n_filters) token_embedding = self._highways.forward(token_embedding) # final projection (batch_size * sequence_length, embedding_dim) token_embedding = self._projection(token_embedding) # reshape to (batch_size, sequence_length, embedding_dim) batch_size, sequence_length, _ = character_ids_with_bos_eos.shape return { 'mask': mask_with_bos_eos, 'token_embedding': token_embedding.reshape((batch_size, sequence_length, -1)) } def _load_weights(self): self._load_char_embedding() self._load_cnn_weights() self._load_highway() self._load_projection() def _load_char_embedding(self): with h5py.File(cached_path(self._weight_file), 'r') as fin: char_embed_weights = fin['char_embed'][...] weights = numpy.zeros( (char_embed_weights.shape[0] + 1, char_embed_weights.shape[1]), dtype='float32' ) weights[1:, :] = char_embed_weights with self.init_scope(): self._char_embedding_weights = chainer.Parameter(weights) self._char_embedding_weights._requires_grad = self.requires_grad def _load_cnn_weights(self): cnn_options = self._options['char_cnn'] filters = cnn_options['filters'] char_embed_dim = cnn_options['embedding']['dim'] convolutions = [] for i, (width, num) in enumerate(filters): conv = L.Convolution2D( in_channels=char_embed_dim, out_channels=num, ksize=(width, 1), nobias=False ) # load the weights with h5py.File(cached_path(self._weight_file), 'r') as fin: weight = fin['CNN']['W_cnn_{}'.format(i)][...] bias = fin['CNN']['b_cnn_{}'.format(i)][...] w_reshaped = numpy.transpose( weight.squeeze(axis=0), axes=(2, 1, 0)) # if w_reshaped.shape != tuple(conv.W.data.shape): # raise ValueError("Invalid weight file") w_reshaped = w_reshaped[:, :, :, None] conv.W.data[:] = w_reshaped conv.b.data[:] = bias conv.W._requires_grad = self.requires_grad conv.b._requires_grad = self.requires_grad convolutions.append(conv) with self.init_scope(): setattr(self, 'char_conv_{}'.format(i), conv) self._convolutions = convolutions def _load_highway(self): # pylint: disable=protected-access # the highway layers have same dimensionality as the number of cnn filters cnn_options = self._options['char_cnn'] filters = cnn_options['filters'] n_filters = sum(f[1] for f in filters) n_highway = cnn_options['n_highway'] # create the layers, and load the weights with self.init_scope(): self._highways = Highway(n_filters, n_highway, activation=F.relu) for k in range(n_highway): # The AllenNLP highway is one matrix multplication with concatenation of # transform and carry weights. with h5py.File(cached_path(self._weight_file), 'r') as fin: # The weights are transposed due to multiplication order assumptions in tf # vs pytorch (tf.matmul(X, W) vs pytorch.matmul(W, X)) w_transform = numpy.transpose( fin['CNN_high_{}'.format(k)]['W_transform'][...]) # -1.0 since AllenNLP is g * x + (1 - g) * f(x) but tf is (1 - g) * x + g * f(x) w_carry = -1.0 * \ numpy.transpose( fin['CNN_high_{}'.format(k)]['W_carry'][...]) weight = numpy.concatenate([w_transform, w_carry], axis=0) self._highways._layers[k].W.data[:] = weight self._highways._layers[k].W._requires_grad = self.requires_grad b_transform = fin['CNN_high_{}'.format(k)]['b_transform'][...] b_carry = -1.0 * fin['CNN_high_{}'.format(k)]['b_carry'][...] bias = numpy.concatenate([b_transform, b_carry], axis=0) self._highways._layers[k].b.data[:] = bias self._highways._layers[k].b._requires_grad = self.requires_grad def _load_projection(self): cnn_options = self._options['char_cnn'] filters = cnn_options['filters'] n_filters = sum(f[1] for f in filters) with self.init_scope(): self._projection = L.Linear( n_filters, self.output_dim, nobias=False) with h5py.File(cached_path(self._weight_file), 'r') as fin: weight = fin['CNN_proj']['W_proj'][...] bias = fin['CNN_proj']['b_proj'][...] self._projection.W.data[:] = numpy.transpose(weight) self._projection.b.data[:] = bias self._projection.W._requires_grad = self.requires_grad self._projection.b._requires_grad = self.requires_grad class _ElmoBiLm(chainer.Chain): """ Run a pre-trained bidirectional language model, outputing the activations at each layer for weighting together into an ELMo representation (with ``allennlp.modules.seq2seq_encoders.Elmo``). This is a lower level class, useful for advanced uses, but most users should use ``allennlp.modules.seq2seq_encoders.Elmo`` directly. Parameters ---------- options_file : ``str`` ELMo JSON options file weight_file : ``str`` ELMo hdf5 weight file requires_grad: ``bool``, optional If True, compute gradient of ELMo parameters for fine tuning. """ def __init__(self, options_file, weight_file, token_embedding_file=None, token_batcher=None, requires_grad=False): super(_ElmoBiLm, self).__init__() with open(cached_path(options_file), 'r') as fin: options = json.load(fin) if not options['lstm'].get('use_skip_connections'): raise ConfigurationError( 'We only support pretrained biLMs with residual connections') with self.init_scope(): if token_embedding_file: assert token_batcher is not None self._token_embedder = _ElmoTokenEmbedder( options_file, token_embedding_file, token_batcher) else: self._token_embedder = _ElmoCharacterEncoder( options_file, weight_file, requires_grad=requires_grad) self._elmo_lstm = ElmoLstm(input_size=options['lstm']['projection_dim'], hidden_size=options['lstm']['projection_dim'], cell_size=options['lstm']['dim'], num_layers=options['lstm']['n_layers'], memory_cell_clip_value=options['lstm']['cell_clip'], state_projection_clip_value=options['lstm']['proj_clip'], requires_grad=requires_grad) self._elmo_lstm.load_weights(weight_file) # Number of representation layers including context independent layer self.num_layers = options['lstm']['n_layers'] + 1 def get_output_dim(self): return 2 * self._token_embedder.get_output_dim() def forward(self, inputs): """ Parameters ---------- inputs: ``torch.autograd.Variable`` Shape ``(batch_size, timesteps, 50)`` of character ids representing the current batch. Returns ------- Dict with keys: ``'activations'``: ``List[torch.autograd.Variable]`` A list of activations at each layer of the network, each of shape ``(batch_size, timesteps + 2, embedding_dim)`` ``'mask'``: ``torch.autograd.Variable`` Shape ``(batch_size, timesteps + 2)`` long tensor with sequence mask. Note that the output tensors all include additional special begin and end of sequence markers. """ token_embedding = self._token_embedder.forward(inputs) type_representation = token_embedding['token_embedding'] mask = token_embedding['mask'] lstm_outputs = self._elmo_lstm.forward(type_representation, mask) # Prepare the output. The first layer is duplicated. output_tensors = [ F.concat([type_representation, type_representation], axis=-1) ] for layer_activations in F.split_axis(lstm_outputs, lstm_outputs.shape[0], axis=0): output_tensors.append(F.squeeze(layer_activations, 0)) return { 'activations': output_tensors, 'mask': mask, } def minibatch_iterator(iterable, batchsize): minibatch = [] _iterable = iter(iterable) while True: x = next(_iterable, None) if x is None: break minibatch.append(x) if len(minibatch) >= batchsize: yield minibatch minibatch = [] if minibatch: yield minibatch def dump_token_embeddings(vocab_file, options_file, weight_file, outfile, gpu=-1, batchsize=128): ''' Given an input vocabulary file, dump all the token embeddings to the outfile. The result can be used as the embedding_weight_file when constructing a BidirectionalLanguageModel. ''' with open(options_file, 'r') as fin: options = json.load(fin) max_word_length = options['char_cnn']['max_characters_per_token'] vocab = UnicodeCharsVocabulary(vocab_file, max_word_length) batcher = Batcher(vocab_file, max_word_length) model = Elmo( options_file, weight_file, num_output_representations=1, requires_grad=False, do_layer_norm=False, dropout=0.) tokens = [vocab.id_to_word(i) for i in range(vocab.size)] n_tokens = len(tokens) # (batch_size, timesteps, 50) if gpu >= 0: cuda.get_device_from_id(gpu).use() model.to_gpu() all_embeddings = [] with chainer.using_config("train", False), \ chainer.no_backprop_mode(): for minibatch in minibatch_iterator(tqdm.tqdm(tokens, total=n_tokens), batchsize): char_ids = batcher.batch_sentences([minibatch], add_bos_eos=False) char_ids = model.xp.asarray(char_ids) # to gpu embeddings = model._elmo_lstm._token_embedder\ .forward(char_ids)['token_embedding'] # (batch_size, sequence_length + 2, embedding_dim) embeddings = embeddings[:, 1:-1] # del bos and eos embeddings = embeddings[0] embeddings = cuda.to_cpu(embeddings.array) all_embeddings.append(embeddings) all_embeddings = numpy.concatenate(all_embeddings, axis=0) with h5py.File(outfile, 'w') as fout: ds = fout.create_dataset( 'embedding', all_embeddings.shape, dtype='float32', data=all_embeddings) def dump_bilm_embeddings(vocab_file, dataset_file, options_file, weight_file, outfile, gpu=-1, batchsize=32): with open(options_file, 'r') as fin: options = json.load(fin) max_word_length = options['char_cnn']['max_characters_per_token'] vocab = UnicodeCharsVocabulary(vocab_file, max_word_length) batcher = Batcher(vocab_file, max_word_length) model = Elmo( options_file, weight_file, num_output_representations=1, requires_grad=False, do_layer_norm=False, dropout=0.) if gpu >= 0: cuda.get_device_from_id(gpu).use() model.to_gpu() # (batch_size, timesteps, 50) # TODO(sosk): preencoding token embedding for acceleration with chainer.using_config("train", False), \ chainer.no_backprop_mode(): sentence_id = 0 n_lines = sum([1 for _ in open(dataset_file, 'r')]) with open(dataset_file, 'r') as fin, h5py.File(outfile, 'w') as fout: for minibatch in minibatch_iterator(tqdm.tqdm(fin, total=n_lines), batchsize): sentences = [line.strip().split() for line in minibatch] char_ids = batcher.batch_sentences( sentences, add_bos_eos=False) char_ids = model.xp.asarray(char_ids) mb_outs = model.forward(char_ids) mb_embedding_layers = mb_outs['elmo_layers'] # [(batch_size, max_sequence_length, embedding_dim), ..., x n_layers] # Note that embedding layers have already trushed bos & eos # But they contains padding mb_mask = mb_outs['mask'] mb_concat_embedding_layers = cuda.to_cpu( model.xp.stack([mb_emb.array for mb_emb in mb_embedding_layers], axis=1)) # (batch_size, n_layers=3, max_sequence_length, embedding_dim) for mask, concat_embedding_layers in zip(mb_mask, mb_concat_embedding_layers): # remove pads length = int(mask.sum()) concat_embedding_layers = concat_embedding_layers[:, :length] # (n_layers=3, sequence_length, embedding_dim) ds = fout.create_dataset( '{}'.format(sentence_id), concat_embedding_layers.shape, dtype='float32', data=concat_embedding_layers ) sentence_id += 1
StarcoderdataPython
1617542
from segmentation.data.dataset import get_segmentation_dataset from segmentation.data.augmentation import Augmentor, sequences from segmentation.data.preprocessing.mask_functions import ( convert_to_tensors_float, reduce_to_semantic_mask_add_xy, append_semantic_mask_add_xy, ) from segmentation.data.preprocessing.mask_functions import channel_first from segmentation.data.preprocessing.preprocessor import Preprocessor from segmentation.evaluation.pq_bf.panoptic_quality import single_channel_pq from segmentation.data.postprocessing.postprocessor import Postprocessor from segmentation.data.postprocessing.classification import sigmoid from segmentation.data.postprocessing.hover import xy_watershed from segmentation.models.hover.utils import hover_loss augmentor = Augmentor(sequence=sequences.seq, augment_target=False) preprocessor = Preprocessor( sequence=[reduce_to_semantic_mask_add_xy, channel_first, convert_to_tensors_float] ) test_preprocessor = Preprocessor( sequence=[append_semantic_mask_add_xy, channel_first, convert_to_tensors_float] ) postprocessor = Postprocessor(sequence=[sigmoid, xy_watershed]) dictionary = { "get_dataset_func": get_segmentation_dataset, "augmentation_func": augmentor.augmentation_func, "preprocessing_func": preprocessor.preprocessing_func, "test_preprocessing_func": test_preprocessor.preprocessing_func, "loss": hover_loss, "postprocessing_func": postprocessor.postprocessing_func, "metric": single_channel_pq, }
StarcoderdataPython
3327597
<reponame>Steve-YJ/sagemaker-studio-end-to-end from pyspark.sql.session import SparkSession from pyspark.sql.dataframe import DataFrame # You may want to configure the Spark Context with the right credentials provider. spark = SparkSession.builder.master('local').getOrCreate() mode = None def capture_stdout(func, *args, **kwargs): """Capture standard output to a string buffer""" from contextlib import redirect_stdout import io stdout_string = io.StringIO() with redirect_stdout(stdout_string): func(*args, **kwargs) return stdout_string.getvalue() def convert_or_coerce(pandas_df, spark): """Convert pandas df to pyspark df and coerces the mixed cols to string""" import re try: return spark.createDataFrame(pandas_df) except TypeError as e: match = re.search(r".*field (\w+).*Can not merge type.*", str(e)) if match is None: raise e mixed_col_name = match.group(1) # Coercing the col to string pandas_df[mixed_col_name] = pandas_df[mixed_col_name].astype("str") return pandas_df def default_spark(value): return {"default": value} def default_spark_with_stdout(df, stdout): return { "default": df, "stdout": stdout, } def default_spark_with_trained_parameters(value, trained_parameters): return {"default": value, "trained_parameters": trained_parameters} def default_spark_with_trained_parameters_and_state(df, trained_parameters, state): return {"default": df, "trained_parameters": trained_parameters, "state": state} def dispatch(key_name, args, kwargs, funcs): """ Dispatches to another operator based on a key in the passed parameters. This also slices out any parameters using the parameter_name passed in, and will reassemble the trained_parameters correctly after invocation. Args: key_name: name of the key in kwargs used to identify the function to use. args: dataframe that will be passed as the first set of parameters to the function. kwargs: keyword arguments that key_name will be found in; also where args will be passed to parameters. These are also expected to include trained_parameters if there are any. funcs: dictionary mapping from value of key_name to (function, parameter_name) """ if key_name not in kwargs: raise OperatorCustomerError(f"Missing required parameter {key_name}") operator = kwargs[key_name] if operator not in funcs: raise OperatorCustomerError(f"Invalid choice selected for {key_name}. {operator} is not supported.") func, parameter_name = funcs[operator] # Extract out the parameters that should be available. func_params = kwargs.get(parameter_name, {}) if func_params is None: func_params = {} # Extract out any trained parameters. specific_trained_parameters = None if "trained_parameters" in kwargs: trained_parameters = kwargs["trained_parameters"] if trained_parameters is not None and parameter_name in trained_parameters: specific_trained_parameters = trained_parameters[parameter_name] func_params["trained_parameters"] = specific_trained_parameters # Execute the function (should return a dict). result = func(*args, **func_params) # Check if the result contains any trained parameters and remap them to the proper structure. if result is not None and "trained_parameters" in result: existing_trained_parameters = kwargs.get("trained_parameters") updated_trained_parameters = result["trained_parameters"] if existing_trained_parameters is not None or updated_trained_parameters is not None: existing_trained_parameters = existing_trained_parameters if existing_trained_parameters is not None else {} existing_trained_parameters[parameter_name] = result["trained_parameters"] # Update the result trained_parameters so they are part of the original structure. result["trained_parameters"] = existing_trained_parameters else: # If the given trained parameters were None and the returned trained parameters were None, don't return anything. del result["trained_parameters"] return result def get_dataframe_with_sequence_ids(df: DataFrame): df_cols = df.columns rdd_with_seq = df.rdd.zipWithIndex() df_with_seq = rdd_with_seq.toDF() df_with_seq = df_with_seq.withColumnRenamed("_2", "_seq_id_") for col_name in df_cols: df_with_seq = df_with_seq.withColumn(col_name, df_with_seq["_1"].getItem(col_name)) df_with_seq = df_with_seq.drop("_1") return df_with_seq def get_execution_state(status: str, message=None): return {"status": status, "message": message} class OperatorCustomerError(Exception): """Error type for Customer Errors in Spark Operators""" def encode_categorical_ordinal_encode( df, input_column=None, output_column=None, invalid_handling_strategy=None, trained_parameters=None ): INVALID_HANDLING_STRATEGY_SKIP = "Skip" INVALID_HANDLING_STRATEGY_ERROR = "Error" INVALID_HANDLING_STRATEGY_KEEP = "Keep" INVALID_HANDLING_STRATEGY_REPLACE_WITH_NAN = "Replace with NaN" from pyspark.ml.feature import StringIndexer, StringIndexerModel from pyspark.sql.functions import when expects_column(df, input_column, "Input column") invalid_handling_map = { INVALID_HANDLING_STRATEGY_SKIP: "skip", INVALID_HANDLING_STRATEGY_ERROR: "error", INVALID_HANDLING_STRATEGY_KEEP: "keep", INVALID_HANDLING_STRATEGY_REPLACE_WITH_NAN: "keep", } output_column, output_is_temp = get_temp_col_if_not_set(df, output_column) # process inputs handle_invalid = ( invalid_handling_strategy if invalid_handling_strategy in invalid_handling_map else INVALID_HANDLING_STRATEGY_ERROR ) trained_parameters = load_trained_parameters( trained_parameters, {"invalid_handling_strategy": invalid_handling_strategy} ) input_handle_invalid = invalid_handling_map.get(handle_invalid) index_model, index_model_loaded = load_pyspark_model_from_trained_parameters( trained_parameters, StringIndexerModel, "string_indexer_model" ) if index_model is None: indexer = StringIndexer(inputCol=input_column, outputCol=output_column, handleInvalid=input_handle_invalid) # fit the model and transform try: index_model = fit_and_save_model(trained_parameters, "string_indexer_model", indexer, df) except Exception as e: if input_handle_invalid == "error": raise OperatorSparkOperatorCustomerError( f"Encountered error calculating string indexes. Halting because error handling is set to 'Error'. Please check your data and try again: {e}" ) else: raise e output_df = transform_using_trained_model(index_model, df, index_model_loaded) # finally, if missing should be nan, convert them if handle_invalid == INVALID_HANDLING_STRATEGY_REPLACE_WITH_NAN: new_val = float("nan") # convert all numLabels indices to new_val num_labels = len(index_model.labels) output_df = output_df.withColumn( output_column, when(output_df[output_column] == num_labels, new_val).otherwise(output_df[output_column]) ) # finally handle the output column name appropriately. output_df = replace_input_if_output_is_temp(output_df, input_column, output_column, output_is_temp) return default_spark_with_trained_parameters(output_df, trained_parameters) def encode_categorical_one_hot_encode( df, input_column=None, input_already_ordinal_encoded=None, invalid_handling_strategy=None, drop_last=None, output_style=None, output_column=None, trained_parameters=None, ): INVALID_HANDLING_STRATEGY_SKIP = "Skip" INVALID_HANDLING_STRATEGY_ERROR = "Error" INVALID_HANDLING_STRATEGY_KEEP = "Keep" OUTPUT_STYLE_VECTOR = "Vector" OUTPUT_STYLE_COLUMNS = "Columns" invalid_handling_map = { INVALID_HANDLING_STRATEGY_SKIP: "skip", INVALID_HANDLING_STRATEGY_ERROR: "error", INVALID_HANDLING_STRATEGY_KEEP: "keep", } handle_invalid = invalid_handling_map.get(invalid_handling_strategy, "error") expects_column(df, input_column, "Input column") output_format = output_style if output_style in [OUTPUT_STYLE_VECTOR, OUTPUT_STYLE_COLUMNS] else OUTPUT_STYLE_VECTOR drop_last = parse_parameter(bool, drop_last, "Drop Last", True) input_ordinal_encoded = parse_parameter(bool, input_already_ordinal_encoded, "Input already ordinal encoded", False) output_column = output_column if output_column else input_column trained_parameters = load_trained_parameters( trained_parameters, {"invalid_handling_strategy": invalid_handling_strategy, "drop_last": drop_last} ) from pyspark.ml.feature import ( StringIndexer, StringIndexerModel, OneHotEncoder, OneHotEncoderModel, ) from pyspark.ml.functions import vector_to_array import pyspark.sql.functions as sf from pyspark.sql.types import DoubleType # first step, ordinal encoding. Not required if input_ordinal_encoded==True # get temp name for ordinal encoding ordinal_name = temp_col_name(df, output_column) if input_ordinal_encoded: df_ordinal = df.withColumn(ordinal_name, df[input_column].cast("int")) labels = None else: index_model, index_model_loaded = load_pyspark_model_from_trained_parameters( trained_parameters, StringIndexerModel, "string_indexer_model" ) if index_model is None: # apply ordinal encoding indexer = StringIndexer(inputCol=input_column, outputCol=ordinal_name, handleInvalid=handle_invalid) try: index_model = fit_and_save_model(trained_parameters, "string_indexer_model", indexer, df) except Exception as e: if handle_invalid == "error": raise OperatorSparkOperatorCustomerError( f"Encountered error calculating string indexes. Halting because error handling is set to 'Error'. Please check your data and try again: {e}" ) else: raise e try: df_ordinal = transform_using_trained_model(index_model, df, index_model_loaded) except Exception as e: if handle_invalid == "error": raise OperatorSparkOperatorCustomerError( f"Encountered error transforming string indexes. Halting because error handling is set to 'Error'. Please check your data and try again: {e}" ) else: raise e labels = index_model.labels # drop the input column if required from the ordinal encoded dataset if output_column == input_column: df_ordinal = df_ordinal.drop(input_column) temp_output_col = temp_col_name(df_ordinal, output_column) # apply onehot encoding on the ordinal cur_handle_invalid = handle_invalid if input_ordinal_encoded else "error" cur_handle_invalid = "keep" if cur_handle_invalid == "skip" else cur_handle_invalid ohe_model, ohe_model_loaded = load_pyspark_model_from_trained_parameters( trained_parameters, OneHotEncoderModel, "one_hot_encoder_model" ) if ohe_model is None: ohe = OneHotEncoder( dropLast=drop_last, handleInvalid=cur_handle_invalid, inputCol=ordinal_name, outputCol=temp_output_col ) try: ohe_model = fit_and_save_model(trained_parameters, "one_hot_encoder_model", ohe, df_ordinal) except Exception as e: if handle_invalid == "error": raise OperatorSparkOperatorCustomerError( f"Encountered error calculating encoding categories. Halting because error handling is set to 'Error'. Please check your data and try again: {e}" ) else: raise e output_df = transform_using_trained_model(ohe_model, df_ordinal, ohe_model_loaded) if output_format == OUTPUT_STYLE_COLUMNS: if labels is None: labels = list(range(ohe_model.categorySizes[0])) current_output_cols = set(list(output_df.columns)) old_cols = [sf.col(name) for name in df.columns if name in current_output_cols] arr_col = vector_to_array(output_df[temp_output_col]) new_cols = [(arr_col[i]).alias(f"{output_column}_{name}") for i, name in enumerate(labels)] output_df = output_df.select(*(old_cols + new_cols)) else: # remove the temporary ordinal encoding output_df = output_df.drop(ordinal_name) output_df = output_df.withColumn(output_column, sf.col(temp_output_col)) output_df = output_df.drop(temp_output_col) final_ordering = [col for col in df.columns] if output_column not in final_ordering: final_ordering.append(output_column) output_df = output_df.select(final_ordering) return default_spark_with_trained_parameters(output_df, trained_parameters) import re from pyspark.sql import functions as sf, types def format_string_lower_case(df, input_column=None, output_column=None, trained_parameters=None): expects_column(df, input_column, "Input column") return default_spark( df.withColumn( output_column if output_column else input_column, sf.lower(df[input_column].cast(types.StringType())) ) ) def format_string_upper_case(df, input_column=None, output_column=None, trained_parameters=None): expects_column(df, input_column, "Input column") return default_spark( df.withColumn( output_column if output_column else input_column, sf.upper(df[input_column].cast(types.StringType())) ) ) def format_string_title_case(df, input_column=None, output_column=None, trained_parameters=None): expects_column(df, input_column, "Input column") return default_spark( df.withColumn( output_column if output_column else input_column, sf.pandas_udf(lambda s: s.str.title(), returnType=types.StringType())( df[input_column].cast(types.StringType()) ), ) ) def format_string_capitalize(df, input_column=None, output_column=None, trained_parameters=None): expects_column(df, input_column, "Input column") return default_spark( df.withColumn( output_column if output_column else input_column, sf.pandas_udf(lambda s: s.str.capitalize(), returnType=types.StringType())( df[input_column].cast(types.StringType()) ), ) ) def format_string_swap_case(df, input_column=None, output_column=None, trained_parameters=None): expects_column(df, input_column, "Input column") return default_spark( df.withColumn( output_column if output_column else input_column, sf.pandas_udf(lambda s: s.str.swapcase(), returnType=types.StringType())( df[input_column].cast(types.StringType()) ), ) ) def format_string_left_pad( df, input_column=None, width=None, fill_character=None, output_column=None, trained_parameters=None ): expects_column(df, input_column, "Input column") width = parse_parameter(int, width, "Width") fill_character = parse_parameter(str, fill_character, "Fill character", " ") MAX_WIDTH = 1000 if width > MAX_WIDTH: raise OperatorSparkOperatorCustomerError(f"Width must be less than {MAX_WIDTH}. Received: {width}") if len(fill_character) > 1: raise OperatorSparkOperatorCustomerError(f"Fill character can only be a single character. Received: {fill_character}") return default_spark( df.withColumn( output_column if output_column else input_column, sf.lpad(df[input_column].cast(types.StringType()), len=width, pad=fill_character), ) ) def format_string_right_pad( df, input_column=None, width=None, fill_character=None, output_column=None, trained_parameters=None ): expects_column(df, input_column, "Input column") width = parse_parameter(int, width, "Width") fill_character = parse_parameter(str, fill_character, "Fill character", " ") MAX_WIDTH = 1000 if width > MAX_WIDTH: raise OperatorSparkOperatorCustomerError(f"Width must be less than {MAX_WIDTH}. Received: {width}") if len(fill_character) > 1: raise OperatorSparkOperatorCustomerError(f"Fill character can only be a single character. Received: {fill_character}") return default_spark( df.withColumn( output_column if output_column else input_column, sf.rpad(df[input_column].cast(types.StringType()), len=width, pad=fill_character), ) ) def format_string_center_pad_on_either_side( df, input_column=None, width=None, fill_character=None, output_column=None, trained_parameters=None ): expects_column(df, input_column, "Input column") width = parse_parameter(int, width, "Width") fill_character = parse_parameter(str, fill_character, "Fill character", " ") MAX_WIDTH = 1000 if width > MAX_WIDTH: raise OperatorSparkOperatorCustomerError(f"Width must be less than {MAX_WIDTH}. Received: {width}") if len(fill_character) > 1: raise OperatorSparkOperatorCustomerError(f"Fill character can only be a single character. Received: {fill_character}") return default_spark( df.withColumn( output_column if output_column else input_column, sf.pandas_udf(lambda s: s.str.center(width=width, fillchar=fill_character), returnType=types.StringType())( df[input_column].cast(types.StringType()) ), ) ) def format_string_strip_characters_from_left( df, input_column=None, characters_to_remove=None, output_column=None, trained_parameters=None ): expects_column(df, input_column, "Input column") return default_spark( df.withColumn( output_column if output_column else input_column, sf.pandas_udf(lambda s: s.str.lstrip(to_strip=characters_to_remove), returnType=types.StringType())( df[input_column].cast(types.StringType()) ), ) ) def format_string_strip_characters_from_right( df, input_column=None, characters_to_remove=None, output_column=None, trained_parameters=None ): expects_column(df, input_column, "Input column") return default_spark( df.withColumn( output_column if output_column else input_column, sf.pandas_udf(lambda s: s.str.rstrip(to_strip=characters_to_remove), returnType=types.StringType())( df[input_column].cast(types.StringType()) ), ) ) def format_string_strip_left_and_right( df, input_column=None, characters_to_remove=None, output_column=None, trained_parameters=None ): expects_column(df, input_column, "Input column") return default_spark( df.withColumn( output_column if output_column else input_column, sf.pandas_udf(lambda s: s.str.strip(to_strip=characters_to_remove), returnType=types.StringType())( df[input_column].cast(types.StringType()) ), ) ) def format_string_prepend_zeros(df, input_column=None, width=None, output_column=None, trained_parameters=None): expects_column(df, input_column, "Input column") width = parse_parameter(int, width, "Width") MAX_WIDTH = 1000 if width > MAX_WIDTH: raise OperatorSparkOperatorCustomerError(f"Width must be less than {MAX_WIDTH}. Received: {width}") return default_spark( df.withColumn( output_column if output_column else input_column, sf.lpad(df[input_column].cast(types.StringType()), len=width, pad="0"), ) ) def format_string_add_prefix(df, input_column=None, prefix=None, output_column=None, trained_parameters=None): expects_column(df, input_column, "Input column") return default_spark( df.withColumn( output_column if output_column else input_column, sf.concat(sf.lit(prefix), df[input_column].cast(types.StringType())), ) ) def format_string_add_suffix(df, input_column=None, suffix=None, output_column=None, trained_parameters=None): expects_column(df, input_column, "Input column") return default_spark( df.withColumn( output_column if output_column else input_column, sf.concat(df[input_column].cast(types.StringType()), sf.lit(suffix)), ) ) def format_string_remove_symbols(df, input_column=None, symbols=None, output_column=None, trained_parameters=None): expects_column(df, input_column, "Input column") symbols = "!@#$%^&*()_+=-/\\`~{}|<>?" if not symbols else symbols regex = "|".join([re.escape(symbol) for symbol in symbols]) return default_spark( df.withColumn( output_column if output_column else input_column, sf.regexp_replace(df[input_column].cast(types.StringType()), f"({regex})", ""), ) ) from enum import Enum from pyspark.sql.types import BooleanType, DateType, DoubleType, LongType, StringType from pyspark.sql import functions as f class NonCastableDataHandlingMethod(Enum): REPLACE_WITH_NULL = "replace_null" REPLACE_WITH_NULL_AND_PUT_NON_CASTABLE_DATA_IN_NEW_COLUMN = "replace_null_with_new_col" REPLACE_WITH_FIXED_VALUE = "replace_value" REPLACE_WITH_FIXED_VALUE_AND_PUT_NON_CASTABLE_DATA_IN_NEW_COLUMN = "replace_value_with_new_col" DROP_NON_CASTABLE_ROW = "drop" @staticmethod def get_names(): return [item.name for item in NonCastableDataHandlingMethod] @staticmethod def get_values(): return [item.value for item in NonCastableDataHandlingMethod] class MohaveDataType(Enum): BOOL = "bool" DATE = "date" FLOAT = "float" LONG = "long" STRING = "string" OBJECT = "object" @staticmethod def get_names(): return [item.name for item in MohaveDataType] @staticmethod def get_values(): return [item.value for item in MohaveDataType] PYTHON_TYPE_MAPPING = { MohaveDataType.BOOL: bool, MohaveDataType.DATE: str, MohaveDataType.FLOAT: float, MohaveDataType.LONG: int, MohaveDataType.STRING: str, } MOHAVE_TO_SPARK_TYPE_MAPPING = { MohaveDataType.BOOL: BooleanType, MohaveDataType.DATE: DateType, MohaveDataType.FLOAT: DoubleType, MohaveDataType.LONG: LongType, MohaveDataType.STRING: StringType, } SPARK_TYPE_MAPPING_TO_SQL_TYPE = { BooleanType: "BOOLEAN", LongType: "BIGINT", DoubleType: "DOUBLE", StringType: "STRING", DateType: "DATE", } SPARK_TO_MOHAVE_TYPE_MAPPING = {value: key for (key, value) in MOHAVE_TO_SPARK_TYPE_MAPPING.items()} def cast_single_column_type_helper(df, column_name_to_cast, column_name_to_add, mohave_data_type, date_formatting): if mohave_data_type == MohaveDataType.DATE: df = df.withColumn(column_name_to_add, f.to_date(df[column_name_to_cast], date_formatting)) else: df = df.withColumn( column_name_to_add, df[column_name_to_cast].cast(MOHAVE_TO_SPARK_TYPE_MAPPING[mohave_data_type]()) ) return df def cast_single_column_type( df, column, mohave_data_type, invalid_data_handling_method, replace_value=None, date_formatting="dd-MM-yyyy" ): """Cast single column to a new type Args: df (DataFrame): spark dataframe column (Column): target column for type casting mohave_data_type (Enum): Enum MohaveDataType invalid_data_handling_method (Enum): Enum NonCastableDataHandlingMethod replace_value (str): value to replace for invalid data when "replace_value" is specified date_formatting (str): format for date. Default format is "dd-MM-yyyy" Returns: df (DataFrame): casted spark dataframe """ cast_to_date = f.to_date(df[column], date_formatting) cast_to_non_date = df[column].cast(MOHAVE_TO_SPARK_TYPE_MAPPING[mohave_data_type]()) non_castable_column = f"{column}_typecast_error" temp_column = "temp_column" if invalid_data_handling_method == NonCastableDataHandlingMethod.REPLACE_WITH_NULL: # Replace non-castable data to None in the same column. pyspark's default behaviour # Original dataframe # +---+------+ # | id | txt | # +---+---+--+ # | 1 | foo | # | 2 | bar | # | 3 | 1 | # +---+------+ # cast txt column to long # +---+------+ # | id | txt | # +---+------+ # | 1 | None | # | 2 | None | # | 3 | 1 | # +---+------+ return df.withColumn(column, cast_to_date if (mohave_data_type == MohaveDataType.DATE) else cast_to_non_date) if invalid_data_handling_method == NonCastableDataHandlingMethod.DROP_NON_CASTABLE_ROW: # Drop non-castable row # Original dataframe # +---+------+ # | id | txt | # +---+---+--+ # | 1 | foo | # | 2 | bar | # | 3 | 1 | # +---+------+ # cast txt column to long, _ non-castable row # +---+----+ # | id|txt | # +---+----+ # | 3| 1 | # +---+----+ df = df.withColumn(column, cast_to_date if (mohave_data_type == MohaveDataType.DATE) else cast_to_non_date) return df.where(df[column].isNotNull()) if ( invalid_data_handling_method == NonCastableDataHandlingMethod.REPLACE_WITH_NULL_AND_PUT_NON_CASTABLE_DATA_IN_NEW_COLUMN ): # Replace non-castable data to None in the same column and put non-castable data to a new column # Original dataframe # +---+------+ # | id | txt | # +---+------+ # | 1 | foo | # | 2 | bar | # | 3 | 1 | # +---+------+ # cast txt column to long # +---+----+------------------+ # | id|txt |txt_typecast_error| # +---+----+------------------+ # | 1|None| foo | # | 2|None| bar | # | 3| 1 | | # +---+----+------------------+ df = df.withColumn(temp_column, cast_to_date if (mohave_data_type == MohaveDataType.DATE) else cast_to_non_date) df = df.withColumn(non_castable_column, f.when(df[temp_column].isNotNull(), "").otherwise(df[column]),) elif invalid_data_handling_method == NonCastableDataHandlingMethod.REPLACE_WITH_FIXED_VALUE: # Replace non-castable data to a value in the same column # Original dataframe # +---+------+ # | id | txt | # +---+------+ # | 1 | foo | # | 2 | bar | # | 3 | 1 | # +---+------+ # cast txt column to long, replace non-castable value to 0 # +---+-----+ # | id| txt | # +---+-----+ # | 1| 0 | # | 2| 0 | # | 3| 1 | # +---+----+ value = _validate_and_cast_value(value=replace_value, mohave_data_type=mohave_data_type) df = df.withColumn(temp_column, cast_to_date if (mohave_data_type == MohaveDataType.DATE) else cast_to_non_date) replace_date_value = f.when(df[temp_column].isNotNull(), df[temp_column]).otherwise( f.to_date(f.lit(value), date_formatting) ) replace_non_date_value = f.when(df[temp_column].isNotNull(), df[temp_column]).otherwise(value) df = df.withColumn( temp_column, replace_date_value if (mohave_data_type == MohaveDataType.DATE) else replace_non_date_value ) elif ( invalid_data_handling_method == NonCastableDataHandlingMethod.REPLACE_WITH_FIXED_VALUE_AND_PUT_NON_CASTABLE_DATA_IN_NEW_COLUMN ): # Replace non-castable data to a value in the same column and put non-castable data to a new column # Original dataframe # +---+------+ # | id | txt | # +---+---+--+ # | 1 | foo | # | 2 | bar | # | 3 | 1 | # +---+------+ # cast txt column to long, replace non-castable value to 0 # +---+----+------------------+ # | id|txt |txt_typecast_error| # +---+----+------------------+ # | 1| 0 | foo | # | 2| 0 | bar | # | 3| 1 | | # +---+----+------------------+ value = _validate_and_cast_value(value=replace_value, mohave_data_type=mohave_data_type) df = df.withColumn(temp_column, cast_to_date if (mohave_data_type == MohaveDataType.DATE) else cast_to_non_date) df = df.withColumn(non_castable_column, f.when(df[temp_column].isNotNull(), "").otherwise(df[column]),) replace_date_value = f.when(df[temp_column].isNotNull(), df[temp_column]).otherwise( f.to_date(f.lit(value), date_formatting) ) replace_non_date_value = f.when(df[temp_column].isNotNull(), df[temp_column]).otherwise(value) df = df.withColumn( temp_column, replace_date_value if (mohave_data_type == MohaveDataType.DATE) else replace_non_date_value ) # drop temporary column df = df.withColumn(column, df[temp_column]).drop(temp_column) df_cols = df.columns if non_castable_column in df_cols: # Arrange columns so that non_castable_column col is next to casted column df_cols.remove(non_castable_column) column_index = df_cols.index(column) arranged_cols = df_cols[: column_index + 1] + [non_castable_column] + df_cols[column_index + 1 :] df = df.select(*arranged_cols) return df def _validate_and_cast_value(value, mohave_data_type): if value is None: return value try: return PYTHON_TYPE_MAPPING[mohave_data_type](value) except ValueError as e: raise ValueError( f"Invalid value to replace non-castable data. " f"{mohave_data_type} is not in mohave supported date type: {MohaveDataType.get_values()}. " f"Please use a supported type", e, ) import os import collections import tempfile import zipfile import base64 import logging from io import BytesIO import numpy as np class OperatorSparkOperatorCustomerError(Exception): """Error type for Customer Errors in Spark Operators""" def temp_col_name(df, *illegal_names): """Generates a temporary column name that is unused. """ name = "temp_col" idx = 0 name_set = set(list(df.columns) + list(illegal_names)) while name in name_set: name = f"_temp_col_{idx}" idx += 1 return name def get_temp_col_if_not_set(df, col_name): """Extracts the column name from the parameters if it exists, otherwise generates a temporary column name. """ if col_name: return col_name, False else: return temp_col_name(df), True def replace_input_if_output_is_temp(df, input_column, output_column, output_is_temp): """Replaces the input column in the dataframe if the output was not set This is used with get_temp_col_if_not_set to enable the behavior where a transformer will replace its input column if an output is not specified. """ if output_is_temp: df = df.withColumn(input_column, df[output_column]) df = df.drop(output_column) return df else: return df def parse_parameter(typ, value, key, default=None, nullable=False): if value is None: if default is not None or nullable: return default else: raise OperatorSparkOperatorCustomerError(f"Missing required input: '{key}'") else: try: value = typ(value) if isinstance(value, (int, float, complex)) and not isinstance(value, bool): if np.isnan(value) or np.isinf(value): raise OperatorSparkOperatorCustomerError( f"Invalid value provided for '{key}'. Expected {typ.__name__} but received: {value}" ) else: return value else: return value except (ValueError, TypeError): raise OperatorSparkOperatorCustomerError( f"Invalid value provided for '{key}'. Expected {typ.__name__} but received: {value}" ) except OverflowError: raise OperatorSparkOperatorCustomerError( f"Overflow Error: Invalid value provided for '{key}'. Given value '{value}' exceeds the range of type " f"'{typ.__name__}' for this input. Insert a valid value for type '{typ.__name__}' and try your request " f"again." ) def expects_valid_column_name(value, key, nullable=False): if nullable and value is None: return if value is None or len(str(value).strip()) == 0: raise OperatorSparkOperatorCustomerError(f"Column name cannot be null, empty, or whitespace for parameter '{key}': {value}") def expects_parameter(value, key, condition=None): if value is None: raise OperatorSparkOperatorCustomerError(f"Missing required input: '{key}'") elif condition is not None and not condition: raise OperatorSparkOperatorCustomerError(f"Invalid value provided for '{key}': {value}") def expects_column(df, value, key): if not value or value not in df.columns: raise OperatorSparkOperatorCustomerError(f"Expected column in dataframe for '{key}' however received '{value}'") def expects_parameter_value_in_list(key, value, items): if value not in items: raise OperatorSparkOperatorCustomerError(f"Illegal parameter value. {key} expected to be in {items}, but given {value}") def encode_pyspark_model(model): with tempfile.TemporaryDirectory() as dirpath: dirpath = os.path.join(dirpath, "model") # Save the model model.save(dirpath) # Create the temporary zip-file. mem_zip = BytesIO() with zipfile.ZipFile(mem_zip, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf: # Zip the directory. for root, dirs, files in os.walk(dirpath): for file in files: rel_dir = os.path.relpath(root, dirpath) zf.write(os.path.join(root, file), os.path.join(rel_dir, file)) zipped = mem_zip.getvalue() encoded = base64.b85encode(zipped) return str(encoded, "utf-8") def decode_pyspark_model(model_factory, encoded): with tempfile.TemporaryDirectory() as dirpath: zip_bytes = base64.b85decode(encoded) mem_zip = BytesIO(zip_bytes) mem_zip.seek(0) with zipfile.ZipFile(mem_zip, "r") as zf: zf.extractall(dirpath) model = model_factory.load(dirpath) return model def hash_parameters(value): # pylint: disable=W0702 try: if isinstance(value, collections.Hashable): return hash(value) if isinstance(value, dict): return hash(frozenset([hash((hash_parameters(k), hash_parameters(v))) for k, v in value.items()])) if isinstance(value, list): return hash(frozenset([hash_parameters(v) for v in value])) raise RuntimeError("Object not supported for serialization") except: # noqa: E722 raise RuntimeError("Object not supported for serialization") def load_trained_parameters(trained_parameters, operator_parameters): trained_parameters = trained_parameters if trained_parameters else {} parameters_hash = hash_parameters(operator_parameters) stored_hash = trained_parameters.get("_hash") if stored_hash != parameters_hash: trained_parameters = {"_hash": parameters_hash} return trained_parameters def load_pyspark_model_from_trained_parameters(trained_parameters, model_factory, name): if trained_parameters is None or name not in trained_parameters: return None, False try: model = decode_pyspark_model(model_factory, trained_parameters[name]) return model, True except Exception as e: logging.error(f"Could not decode PySpark model {name} from trained_parameters: {e}") del trained_parameters[name] return None, False def fit_and_save_model(trained_parameters, name, algorithm, df): model = algorithm.fit(df) trained_parameters[name] = encode_pyspark_model(model) return model def transform_using_trained_model(model, df, loaded): try: return model.transform(df) except Exception as e: if loaded: raise OperatorSparkOperatorCustomerError( f"Encountered error while using stored model. Please delete the operator and try again. {e}" ) else: raise e import re from datetime import date import numpy as np import pandas as pd from pyspark.sql.types import ( BooleanType, IntegralType, FractionalType, StringType, ) def type_inference(df): # noqa: C901 # pylint: disable=R0912 """Core type inference logic Args: df: spark dataframe Returns: dict a schema that maps from column name to mohave datatype """ columns_to_infer = [col for (col, col_type) in df.dtypes if col_type == "string"] pandas_df = df.toPandas() report = {} for (columnName, _) in pandas_df.iteritems(): if columnName in columns_to_infer: column = pandas_df[columnName].values report[columnName] = { "sum_string": len(column), "sum_numeric": sum_is_numeric(column), "sum_integer": sum_is_integer(column), "sum_boolean": sum_is_boolean(column), "sum_date": sum_is_date(column), "sum_null_like": sum_is_null_like(column), "sum_null": sum_is_null(column), } # Analyze numeric_threshold = 0.8 integer_threshold = 0.8 date_threshold = 0.8 bool_threshold = 0.8 column_types = {} for col, insights in report.items(): # Convert all columns to floats to make thresholds easy to calculate. proposed = MohaveDataType.STRING.value if (insights["sum_numeric"] / insights["sum_string"]) > numeric_threshold: proposed = MohaveDataType.FLOAT.value if (insights["sum_integer"] / insights["sum_numeric"]) > integer_threshold: proposed = MohaveDataType.LONG.value elif (insights["sum_boolean"] / insights["sum_string"]) > bool_threshold: proposed = MohaveDataType.BOOL.value elif (insights["sum_date"] / insights["sum_string"]) > date_threshold: proposed = MohaveDataType.DATE.value column_types[col] = proposed for f in df.schema.fields: if f.name not in columns_to_infer: if isinstance(f.dataType, IntegralType): column_types[f.name] = MohaveDataType.LONG.value elif isinstance(f.dataType, FractionalType): column_types[f.name] = MohaveDataType.FLOAT.value elif isinstance(f.dataType, StringType): column_types[f.name] = MohaveDataType.STRING.value elif isinstance(f.dataType, BooleanType): column_types[f.name] = MohaveDataType.BOOL.value else: # unsupported types in mohave column_types[f.name] = MohaveDataType.OBJECT.value return column_types def _is_numeric_single(x): try: x_float = float(x) return np.isfinite(x_float) except ValueError: return False except TypeError: # if x = None return False def sum_is_numeric(x): """count number of numeric element Args: x: numpy array Returns: int """ castables = np.vectorize(_is_numeric_single)(x) return np.count_nonzero(castables) def _is_integer_single(x): try: if not _is_numeric_single(x): return False return float(x) == int(x) except ValueError: return False except TypeError: # if x = None return False def sum_is_integer(x): castables = np.vectorize(_is_integer_single)(x) return np.count_nonzero(castables) def _is_boolean_single(x): boolean_list = ["true", "false"] try: is_boolean = x.lower() in boolean_list return is_boolean except ValueError: return False except TypeError: # if x = None return False except AttributeError: return False def sum_is_boolean(x): castables = np.vectorize(_is_boolean_single)(x) return np.count_nonzero(castables) def sum_is_null_like(x): # noqa: C901 def _is_empty_single(x): try: return bool(len(x) == 0) except TypeError: return False def _is_null_like_single(x): try: return bool(null_like_regex.match(x)) except TypeError: return False def _is_whitespace_like_single(x): try: return bool(whitespace_regex.match(x)) except TypeError: return False null_like_regex = re.compile(r"(?i)(null|none|nil|na|nan)") # (?i) = case insensitive whitespace_regex = re.compile(r"^\s+$") # only whitespace empty_checker = np.vectorize(_is_empty_single)(x) num_is_null_like = np.count_nonzero(empty_checker) null_like_checker = np.vectorize(_is_null_like_single)(x) num_is_null_like += np.count_nonzero(null_like_checker) whitespace_checker = np.vectorize(_is_whitespace_like_single)(x) num_is_null_like += np.count_nonzero(whitespace_checker) return num_is_null_like def sum_is_null(x): return np.count_nonzero(pd.isnull(x)) def _is_date_single(x): try: return bool(date.fromisoformat(x)) # YYYY-MM-DD except ValueError: return False except TypeError: return False def sum_is_date(x): return np.count_nonzero(np.vectorize(_is_date_single)(x)) def cast_df(df, schema): """Cast datafram from given schema Args: df: spark dataframe schema: schema to cast to. It map from df's col_name to mohave datatype Returns: casted dataframe """ # col name to spark data type mapping col_to_spark_data_type_map = {} # get spark dataframe's actual datatype fields = df.schema.fields for f in fields: col_to_spark_data_type_map[f.name] = f.dataType cast_expr = [] # iterate given schema and cast spark dataframe datatype for col_name in schema: mohave_data_type_from_schema = MohaveDataType(schema.get(col_name, MohaveDataType.OBJECT.value)) if mohave_data_type_from_schema != MohaveDataType.OBJECT: spark_data_type_from_schema = MOHAVE_TO_SPARK_TYPE_MAPPING[mohave_data_type_from_schema] # Only cast column when the data type in schema doesn't match the actual data type if not isinstance(col_to_spark_data_type_map[col_name], spark_data_type_from_schema): # use spark-sql expression instead of spark.withColumn to improve performance expr = f"CAST (`{col_name}` as {SPARK_TYPE_MAPPING_TO_SQL_TYPE[spark_data_type_from_schema]})" else: # include column that has same dataType as it is expr = f"`{col_name}`" else: # include column that has same mohave object dataType as it is expr = f"`{col_name}`" cast_expr.append(expr) if len(cast_expr) != 0: df = df.selectExpr(*cast_expr) return df, schema def validate_schema(df, schema): """Validate if every column is covered in the schema Args: schema (): """ columns_in_df = df.columns columns_in_schema = schema.keys() if len(columns_in_df) != len(columns_in_schema): raise ValueError( f"Invalid schema column size. " f"Number of columns in schema should be equal as number of columns in dataframe. " f"schema columns size: {len(columns_in_schema)}, dataframe column size: {len(columns_in_df)}" ) for col in columns_in_schema: if col not in columns_in_df: raise ValueError( f"Invalid column name in schema. " f"Column in schema does not exist in dataframe. " f"Non-existed columns: {col}" ) def s3_source(spark, mode, dataset_definition): """Represents a source that handles sampling, etc.""" content_type = dataset_definition["s3ExecutionContext"]["s3ContentType"].upper() has_header = dataset_definition["s3ExecutionContext"]["s3HasHeader"] path = dataset_definition["s3ExecutionContext"]["s3Uri"].replace("s3://", "s3a://") try: if content_type == "CSV": df = spark.read.csv(path=path, header=has_header, escape='"', quote='"') elif content_type == "PARQUET": df = spark.read.parquet(path) return default_spark(df) except Exception as e: raise RuntimeError("An error occurred while reading files from S3") from e def infer_and_cast_type(df, spark, inference_data_sample_size=1000, trained_parameters=None): """Infer column types for spark dataframe and cast to inferred data type. Args: df: spark dataframe spark: spark session inference_data_sample_size: number of row data used for type inference trained_parameters: trained_parameters to determine if we need infer data types Returns: a dict of pyspark df with column data type casted and trained parameters """ from pyspark.sql.utils import AnalysisException # if trained_parameters is none or doesn't contain schema key, then type inference is needed if trained_parameters is None or not trained_parameters.get("schema", None): # limit first 1000 rows to do type inference limit_df = df.limit(inference_data_sample_size) schema = type_inference(limit_df) else: schema = trained_parameters["schema"] try: validate_schema(df, schema) except ValueError as e: raise OperatorCustomerError(e) try: df, schema = cast_df(df, schema) except (AnalysisException, ValueError) as e: raise OperatorCustomerError(e) trained_parameters = {"schema": schema} return default_spark_with_trained_parameters(df, trained_parameters) def custom_pandas(df, spark, code): """ Apply custom pandas code written by the user on the input dataframe. Right now only pyspark dataframe is supported as input, so the pyspark df is converted to pandas df before the custom pandas code is being executed. The output df is converted back to pyspark df before getting returned. Example: The custom code expects the user to provide an output df. code = \""" import pandas as pd df = pd.get_dummies(df['country'], prefix='country') \""" Notes: This operation expects the user code to store the output in df variable. Args: spark: Spark Session params (dict): dictionary that has various params. Required param for this operation is "code" df: pyspark dataframe Returns: df: pyspark dataframe with the custom pandas code executed on the input df. """ import ast exec_block = ast.parse(code, mode="exec") if len(exec_block.body) == 0: return default_spark(df) pandas_df = df.toPandas() _globals, _locals = {}, {"df": pandas_df} stdout = capture_stdout(exec, compile(exec_block, "<string>", mode="exec"), _locals) # pylint: disable=W0122 pandas_df = eval("df", _globals, _locals) # pylint: disable=W0123 # find list of columns with all None values and fill with empty str. null_columns = pandas_df.columns[pandas_df.isnull().all()].tolist() pandas_df[null_columns] = pandas_df[null_columns].fillna("") # convert the mixed cols to str, since pyspark df does not support mixed col. df = convert_or_coerce(pandas_df, spark) # while statement is to recurse over all fields that have mixed type and cannot be converted while not isinstance(df, DataFrame): df = convert_or_coerce(df, spark) return default_spark_with_stdout(df, stdout) def format_string(df, spark, **kwargs): return dispatch( "operator", [df], kwargs, { "Lower case": (format_string_lower_case, "lower_case_parameters"), "Upper case": (format_string_upper_case, "upper_case_parameters"), "Title case": (format_string_title_case, "title_case_parameters"), "Capitalize": (format_string_capitalize, "capitalize_parameters"), "Swap case": (format_string_swap_case, "swap_case_parameters"), "Left pad": (format_string_left_pad, "left_pad_parameters"), "Right pad": (format_string_right_pad, "right_pad_parameters"), "Center (pad on either side)": ( format_string_center_pad_on_either_side, "center_pad_on_either_side_parameters", ), "Strip characters from left": ( format_string_strip_characters_from_left, "strip_characters_from_left_parameters", ), "Strip characters from right": ( format_string_strip_characters_from_right, "strip_characters_from_right_parameters", ), "Strip left and right": (format_string_strip_left_and_right, "strip_left_and_right_parameters"), "Prepend zeros": (format_string_prepend_zeros, "prepend_zeros_parameters"), "Add prefix": (format_string_add_prefix, "add_prefix_parameters"), "Add suffix": (format_string_add_suffix, "add_suffix_parameters"), "Remove symbols": (format_string_remove_symbols, "remove_symbols_parameters"), }, ) def encode_categorical(df, spark, **kwargs): return dispatch( "operator", [df], kwargs, { "Ordinal encode": (encode_categorical_ordinal_encode, "ordinal_encode_parameters"), "One-hot encode": (encode_categorical_one_hot_encode, "one_hot_encode_parameters"), }, ) def cast_single_data_type( # noqa: C901 df, spark, column, data_type, non_castable_data_handling_method="replace_null", replace_value=None, date_formatting="dd-MM-yyyy", ): """Cast pyspark dataframe column type Args: column: column name e.g.: "col_1" data_type: data type to cast to non_castable_data_handling_method: supported method: ("replace_null","replace_null_with_new_col", "replace_value","replace_value_with_new_col","drop") If not specified, it will use the default method replace_null. see casting.NonCastableDataHandlingMethod replace_value: value to replace non-castable data date_formatting: date format to cast to Returns: df: pyspark df with column data type casted """ from pyspark.sql.utils import AnalysisException supported_type = MohaveDataType.get_values() df_cols = df.columns # Validate input params if column not in df_cols: raise OperatorCustomerError( f"Invalid column name. {column} is not in current columns {df_cols}. Please use a valid column name." ) if data_type not in supported_type: raise OperatorCustomerError( f"Invalid data_type. {data_type} is not in {supported_type}. Please use a supported data type." ) support_invalid_data_handling_method = NonCastableDataHandlingMethod.get_values() if non_castable_data_handling_method not in support_invalid_data_handling_method: raise OperatorCustomerError( f"Invalid data handling method. " f"{non_castable_data_handling_method} is not in {support_invalid_data_handling_method}. " f"Please use a supported method." ) mohave_data_type = MohaveDataType(data_type) spark_data_type = [f.dataType for f in df.schema.fields if f.name == column] if isinstance(spark_data_type[0], MOHAVE_TO_SPARK_TYPE_MAPPING[mohave_data_type]): return default_spark(df) try: df = cast_single_column_type( df, column=column, mohave_data_type=MohaveDataType(data_type), invalid_data_handling_method=NonCastableDataHandlingMethod(non_castable_data_handling_method), replace_value=replace_value, date_formatting=date_formatting, ) except (AnalysisException, ValueError) as e: raise OperatorCustomerError(e) return default_spark(df) op_1_output = s3_source(spark=spark, mode=mode, **{'dataset_definition': {'__typename': 'S3CreateDatasetDefinitionOutput', 'datasetSourceType': 'S3', 'name': 'claims.csv', 'description': None, 's3ExecutionContext': {'__typename': 'S3ExecutionContext', 's3Uri': 's3://sagemaker-us-east-1-870180618679/fraud-detect-demo/data/raw/claims.csv', 's3ContentType': 'csv', 's3HasHeader': True}}}) op_2_output = infer_and_cast_type(op_1_output['default'], spark=spark, **{}) op_3_output = custom_pandas(op_2_output['default'], spark=spark, **{'code': '# Table is available as variable `df`\ncat_cols = df.dtypes[df.dtypes == object].index\ndf[cat_cols] = df[cat_cols].apply(lambda x: x.str.lower())\n'}) op_4_output = format_string(op_3_output['default'], spark=spark, **{'operator': 'Remove symbols', 'remove_symbols_parameters': {'symbols': '!@#$%^&*()_+=-/\\`~{}|<>?', 'input_column': 'driver_relationship'}, 'lower_case_parameters': {}}) op_5_output = format_string(op_4_output['default'], spark=spark, **{'operator': 'Remove symbols', 'remove_symbols_parameters': {'symbols': '!@#$%^&*()_+=-/\\`~{}|<>?', 'input_column': 'collision_type'}, 'lower_case_parameters': {}}) op_6_output = format_string(op_5_output['default'], spark=spark, **{'operator': 'Remove symbols', 'remove_symbols_parameters': {'symbols': '!@#$%^&*()_+=-/\\`~{}|<>?', 'input_column': 'incident_type'}, 'lower_case_parameters': {}}) op_7_output = encode_categorical(op_6_output['default'], spark=spark, **{'operator': 'One-hot encode', 'one_hot_encode_parameters': {'invalid_handling_strategy': 'Keep', 'drop_last': False, 'output_style': 'Columns', 'input_column': 'driver_relationship'}, 'ordinal_encode_parameters': {'invalid_handling_strategy': 'Replace with NaN'}}) op_8_output = encode_categorical(op_7_output['default'], spark=spark, **{'operator': 'One-hot encode', 'one_hot_encode_parameters': {'invalid_handling_strategy': 'Keep', 'drop_last': False, 'output_style': 'Columns', 'input_column': 'incident_type'}, 'ordinal_encode_parameters': {'invalid_handling_strategy': 'Replace with NaN'}}) op_9_output = encode_categorical(op_8_output['default'], spark=spark, **{'operator': 'One-hot encode', 'one_hot_encode_parameters': {'invalid_handling_strategy': 'Keep', 'drop_last': False, 'output_style': 'Columns', 'input_column': 'collision_type'}, 'ordinal_encode_parameters': {'invalid_handling_strategy': 'Replace with NaN'}}) op_10_output = encode_categorical(op_9_output['default'], spark=spark, **{'operator': 'One-hot encode', 'one_hot_encode_parameters': {'invalid_handling_strategy': 'Keep', 'drop_last': False, 'output_style': 'Columns', 'input_column': 'authorities_contacted'}, 'ordinal_encode_parameters': {'invalid_handling_strategy': 'Replace with NaN'}}) op_11_output = encode_categorical(op_10_output['default'], spark=spark, **{'operator': 'Ordinal encode', 'ordinal_encode_parameters': {'invalid_handling_strategy': 'Replace with NaN', 'input_column': 'incident_severity'}}) op_12_output = encode_categorical(op_11_output['default'], spark=spark, **{'operator': 'Ordinal encode', 'ordinal_encode_parameters': {'invalid_handling_strategy': 'Replace with NaN', 'input_column': 'police_report_available'}}) op_13_output = custom_pandas(op_12_output['default'], spark=spark, **{'code': "# Table is available as variable `df`\nimport pandas as pd\ndf['event_time'] = pd.to_datetime('now').timestamp()"}) op_14_output = cast_single_data_type(op_13_output['default'], spark=spark, **{'column': 'police_report_available', 'original_data_type': 'Float', 'data_type': 'long'}) op_15_output = cast_single_data_type(op_14_output['default'], spark=spark, **{'column': 'authorities_contacted_fire', 'original_data_type': 'Float', 'data_type': 'long'}) op_16_output = cast_single_data_type(op_15_output['default'], spark=spark, **{'column': 'authorities_contacted_ambulance', 'original_data_type': 'Float', 'data_type': 'long'}) op_17_output = cast_single_data_type(op_16_output['default'], spark=spark, **{'column': 'authorities_contacted_none', 'original_data_type': 'Float', 'data_type': 'long'}) op_18_output = cast_single_data_type(op_17_output['default'], spark=spark, **{'column': 'authorities_contacted_police', 'original_data_type': 'Float', 'data_type': 'long'}) op_19_output = cast_single_data_type(op_18_output['default'], spark=spark, **{'column': 'collision_type_na', 'original_data_type': 'Float', 'data_type': 'long'}) op_20_output = cast_single_data_type(op_19_output['default'], spark=spark, **{'column': 'collision_type_side', 'original_data_type': 'Float', 'data_type': 'long'}) op_21_output = cast_single_data_type(op_20_output['default'], spark=spark, **{'column': 'incident_type_theft', 'original_data_type': 'Float', 'data_type': 'long'}) op_22_output = cast_single_data_type(op_21_output['default'], spark=spark, **{'column': 'incident_type_breakin', 'original_data_type': 'Float', 'data_type': 'long'}) op_23_output = cast_single_data_type(op_22_output['default'], spark=spark, **{'column': 'incident_type_collision', 'original_data_type': 'Float', 'data_type': 'long'}) op_24_output = cast_single_data_type(op_23_output['default'], spark=spark, **{'column': 'driver_relationship_other', 'original_data_type': 'Float', 'data_type': 'long'}) op_25_output = cast_single_data_type(op_24_output['default'], spark=spark, **{'column': 'driver_relationship_child', 'original_data_type': 'Float', 'data_type': 'long'}) op_26_output = cast_single_data_type(op_25_output['default'], spark=spark, **{'column': 'driver_relationship_spouse', 'original_data_type': 'Float', 'data_type': 'long'}) op_27_output = cast_single_data_type(op_26_output['default'], spark=spark, **{'column': 'driver_relationship_na', 'original_data_type': 'Float', 'data_type': 'long'}) op_28_output = cast_single_data_type(op_27_output['default'], spark=spark, **{'column': 'driver_relationship_self', 'original_data_type': 'Float', 'data_type': 'long'}) op_29_output = cast_single_data_type(op_28_output['default'], spark=spark, **{'column': 'total_claim_amount', 'original_data_type': 'Long', 'data_type': 'float'}) op_30_output = cast_single_data_type(op_29_output['default'], spark=spark, **{'column': 'vehicle_claim', 'original_data_type': 'Long', 'data_type': 'float'}) op_31_output = cast_single_data_type(op_30_output['default'], spark=spark, **{'column': 'injury_claim', 'original_data_type': 'Long', 'data_type': 'float'}) op_32_output = cast_single_data_type(op_31_output['default'], spark=spark, **{'column': 'incident_severity', 'original_data_type': 'Float', 'data_type': 'long'}) op_33_output = cast_single_data_type(op_32_output['default'], spark=spark, **{'column': 'collision_type_rear', 'original_data_type': 'Float', 'data_type': 'long'}) op_34_output = cast_single_data_type(op_33_output['default'], spark=spark, **{'column': 'collision_type_front', 'original_data_type': 'Float', 'data_type': 'long'}) # Glossary: variable name to node_id # # op_1_output: e5d60d4f-6284-4a68-a788-39787909ebc9 # op_2_output: 1626aef2-cad0-4922-a496-34586d3def90 # op_3_output: 921ad4e5-3812-4651-b3cd-fecc38e0bba6 # op_4_output: e90bfd12-d702-4c79-8e11-5e4011600fda # op_5_output: 10ca6bec-5d89-43bd-ba3e-7b5e839e9d23 # op_6_output: 09a3e1c7-29c5-46e8-8690-4cdaf905628a # op_7_output: a5333162-b98e-41f4-8b18-5bb68b98a615 # op_8_output: de96bceb-ac8c-40d4-a9e8-5a777b44437c # op_9_output: 2e5cb36f-b0a5-4763-9740-2ef60f3c6376 # op_10_output: e20b22bc-12aa-469e-9d6c-c4083ddedf08 # op_11_output: cd48da2b-c648-41e2-b828-38b518fc795d # op_12_output: 9ff4c2a4-e1fe-4a66-819f-f7d8df7a5fed # op_13_output: 67fdfb06-278a-4360-8454-3ec1abf1ddd3 # op_14_output: f324323b-8d6e-4e6f-a362-eb9405c2aabf # op_15_output: c3e12fe4-0792-4627-a728-43bb51312196 # op_16_output: 0e239308-1ad0-421b-9e8f-36011d83a6b6 # op_17_output: 93d33455-1cf2-485d-aaf7-5ae5c7d5197e # op_18_output: 0eff4390-66cb-423a-bad4-40fc368aa6d4 # op_19_output: 488aa71e-881e-451e-be8b-5d960530715c # op_20_output: 38ede4e0-ac3c-4e73-9b5e-ad5216997520 # op_21_output: dc6b5e18-0423-4940-afbe-57e24560400e # op_22_output: acb3f245-c50b-4174-8295-5b933500568b # op_23_output: 9dfb1906-6d9a-45d3-ac92-d5f3f535ff8a # op_24_output: a65a0721-7696-4e64-9e65-2423dc65163e # op_25_output: 9b23353f-c840-4bed-9368-636a249038b7 # op_26_output: 1c9c8473-9ccb-4ce4-a2a0-db15c648565e # op_27_output: a00c44fb-3704-4e1c-bda7-887f0feae6a6 # op_28_output: 7bd2e323-2ef9-4329-844a-0f2406ff980c # op_29_output: 7132ae96-da8f-4a02-8708-0bc233a5ecd2 # op_30_output: 10a9d871-4660-44fb-aa9f-14f14a4f5a44 # op_31_output: 01b14795-ad16-4e33-af09-5cedf7a3b806 # op_32_output: 8328f4cc-9adf-47e7-9752-9ab1cf83e7b9 # op_33_output: 6d59ff64-c095-4f20-a7ba-c4a49e842c7c # op_34_output: 62d710d9-a288-4004-b960-6cf452c0380c
StarcoderdataPython
15734
<reponame>yamanogluberk/ConnectedClipboard import select import socket import json import threading import time import clipboard import math from datetime import datetime ip = "" localpart = "" name = "" tcp = 5555 udp = 5556 buffer_size = 1024 broadcast_try_count = 3 ping_try_count = 3 members = [] # item - (str) ipaddress current_room_ip = "" my_room_name = "" # only room owner has this data discovered_rooms = set() # item - (roomname, roomip) REQUESTED_ROOM = ("", "") CLIPBOARD_DATA = clipboard.paste() CLIPBOARD_LOCK = threading.Lock() DATA_LOCK = threading.Lock() SHARED_TIME_BASE = 0 PRIVATE_TIME_BASE = 0 LATENCY = 0 RECEIVED_PING_COUNTER = 0 LAST_CHANGED_TS = 0 is_main_ui = True input_active = True def main(): print() print("*****************************************") print("**** WELCOME TO Clipboarder ****") print("*****************************************") print() get_ip() listen_udp = threading.Thread(target=start_listening_udp) listen_udp.setDaemon(True) listen_udp.start() listen_tcp = threading.Thread(target=start_listening_tcp) listen_tcp.setDaemon(True) listen_tcp.start() listen_cb = threading.Thread(target=listening_clipboard) listen_cb.setDaemon(True) listen_cb.start() send_discover() main_ui_info() input_ui() listen_cb.join() listen_udp.join() listen_tcp.join() def input_ui(): global is_main_ui global input_active while True: cmd = input() if not input_active: continue if is_main_ui: splitted = cmd.strip().split(" ") if len(splitted) >= 2 and splitted[0] == "/create": create_new_room(' '.join(splitted[1:])) elif len(splitted) >= 2 and splitted[0] == "/join": input_active = False join_room(' '.join(splitted[1:])) elif len(splitted) == 1 and splitted[0] == "/quit": terminate() elif len(splitted) == 1 and splitted[0] == "/refresh": discovered_rooms.clear() main_ui_info() send_discover() else: if cmd.strip() == "/leave": leave_room() elif cmd.strip() == "/list": list_users() def main_ui_info(): if len(discovered_rooms) == 0: print() print("There is no active rooms in the network!") print() else: for item in discovered_rooms: print("Active rooms:") print() print(item[0]) print() print(" ********************************************* ") print() print("Type /create <roomname> to create a new room") print("Type /refresh to refresh active room list") print("Type /join <roomname> to join an existing room") print("Type /quit to exit the application") print() print(" ********************************************* ") def room_ui_info(): print() print(f"There are {len(members)} members in the room!") print() print(" ********************************************* ") print() print("Type /leave to leave the current room") print("Type /list to list users in the room") print() print(" ********************************************* ") def create_new_room(room_name): global is_main_ui global my_room_name global current_room_ip my_room_name = room_name current_room_ip = ip members.append(ip) print("New room created with name ", room_name) room_ui_info() is_main_ui = False def join_room(room_name): global is_main_ui global input_active global REQUESTED_ROOM for item in discovered_rooms: if room_name == item[0]: send_connect(item[1]) REQUESTED_ROOM = item return print() print("This room doesnt exist!") print() input_active = True def leave_room(): global current_room_ip global members global is_main_ui global my_room_name global SHARED_TIME_BASE global PRIVATE_TIME_BASE global LATENCY global RECEIVED_PING_COUNTER if current_room_ip == ip: # DISBAND GROUP for mem in members: if mem != ip: send_kick(mem) current_room_ip = "" my_room_name = "" members.clear() main_ui_info() is_main_ui = True else: # LEAVE GROUP send_disconnect(current_room_ip) current_room_ip = "" members.clear() main_ui_info() is_main_ui = True SHARED_TIME_BASE = 0 PRIVATE_TIME_BASE = 0 LATENCY = 0 RECEIVED_PING_COUNTER = 0 def list_users(): k = 1 print("Current users:") for mem in members: print(str(k) + " -> " + mem) k = k + 1 def terminate(): exit() def get_ip(): global ip global localpart s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) temp = "127.0.0.1" try: s.connect(("8.8.8.8", 80)) temp = s.getsockname()[0] finally: s.close() parts = temp.split(".") localpart = parts[3] ip = temp def start_listening_udp(): while True: with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: s.bind(("", udp)) s.setblocking(False) result = select.select([s], [], []) msg = result[0][0].recv(buffer_size) infer_data(msg.decode()) def start_listening_tcp(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((ip, tcp)) s.listen() while True: conn, addr = s.accept() with conn: data = "" while True: temp = conn.recv(buffer_size) if not temp: break data += temp.decode() handle_tcp_req = threading.Thread(target=infer_data, args=(data,)) handle_tcp_req.setDaemon(True) handle_tcp_req.start() #infer_data(data) def infer_data(data): try: data = json.loads(data) if data["IP"] == ip: return if data["TYPE"] == "DISCOVER_ROOMS": discover_received(data) elif data["TYPE"] == "RESPOND_ROOM": respond_received(data) elif data["TYPE"] == "CONNECT": connect_received(data) elif data["TYPE"] == "DISCONNECT": disconnect_received(data) elif data["TYPE"] == "CONNECTION_APPROVED": connection_approved_received(data) elif data["TYPE"] == "NEW_MEMBER": new_member_received(data) elif data["TYPE"] == "MEMBER_DISCONNECTED": member_disconnected_received(data) elif data["TYPE"] == "KICK": kick_received(data) elif data["TYPE"] == "CLIPBOARD": clipboard_received(data) elif data["TYPE"] == "PING": ping_received(data) elif data["TYPE"] == "PING_RESPOND": ping_respond_received(data) elif data["TYPE"] == "REQUEST_TIMESTAMP": receive_timestamp_request(data) elif data["TYPE"] == "RECEIVE TIMESTAMP": receive_timestamp(data) except: print("The received packet is not Json or not the proper practice of the protocol!") def discover_received(data): if my_room_name.strip() != "": send_respond(data["IP"], my_room_name) def respond_received(data): newroom = (data["DATA"], data["IP"]) if newroom not in discovered_rooms: discovered_rooms.add(newroom) main_ui_info() def connect_received(data): if my_room_name.strip() == "": print("Received connect when there is no owned room!!!") return elif data["IP"] in members: pass else: for mem in members: if mem != ip: send_new_member(mem, data["IP"]) members.append(data["IP"]) send_connection_approved(data["IP"]) def disconnect_received(data): if data["IP"] in members: members.remove(data["IP"]) for mem in members: if mem != ip: send_member_disconnected(mem, data["IP"]) def connection_approved_received(data): global current_room_ip global members global is_main_ui global input_active global REQUESTED_ROOM global LATENCY global RECEIVED_PING_COUNTER if current_room_ip == "" and REQUESTED_ROOM[1] == data["IP"]: REQUESTED_ROOM = ("", "") current_room_ip = data["IP"] members = data["DATA"] is_main_ui = False input_active = True room_ui_info() for x in range(ping_try_count): send_ping(current_room_ip) with DATA_LOCK: LATENCY = LATENCY - get_current_timestamp() counter = 0 while RECEIVED_PING_COUNTER != ping_try_count: time.sleep(0.1) counter = counter + 1 if counter > 100: return send_timestamp_request(current_room_ip) def send_ping(target_ip): data = f"{get_json('PING')}" send_message_tcp(data, target_ip) def send_ping_respond(target_ip): data = f"{get_json('PING_RESPOND')}" send_message_tcp(data, target_ip) def ping_received(data): global current_room_ip if current_room_ip == ip and data["IP"] in members: send_ping_respond(data["IP"]) def ping_respond_received(data): global current_room_ip global LATENCY global RECEIVED_PING_COUNTER if current_room_ip == data["IP"]: with DATA_LOCK: LATENCY = LATENCY + get_current_timestamp() #print("PING RESPOND RECEIVED::PING LATENCY --> " + str(LATENCY)) RECEIVED_PING_COUNTER = RECEIVED_PING_COUNTER + 1 def send_timestamp_request(target_ip): data = f"{get_json('REQUEST_TIMESTAMP')}" send_message_tcp(data, target_ip) def receive_timestamp_request(data): global current_room_ip if current_room_ip == ip and data["IP"] in members: send_timestamp(data["IP"]) def send_timestamp(target_ip): ct = get_current_timestamp() data = f"{get_json('RECEIVE TIMESTAMP', ct)}" send_message_tcp(data, target_ip) def receive_timestamp(data): global SHARED_TIME_BASE global PRIVATE_TIME_BASE if current_room_ip == data["IP"]: SHARED_TIME_BASE = data["DATA"] SHARED_TIME_BASE = SHARED_TIME_BASE + (LATENCY / (ping_try_count * 2)) PRIVATE_TIME_BASE = get_current_timestamp() print("LATENCY --> " + str((LATENCY / (ping_try_count * 2)))) print("SHARED_TIME_BASE --> " + str(SHARED_TIME_BASE)) print("PRIVATE_TIME_BASE --> " + str(PRIVATE_TIME_BASE)) def new_member_received(data): if (data["IP"] == current_room_ip) and (data["DATA"] not in members): members.append(data["DATA"]) def member_disconnected_received(data): if (data["IP"] == current_room_ip) and (data["DATA"] in members): members.remove(data["DATA"]) def kick_received(data): global current_room_ip global members global is_main_ui global my_room_name global RECEIVED_PING_COUNTER global SHARED_TIME_BASE global PRIVATE_TIME_BASE global LATENCY if data["IP"] == current_room_ip: current_room_ip = "" members.clear() main_ui_info() is_main_ui = True SHARED_TIME_BASE = 0 PRIVATE_TIME_BASE = 0 LATENCY = 0 RECEIVED_PING_COUNTER = 0 def listening_clipboard(): global CLIPBOARD_DATA global LAST_CHANGED_TS while True: with CLIPBOARD_LOCK: current_clipboard = clipboard.paste() if CLIPBOARD_DATA != current_clipboard: clipboard_ts = SHARED_TIME_BASE + (get_current_timestamp() - PRIVATE_TIME_BASE) for mem in members: if mem != ip: send_clipboard(mem, clipboard_ts, current_clipboard) CLIPBOARD_DATA = current_clipboard LAST_CHANGED_TS = clipboard_ts time.sleep(0.1) def clipboard_received(data): global CLIPBOARD_DATA global LAST_CHANGED_TS with CLIPBOARD_LOCK: if LAST_CHANGED_TS < data["TIMESTAMP"]: CLIPBOARD_DATA = data["DATA"] LAST_CHANGED_TS = data["TIMESTAMP"] clipboard.copy(CLIPBOARD_DATA) def send_clipboard(target_ip, clipboard_ts, clipboard_data): data = f"{get_json_ts('CLIPBOARD', clipboard_ts, clipboard_data)}" send_message_tcp(data, target_ip) def send_discover(): data = f"{get_json('DISCOVER_ROOMS')}" send_broadcast(data) def send_respond(target_ip, room_name): data = f"{get_json('RESPOND_ROOM', room_name)}" send_message_tcp(data, target_ip) def send_connect(target_ip): data = f"{get_json('CONNECT')}" send_message_tcp(data, target_ip) def send_disconnect(target_ip): data = f"{get_json('DISCONNECT')}" send_message_tcp(data, target_ip) def send_kick(target_ip): data = f"{get_json('KICK')}" send_message_tcp(data, target_ip) def send_connection_approved(target_ip): data = f"{get_json('CONNECTION_APPROVED', members)}" send_message_tcp(data, target_ip) def send_new_member(target_ip, member_ip): data = f"{get_json('NEW_MEMBER', member_ip)}" send_message_tcp(data, target_ip) def send_member_disconnected(target_ip, member_ip): data = f"{get_json('MEMBER_DISCONNECTED', member_ip)}" send_message_tcp(data, target_ip) def send_broadcast(data): for x in range(broadcast_try_count): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('', 0)) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.sendto(data.encode(), ('<broadcast>', udp)) s.close() def send_message_tcp(data, destination): thread = threading.Thread(target=send_message_thread, args=(data, destination), daemon=True) thread.start() def send_message_thread(packet, destination): global current_room_ip try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.settimeout(1) s.connect((destination, tcp)) s.sendall(packet.encode()) except: print("!! Unexpected offline member detected !!") def get_json(typename, data=None): packet = {"IP": ip, "TYPE": typename, "DATA": data} return json.dumps(packet) def get_json_ts(typename, timestamp, data): packet = {"IP": ip, "TYPE": typename, "TIMESTAMP": timestamp, "DATA": data} return json.dumps(packet) def get_current_timestamp(): ts = datetime.now().timestamp() * 1000 ts = math.floor(ts) return ts if __name__ == '__main__': main()
StarcoderdataPython
3270827
import numpy as np from multi_affine.datagenerators import indicator, load_volfile, select_index_atlas def datagenerator_nonrigid(gen, diffeomorphic=False, atlas_shape=[64,64,64], batch_size=1, test=False): """ function to generate data for training. Args: gen: image generator to load image and atlas diffeomorphic: if true placeholder for inv_warp is added Returns: input [image, atlas] and output network [atlas, zeros] where the zeros are a placeholder for the deformation field. """ zeros = np.zeros((batch_size, *atlas_shape, len(atlas_shape))) if diffeomorphic == False: while True: X = next(gen) yield ([X[0], X[1]], [X[1], zeros]) if test == True: return [[X[0], X[1]], [X[1], zeros]] else: while True: X = next(gen) yield ([X[0], X[1]], [X[1], zeros, zeros]) def image_generator(vol_names, M, atlasses, age_atlas, atlas_files, batch_size=1, np_var='vol_data', test=False): """ function to load image and atlas for training. Args: vol_names: list with names of the images in the dataset M: number of atlases used for optimization atlasses: npy array with atlasses age_atlas: list with age of atlases atlas_list: list of names of avaliable atlases Return: X: input image atlas: select atlases to be used as input Here out of the M eligible atlases one is chosen as input for the network. """ while True: idxes = np.random.randint(len(vol_names), size=batch_size) for idx in idxes: X = load_volfile(vol_names[idx], np_var=np_var) X = X[np.newaxis, ..., np.newaxis] # for implementation of data augmentation: this should be put here gt_file=vol_names[idx].split('_moved_affine')[0]+'_annotation.npz' age=int(load_volfile(gt_file,np_var='GA')) indi=indicator(age, M, age_atlas, atlas_files) #randomly select which of the M available atlases from indi is used for training in this epoch idxes_select=select_index_atlas(indi) atlas=atlasses[idxes_select,:,:,:,:][np.newaxis,...] return_vals = [X,atlas] yield tuple(return_vals) if test == True: return return_vals
StarcoderdataPython
3369019
<reponame>jzmq/minos<gh_stars>100-1000 import json import logging import logging.config import os import sys import time import tsdb_register import urllib from tsdb_register import collect_period from tsdb_register import metrics_url from tsdb_register import opentsdb_bin_path from tsdb_register import opentsdb_extra_args from tsdb_register import TsdbRegister local_data_path = 'metrics_dump.data' logging.config.fileConfig('metrics_logging.conf') logger_metrics = logging.getLogger('metrics') def verify_config(): if not metrics_url: logger_metrics.warning("Please set metrics url") return False if not opentsdb_bin_path: logger_metrics.warning("Please set opentsdb_bin_path") return False if not collect_period: logger_metrics.warning("Please set collect_period") return False return True class MetricsCollector(): def __init__(self): self.tsdb_register = TsdbRegister() def run(self): while True: start = time.time() self.collect_metrics() self.tsdb_register.register_new_keys_to_tsdb() self.batch_output_to_tsdb() end = time.time() to_sleep_time = collect_period - (end - start) if to_sleep_time > 0: time.sleep(to_sleep_time) def collect_metrics(self): try: out_file = open(local_data_path, 'w') json_string = urllib.urlopen(metrics_url).read() metrics = json.loads(json_string) timestamp = metrics['timestamp'] for endpoint, group_metrics in metrics['data'].iteritems(): for group, key_metrics in group_metrics.iteritems(): for key, metric in key_metrics.iteritems(): if key.find('#') != -1: key = key.replace("#", "_") value = metric['value'] self.append_to_file(out_file, timestamp, key, value, endpoint, group) if key not in self.tsdb_register.register_keys: self.tsdb_register.new_keys.append(key) self.tsdb_register.register_keys.add(key) out_file.close() except Exception, e: logger_metrics.error("collect_metrics exception: %s", e) @staticmethod def append_to_file(out_file, timestamp, key, value, endpoint, group): # format example: metric_key 1288900000 42 host=127.0.0.1-10000 group=Master out_file.write("%s %s %s host=%s group=%s\n" % (key, timestamp, value, endpoint, group)) def batch_output_to_tsdb(self): start_time = time.time() os.system('%s import %s %s' % (opentsdb_bin_path, opentsdb_extra_args, local_data_path)) logger_metrics.info("Batch import metrics cost %f secs" % (time.time() - start_time)) if __name__ == '__main__': if not verify_config(): sys.exit(-1) collector = MetricsCollector() collector.run()
StarcoderdataPython
3299978
from abc import ABC, abstractmethod from dataclasses import dataclass, field # Added list for typing for back compatibility to 3.8 and 3.7 from typing import Union, List from .component import AbstractComponent @dataclass class AbstractBuilder(ABC): builder_component: Union[None, AbstractComponent] = None # use List instead of list for typehint for py37 and py38 components: List[AbstractComponent] = field(default_factory=list) @abstractmethod def add_component(self, component: AbstractComponent): ... @abstractmethod def build(self, build_content: str = None): ... class Builder(AbstractBuilder): def add_component(self, component: AbstractComponent): self.components.append(component) @abstractmethod def build(self, build_content: str = None) -> str: ...
StarcoderdataPython
1791506
<reponame>fogleman/DCPU-16 import distutils import os import py2exe import shutil import sys def run_py2exe(): py2exe.__version__ sys.argv.append('py2exe') distutils.core.setup( options = {"py2exe":{ "compressed": True, "optimize": 1, "bundle_files": 1, "excludes": ['Tkconstants', 'Tkinter', 'tcl'], "dll_excludes": ['msvcp90.dll'], }}, windows = [{ "script": "main.py", "dest_base": "dcpu16", "icon_resources": [(1, "icons/icon.ico")], "other_resources": [(24, 1, MANIFEST)], }], zipfile=None, ) def copy_file(src): print 'Copying:', src dst = os.path.join('dist', src) try: os.makedirs(os.path.split(dst)[0]) except Exception: pass shutil.copyfile(src, dst) def copy_directory(src): for path, _, files in os.walk(src): if '.svn' in path: continue for filename in files: copy_file(os.path.join(path, filename)) def main(): run_py2exe() copy_directory('Microsoft.VC90.CRT') copy_directory('programs') copy_file('_emulator.dll') MANIFEST = ''' <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="2.0.0.0" processorArchitecture="x86" name="Star Rocket Level Editor" type="win32" /> <description>Star Rocket Level Editor 1.0</description> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false" /> </requestedPrivileges> </security> </trustInfo> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="<KEY>" /> </dependentAssembly> </dependency> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="x86" publicKeyToken="<KEY>" language="*" /> </dependentAssembly> </dependency> </assembly> ''' if __name__ == '__main__': main()
StarcoderdataPython
1641227
<gh_stars>100-1000 #!/usr/bin/python # # Copyright 2020 Google LLC # # 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 matplotlib.pyplot as plt import matplotlib.colors as colors import matplotlib.cbook as cbook import numpy as np raw = np.loadtxt("grid_search_bhe.txt") data = raw[:, 2].reshape(100, 100) error = np.linalg.norm(raw[:, 3:5] - np.array([[3.0, 4.0]]), axis=1) error = error.reshape(100, 100) print(error) # print(data[0]) # plt.imshow(data, cmap='hot', interpolation='nearest') # plt.grid() # plt.gca().set_xticks(np.arange(0, 100, 10)) # plt.gca().set_yticks(np.arange(0, 100, 10)) # plt.gca().set_xticklabels(np.arange(0, 10, 1)) # plt.gca().set_yticklabels(np.arange(0, 10, 1)) # plt.xlabel("Link length 1") # plt.ylabel("Link length 2") # plt.colorbar() # plt.show() X, Y = np.mgrid[0.1:10.1:0.1, 0.1:10.1:0.1] # A low hump with a spike coming out of the top right. Needs to have # z/colour axis on a log scale so we see both hump and spike. linear # scale only shows the spike. # Z1 = np.exp(-(X)**2 - (Y)**2) # Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) # Z = Z1 + 50 * Z2 fig, ax = plt.subplots(1, 2) pcm = ax[0].pcolor(X, Y, data, norm=colors.LogNorm(vmin=data.min(), vmax=data.max()), cmap='PuBu_r') fig.colorbar(pcm, ax=ax[0], extend='max') ax[0].set_xlabel("Link length 1") ax[0].set_ylabel("Link length 2") ax[0].set_title("Final Cost") ax[0].set_aspect('equal', 'box') print("error.min()", error.min()) print("error.max()", error.max()) pcm = ax[1].pcolor(X, Y, error, norm=colors.Normalize(vmin=error.min(), vmax=error.max()), cmap='PuBu_r') fig.colorbar(pcm, ax=ax[1], extend='max') ax[1].set_xlabel("Link length 1") ax[1].set_ylabel("Link length 2") ax[1].set_title("True Parameter Error") ax[1].set_aspect('equal', 'box') # pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r') # fig.colorbar(pcm, ax=ax[1], extend='max') plt.show()
StarcoderdataPython
3247272
# -*- coding: utf-8 -*- """ .. module:: entry :platform: Unix :synopsis: Yify film entry model .. moduleauthor:: <NAME> <<EMAIL>> """ import re class Entry: """Represents a film entry""" def __init__(self, data): """ Args: data (dict): entry data """ self._data = data @property def title(self): """Film title""" return ( re.search(r"(^.+?)(\(.*\)\s)(\[.*\]\s)", self._data["title"]) .group(1) .strip() ) @property def year(self): """Film year""" return ( re.search(r"(^.+?)(\(.*\)\s)(\[.*\]\s)", self._data["title"]) .group(2) .strip()[1:-1] ) @property def format(self): """Film format (typically 720p or 1080p""" return ( re.search(r"(^.+?)(\(.*\)\s)(\[.*\]\s)", self._data["title"]) .group(3) .strip()[1:-1] ) @property def summary(self): """Synopsis of the film""" return re.search(r"(^.+)(/>)(.*)", self._data["summary"]).group(3).strip() @property def runtime(self): """Runtime in minutes""" return ( re.search(r"(Runtime: )(\d.*?)\s", self._data["summary"]).group(2).strip() ) @property def rating(self): """IMDB rating as x/x""" return ( re.search(r"(Rating:\s)(.+)(<br\s/>Runtime)", self._data["summary"]) .group(2) .strip() ) @property def id(self): """Id of the film on Yify, also servers as link""" return self._data["id"] @property def link(self): """Links to the film, without specifying the format""" return self._data["link"] @property def published(self): """Time the film was added to Yify""" return self._data["published"] def get_as_record(self): """Returns record as tuple to be inserted into sqlite3 database""" return tuple( [ self.id, self.title, self.year, self.format, self.summary, self.runtime, self.rating, self.link, self.published, ] ) if __name__ == "__main__": pass
StarcoderdataPython
179987
#!/usr/bin/env python3 import sys def validate(expr) -> str: try: if expr == 'true': return 'Did you mean \'True\'?' if expr == 'false': return 'Did you mean \'False\'?' x = eval(expr) typ = type(x) if typ == str or typ == int or typ == bool: return if typ == list: if len(x) == 0: return elmtType = type(x[0]) if not (elmtType == int or elmtType == str or elmtType == bool): return 'Only int, string and boolean lists are supported.' for e in x[1:]: if type(e) != elmtType: return 'All elements of a list should have the same type' elif typ == dict: if len(x) == 0: return keyType = type(next(iter(x))) valType = type(next(iter(x.values()))) if not (keyType == int or keyType == str): return 'Only int and string keys are supported.' if not (valType == int or valType == str): return 'Only int and string values are supported.' for k in x: if type(k) != keyType: return 'All keys of a dict should have the same type' if type(x[k]) != valType: return 'All values of a dict should have the same type' elif typ == set: if len(x) == 0: return elmtType = type(next(iter(x))) if not (elmtType == int or elmtType == str): return 'Only int and string sets are supported.' for k in x: if type(k) != elmtType: return 'All elements of a set should have the same type' else: return 'Type \'%s\' not supported' % str(typ.__name__) except Exception as e: return str(e) def main(action, arg): # We do many things! if action == 'validate': msg = validate(arg) if msg: print(msg) else: print('Action not recognized: %s' % action) if __name__ == '__main__': main(sys.argv[1], sys.argv[2])
StarcoderdataPython
152222
"""Uses the same strategy as ``adjacency_list.py``, but associates each DOM row with its owning document row, so that a full document of DOM nodes can be loaded using O(1) queries - the construction of the "hierarchy" is performed after the load in a non-recursive fashion and is more efficient. """ # PART I - Imports/Configuration from __future__ import print_function import os import re from xml.etree import ElementTree from sqlalchemy import and_ from sqlalchemy import Column from sqlalchemy import create_engine from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import String from sqlalchemy import Table from sqlalchemy import Unicode from sqlalchemy.orm import lazyload from sqlalchemy.orm import mapper from sqlalchemy.orm import relationship from sqlalchemy.orm import Session e = create_engine("sqlite://") meta = MetaData() # PART II - Table Metadata # stores a top level record of an XML document. documents = Table( "documents", meta, Column("document_id", Integer, primary_key=True), Column("filename", String(30), unique=True), ) # stores XML nodes in an adjacency list model. This corresponds to # Element and SubElement objects. elements = Table( "elements", meta, Column("element_id", Integer, primary_key=True), Column("parent_id", Integer, ForeignKey("elements.element_id")), Column("document_id", Integer, ForeignKey("documents.document_id")), Column("tag", Unicode(30), nullable=False), Column("text", Unicode), Column("tail", Unicode), ) # stores attributes. This corresponds to the dictionary of attributes # stored by an Element or SubElement. attributes = Table( "attributes", meta, Column( "element_id", Integer, ForeignKey("elements.element_id"), primary_key=True, ), Column("name", Unicode(100), nullable=False, primary_key=True), Column("value", Unicode(255)), ) meta.create_all(e) # PART III - Model # our document class. contains a string name, # and the ElementTree root element. class Document(object): def __init__(self, name, element): self.filename = name self.element = element # PART IV - Persistence Mapping # Node class. a non-public class which will represent the DB-persisted # Element/SubElement object. We cannot create mappers for ElementTree elements # directly because they are at the very least not new-style classes, and also # may be backed by native implementations. so here we construct an adapter. class _Node(object): pass # Attribute class. also internal, this will represent the key/value attributes # stored for a particular Node. class _Attribute(object): def __init__(self, name, value): self.name = name self.value = value # setup mappers. Document will eagerly load a list of _Node objects. # they will be ordered in primary key/insert order, so that we can reconstruct # an ElementTree structure from the list. mapper( Document, documents, properties={ "_nodes": relationship( _Node, lazy="joined", cascade="all, delete-orphan" ) }, ) # the _Node objects change the way they load so that a list of _Nodes will # organize themselves hierarchically using the ElementTreeMarshal. this # depends on the ordering of nodes being hierarchical as well; relationship() # always applies at least ROWID/primary key ordering to rows which will # suffice. mapper( _Node, elements, properties={ "children": relationship( _Node, lazy=None ), # doesnt load; used only for the save relationship "attributes": relationship( _Attribute, lazy="joined", cascade="all, delete-orphan" ), # eagerly load attributes }, ) mapper(_Attribute, attributes) # define marshalling functions that convert from _Node/_Attribute to/from # ElementTree objects. this will set the ElementTree element as # "document._element", and append the root _Node object to the "_nodes" mapped # collection. class ElementTreeMarshal(object): def __get__(self, document, owner): if document is None: return self if hasattr(document, "_element"): return document._element nodes = {} root = None for node in document._nodes: if node.parent_id is not None: parent = nodes[node.parent_id] elem = ElementTree.SubElement(parent, node.tag) nodes[node.element_id] = elem else: parent = None elem = root = ElementTree.Element(node.tag) nodes[node.element_id] = root for attr in node.attributes: elem.attrib[attr.name] = attr.value elem.text = node.text elem.tail = node.tail document._element = ElementTree.ElementTree(root) return document._element def __set__(self, document, element): def traverse(node): n = _Node() n.tag = str(node.tag) n.text = str(node.text) n.tail = str(node.tail) document._nodes.append(n) n.children = [traverse(n2) for n2 in node] n.attributes = [ _Attribute(str(k), str(v)) for k, v in node.attrib.items() ] return n traverse(element.getroot()) document._element = element def __delete__(self, document): del document._element document._nodes = [] # override Document's "element" attribute with the marshaller. Document.element = ElementTreeMarshal() # PART V - Basic Persistence Example line = "\n--------------------------------------------------------" # save to DB session = Session(e) # get ElementTree documents for file in ("test.xml", "test2.xml", "test3.xml"): filename = os.path.join(os.path.dirname(__file__), file) doc = ElementTree.parse(filename) session.add(Document(file, doc)) print("\nSaving three documents...", line) session.commit() print("Done.") print("\nFull text of document 'text.xml':", line) document = session.query(Document).filter_by(filename="test.xml").first() ElementTree.dump(document.element) # PART VI - Searching for Paths # manually search for a document which contains "/somefile/header/field1:hi" print("\nManual search for /somefile/header/field1=='hi':", line) d = ( session.query(Document) .join("_nodes", aliased=True) .filter(and_(_Node.parent_id == None, _Node.tag == "somefile")) .join("children", aliased=True, from_joinpoint=True) .filter(_Node.tag == "header") .join("children", aliased=True, from_joinpoint=True) .filter(and_(_Node.tag == "field1", _Node.text == "hi")) .one() ) ElementTree.dump(d.element) # generalize the above approach into an extremely impoverished xpath function: def find_document(path, compareto): query = session.query(Document) first = True for i, match in enumerate( re.finditer(r"/([\w_]+)(?:\[@([\w_]+)(?:=(.*))?\])?", path) ): (token, attrname, attrvalue) = match.group(1, 2, 3) if first: query = query.join("_nodes", aliased=True).filter( _Node.parent_id == None ) first = False else: query = query.join("children", aliased=True, from_joinpoint=True) query = query.filter(_Node.tag == token) if attrname: query = query.join("attributes", aliased=True, from_joinpoint=True) if attrvalue: query = query.filter( and_( _Attribute.name == attrname, _Attribute.value == attrvalue, ) ) else: query = query.filter(_Attribute.name == attrname) return ( query.options(lazyload("_nodes")).filter(_Node.text == compareto).all() ) for path, compareto in ( ("/somefile/header/field1", "hi"), ("/somefile/field1", "hi"), ("/somefile/header/field2", "there"), ("/somefile/header/field2[@attr=foo]", "there"), ): print("\nDocuments containing '%s=%s':" % (path, compareto), line) print([d.filename for d in find_document(path, compareto)])
StarcoderdataPython
73047
<gh_stars>1-10 # -*- coding: utf-8 -*- """ flask_caching.backends.rediscache ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The redis caching backend. :copyright: (c) 2018 by <NAME>. :copyright: (c) 2010 by <NAME>. :license: BSD, see LICENSE for more details. """ from flask_caching.backends.base import BaseCache, iteritems_wrapper try: import cPickle as pickle except ImportError: # pragma: no cover import pickle class RedisCache(BaseCache): """Uses the Redis key-value store as a cache backend. The first argument can be either a string denoting address of the Redis server or an object resembling an instance of a redis.Redis class. Note: Python Redis API already takes care of encoding unicode strings on the fly. :param host: address of the Redis server or an object which API is compatible with the official Python Redis client (redis-py). :param port: port number on which Redis server listens for connections. :param password: password authentication for the Redis server. :param db: db (zero-based numeric index) on Redis Server to connect. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`~BaseCache.set`. A timeout of 0 indicates that the cache never expires. :param key_prefix: A prefix that should be added to all keys. Any additional keyword arguments will be passed to ``redis.Redis``. """ def __init__( self, host="localhost", port=6379, password=<PASSWORD>, db=0, default_timeout=300, key_prefix=None, **kwargs ): super(RedisCache, self).__init__(default_timeout) if host is None: raise ValueError("RedisCache host parameter may not be None") if isinstance(host, str): try: import redis except ImportError: raise RuntimeError("no redis module found") if kwargs.get("decode_responses", None): raise ValueError( "decode_responses is not supported by " "RedisCache." ) client = redis.Redis( host=host, port=port, password=password, db=db, **kwargs ) else: client = host self._write_client = self._read_clients = client self.key_prefix = key_prefix or "" def _get_prefix(self): return ( self.key_prefix if isinstance(self.key_prefix, str) else self.key_prefix() ) def _normalize_timeout(self, timeout): timeout = BaseCache._normalize_timeout(self, timeout) if timeout == 0: timeout = -1 return timeout def dump_object(self, value): """Dumps an object into a string for redis. By default it serializes integers as regular string and pickle dumps everything else. """ t = type(value) if t == int: return str(value).encode("ascii") return b"!" + pickle.dumps(value) def load_object(self, value): """The reversal of :meth:`dump_object`. This might be called with None. """ if value is None: return None if value.startswith(b"!"): try: return pickle.loads(value[1:]) except pickle.PickleError: return None try: return int(value) except ValueError: # before 0.8 we did not have serialization. Still support that. return value def get(self, key): return self.load_object( self._read_clients.get(self._get_prefix() + key) ) def get_many(self, *keys): if self.key_prefix: keys = [self._get_prefix() + key for key in keys] return [self.load_object(x) for x in self._read_clients.mget(keys)] def set(self, key, value, timeout=None): timeout = self._normalize_timeout(timeout) dump = self.dump_object(value) if timeout == -1: result = self._write_client.set( name=self._get_prefix() + key, value=dump ) else: result = self._write_client.setex( name=self._get_prefix() + key, value=dump, time=timeout ) return result def add(self, key, value, timeout=None): timeout = self._normalize_timeout(timeout) dump = self.dump_object(value) return self._write_client.setnx( name=self._get_prefix() + key, value=dump ) and self._write_client.expire( name=self._get_prefix() + key, time=timeout ) def set_many(self, mapping, timeout=None): timeout = self._normalize_timeout(timeout) # Use transaction=False to batch without calling redis MULTI # which is not supported by twemproxy pipe = self._write_client.pipeline(transaction=False) for key, value in iteritems_wrapper(mapping): dump = self.dump_object(value) if timeout == -1: pipe.set(name=self._get_prefix() + key, value=dump) else: pipe.setex( name=self._get_prefix() + key, value=dump, time=timeout ) return pipe.execute() def delete(self, key): return self._write_client.delete(self._get_prefix() + key) def delete_many(self, *keys): if not keys: return if self.key_prefix: keys = [self._get_prefix() + key for key in keys] return self._write_client.delete(*keys) def has(self, key): return self._read_clients.exists(self._get_prefix() + key) def clear(self): status = False if self.key_prefix: keys = self._read_clients.keys(self._get_prefix() + "*") if keys: status = self._write_client.delete(*keys) else: status = self._write_client.flushdb(asynchronous=True) return status def inc(self, key, delta=1): return self._write_client.incr( name=self._get_prefix() + key, amount=delta ) def dec(self, key, delta=1): return self._write_client.decr( name=self._get_prefix() + key, amount=delta ) def unlink(self, *keys): """when redis-py >= 3.0.0 and redis > 4, support this operation """ if not keys: return if self.key_prefix: keys = [self.key_prefix + key for key in keys] unlink = getattr(self._write_client, "unlink", None) if unlink is not None and callable(unlink): return self._write_client.unlink(*keys) return self._write_client.delete(*keys) class RedisSentinelCache(RedisCache): """Uses the Redis key-value store as a cache backend. The first argument can be either a string denoting address of the Redis server or an object resembling an instance of a redis.Redis class. Note: Python Redis API already takes care of encoding unicode strings on the fly. :param sentinels: A list or a tuple of Redis sentinel addresses. :param master: The name of the master server in a sentinel configuration. :param password: <PASSWORD> for the Redis server. :param db: db (zero-based numeric index) on Redis Server to connect. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`~BaseCache.set`. A timeout of 0 indicates that the cache never expires. :param key_prefix: A prefix that should be added to all keys. Any additional keyword arguments will be passed to ``redis.sentinel.Sentinel``. """ def __init__( self, sentinels=None, master=None, password=<PASSWORD>, db=0, default_timeout=300, key_prefix=None, **kwargs ): super(RedisSentinelCache, self).__init__(default_timeout) try: import redis.sentinel except ImportError: raise RuntimeError("no redis module found") if kwargs.get("decode_responses", None): raise ValueError( "decode_responses is not supported by " "RedisCache." ) sentinels = sentinels or [("127.0.0.1", 26379)] sentinel_kwargs = { key[9:]: value for key, value in kwargs.items() if key.startswith("sentinel_") } kwargs = { key[9:]: value for key, value in kwargs.items() if not key.startswith("sentinel_") } sentinel = redis.sentinel.Sentinel( sentinels=sentinels, password=password, db=db, sentinel_kwargs=sentinel_kwargs, **kwargs ) self._write_client = sentinel.master_for(master) self._read_clients = sentinel.slave_for(master) self.key_prefix = key_prefix or ""
StarcoderdataPython
99238
""" This file does three things: - It implements a simple PyTorch model. - Exports in to ONNX using a combination of tracing and scripting - Converts it to MDF """ import torch import onnx from onnx import helper from modeci_mdf.interfaces.onnx import onnx_to_mdf class SimpleIntegrator(torch.nn.Module): def __init__(self, shape, rate): super().__init__() self.previous_value = torch.zeros(shape) self.rate = rate def forward(self, x): value = self.previous_value + (x * self.rate) self.previous_value = value return value class Linear(torch.nn.Module): def __init__(self, slope=1.0, intercept=0.0): super().__init__() self.slope = slope self.intercept = intercept def forward(self, x): return self.slope * x + self.intercept class ABCD(torch.nn.Module): def __init__(self, A, B, C, D): super().__init__() self.A = A self.B = B self.C = C self.D = D def forward(self, x): # Since we are implementing conditions that reference the number of calls # to A and B, we need to keep track of this. num_A_calls = 0 num_B_calls = 0 # We need to initialize outputs, torchscript jit complains if c and d # are not defined in the FALSE branches of our conditionals. a = torch.zeros_like(x) b = torch.zeros_like(x) c = torch.zeros_like(x) d = torch.zeros_like(x) for i in range(10): # A: pnl.AtNCalls(A, 0), if num_A_calls == 0: a = self.A(x) num_A_calls = num_A_calls + 1 # B: pnl.Always() b = self.B(a) num_B_calls = num_B_calls + 1 # C: pnl.EveryNCalls(B, 5), if num_B_calls % 5 == 0: c = self.C(b) # D: pnl.EveryNCalls(B, 10) if num_B_calls % 10 == 0: d = self.D(b) return c, d def main(): slope = torch.ones((1, 1)) * 2.0 intercept = torch.ones((1, 1)) * 2.0 model = ABCD( A=Linear(slope=slope, intercept=intercept), B=Linear(slope=slope, intercept=intercept), C=Linear(slope=slope, intercept=intercept), D=Linear(slope=slope, intercept=intercept), ) model = torch.jit.script(model) output = model(torch.ones((1, 1))) print(output) dummy_input = torch.ones((1, 1)) torch.onnx.export( model, (dummy_input), "abcd.onnx", verbose=True, input_names=["input"], example_outputs=output, opset_version=9, ) # Load it back in using ONNX package onnx_model = onnx.load("abcd.onnx") onnx.checker.check_model(onnx_model) mdf_model = onnx_to_mdf(onnx_model) mdf_model.to_json_file("abcd.json") mdf_model.to_yaml_file("abcd.yaml") if __name__ == "__main__": main()
StarcoderdataPython
108755
<gh_stars>1-10 from fv3gfs.util import Timer, NullTimer import pytest import time @pytest.fixture def timer(): return Timer() @pytest.fixture def null_timer(): return NullTimer() def test_start_stop(timer): timer.start("label") timer.stop("label") times = timer.times assert "label" in times assert len(times) == 1 assert timer.hits["label"] == 1 assert len(timer.hits) == 1 def test_null_timer_cannot_be_enabled(null_timer): with pytest.raises(NotImplementedError): null_timer.enable() def test_null_timer_is_disabled(null_timer): assert not null_timer.enabled def test_clock(timer): with timer.clock("label"): # small arbitrary computation task to time time.sleep(0.1) times = timer.times assert "label" in times assert len(times) == 1 assert abs(times["label"] - 0.1) < 1e-2 assert timer.hits["label"] == 1 assert len(timer.hits) == 1 def test_start_twice(timer): """cannot call start twice consecutively with no stop""" timer.start("label") with pytest.raises(ValueError) as err: timer.start("label") assert "clock already started for 'label'" in str(err.value) def test_clock_in_clock(timer): """should not be able to create a given clock inside itself""" with timer.clock("label"): with pytest.raises(ValueError) as err: with timer.clock("label"): pass assert "clock already started for 'label'" in str(err.value) def test_consecutive_start_stops(timer): """total time increases with consecutive clock blocks""" timer.start("label") time.sleep(0.01) timer.stop("label") previous_time = timer.times["label"] for i in range(5): timer.start("label") time.sleep(0.01) timer.stop("label") assert timer.times["label"] >= previous_time + 0.01 previous_time = timer.times["label"] assert timer.hits["label"] == 6 def test_consecutive_clocks(timer): """total time increases with consecutive clock blocks""" with timer.clock("label"): time.sleep(0.01) previous_time = timer.times["label"] for i in range(5): with timer.clock("label"): time.sleep(0.01) assert timer.times["label"] >= previous_time + 0.01 previous_time = timer.times["label"] assert timer.hits["label"] == 6 @pytest.mark.parametrize( "ops, result", [ ([], True), (["enable"], True), (["disable"], False), (["disable", "enable"], True), (["disable", "disable"], False), ], ) def test_enable_disable(timer, ops, result): for op in ops: getattr(timer, op)() assert timer.enabled == result def test_disabled_timer_does_not_add_key(timer): timer.disable() with timer.clock("label1"): time.sleep(0.01) assert len(timer.times) == 0 with timer.clock("label2"): time.sleep(0.01) assert len(timer.times) == 0 assert len(timer.hits) == 0 def test_disabled_timer_does_not_add_time(timer): with timer.clock("label"): time.sleep(0.01) initial_time = timer.times["label"] timer.disable() with timer.clock("label"): time.sleep(0.01) assert timer.times["label"] == initial_time assert timer.hits["label"] == 1 @pytest.fixture(params=["clean", "one_label", "two_labels"]) def used_timer(request, timer): if request.param == "clean": return timer elif request.param == "one_label": with timer.clock("label1"): time.sleep(0.01) return timer elif request.param == "two_labels": with timer.clock("label1"): time.sleep(0.01) with timer.clock("label2"): time.sleep(0.01) return timer def test_timer_reset(used_timer): used_timer.reset() assert len(used_timer.times) == 0 assert len(used_timer.hits) == 0
StarcoderdataPython
1777769
<gh_stars>0 import scrapy import regex from bs4 import BeautifulSoup import urllib import pandas class QuotesSpider(scrapy.Spider): name = "CO_Spider" Search_Url = r"http://www.coloradoshines.com/search?location={0}" Main_Url = r"http://www.coloradoshines.com/search" Detail_Url = r"http://www.coloradoshines.com/program_details?id={0}" Filter_Field='ID' custom_settings = { 'ITEM_PIPELINES': { 'First_Spider.pipelines.DuplicatesPipeline': 100 }, 'DOWNLOADER_MIDDLEWARES': { 'First_Spider.middlewares.More_Error_Logged': 200, }, 'ROBOTSTXT_OBEY':False, } Get_ID = regex.compile(r'(?<=id=).*?$', regex.IGNORECASE) Get_Text = regex.compile(r'(?<=\n\s*)\S.*?\S?(?=\n)', regex.IGNORECASE) Get_Title = regex.compile(r'(^|\n).*?(?=:\s?)', regex.IGNORECASE) Get_Address = regex.compile('(?<=^|\n).*?(?=,)', regex.IGNORECASE) Get_City = regex.compile(r'(?<=,\s*?)\S.*?\S?(?=,)', regex.IGNORECASE) Get_State = regex.compile(r'(?<=,\s*?)\S[^,]*?[^,\s](?=\s+\d+)', regex.IGNORECASE) Get_Code = regex.compile(r'(?<=\s*?)\d+$', regex.IGNORECASE) Get_Rating=regex.compile(r'(?<=rating-)\d*?$',regex.IGNORECASE) Params = "page%3AsearchForm=page%3AsearchForm&page%3AsearchForm%3Aj_id120%3A1%3Aj_id128=page%3AsearchForm%3Aj_id120%3A1%3Aj_id128&pagenumber={0}&com.salesforce.visualforce.ViewState={1}&com.salesforce.visualforce.ViewStateVersion={2}&com.salesforce.visualforce.ViewStateMAC={3}" Header ={'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'www.coloradoshines.com'} try: List_Zip_Url=r"C:\Users\MyPC\Desktop\List ZIP.csv" List_Zip=pandas.read_csv(List_Zip_Url) except:pass def Filter_Text_From_Collection(self, Text_Collection): for line in Text_Collection: try: return self.Get_Text.search(line).group() except: continue return None def Try_Assign(self,Regex_Expression,Search_String,Orientaton="Search",Pos=0): if Regex_Expression.search(Search_String): if Orientaton=="Search":return Regex_Expression.search(Search_String).group() elif Orientaton=="Findall" and Pos+1<=len(Regex_Expression.findall(Search_String)):return Regex_Expression.findall(Search_String)[Pos] return None def start_requests(self): for index,Line in self.List_Zip.iterrows(): yield scrapy.Request(url=self.Search_Url.format(Line['ZIP']),callback=self.parse,meta={'Referer':self.Search_Url.format(Line['ZIP'])}) def parse(self,response): Current_Page=response.meta.get('Current_Page') Referer = response.meta.get('Referer') Viewstate_Token=response.meta.get('Viewstate_Token') Viewstate_Version = response.meta.get('Viewstate_Version') Viewstate_MAC = response.meta.get('Viewstate_MAC') self.Header['Referer']=Referer if not Current_Page: Current_Page=1 Viewstate_Token = urllib.parse.quote_plus(response.css('input[id="com.salesforce.visualforce.ViewState"]::attr(value)').extract_first()) Viewstate_Version = urllib.parse.quote_plus(response.css('input[id="com.salesforce.visualforce.ViewStateVersion"]::attr(value)').extract_first()) Viewstate_MAC = urllib.parse.quote_plus(response.css('input[id="com.salesforce.visualforce.ViewStateMAC"]::attr(value)').extract_first()) ID_Collection = response.css('.view-details::attr(href)').extract() if len(ID_Collection)==0:return for ID in ID_Collection: ID_Num=self.Get_ID.search(ID).group() yield scrapy.Request(url=self.Detail_Url.format(ID_Num),meta={'ID_Num':ID_Num},callback=self.parse_detail) Next_String=response.css('ul.pagination>li.next').extract_first() if Next_String: Current_Page=Current_Page+1 yield scrapy.Request(url=self.Main_Url,method='POST',headers=self.Header,callback=self.parse, body=self.Params.format(str(Current_Page),Viewstate_Token,Viewstate_Version,Viewstate_MAC), meta={'Current_Page':Current_Page,'Referer':Referer, 'Viewstate_Token':Viewstate_Token,'Viewstate_Version':Viewstate_Version,'Viewstate_MAC':Viewstate_MAC } ) def parse_detail(self,response): Temp_Dict=dict() Whole_Address = response.css('.field-address::text').extract_first() ID_Num=response.meta.get('ID_Num') Rate_String = response.css('p.result-rating>span>span::attr(class)').extract_first() if Rate_String:Temp_Dict['QUALITY_RATING']=self.Try_Assign(self.Get_Rating,Rate_String) Temp_Dict['ID']=ID_Num Temp_Dict['URL']=self.Detail_Url.format(ID_Num) Temp_Dict['ADDRESS']=self.Try_Assign(self.Get_Address,Whole_Address) Temp_Dict['CITY'] = self.Try_Assign(self.Get_City,Whole_Address) Temp_Dict['STATE'] = self.Try_Assign(self.Get_State,Whole_Address) Temp_Dict['ZIP'] = self.Try_Assign(self.Get_Code,Whole_Address) Temp_Dict['PHONE'] = response.css('.field-phone>a::text').extract_first() Temp_Dict['WEBSITE'] = response.css('.field-website>span>a::text').extract_first() Temp_Dict['BUSINESS_NAME']=response.css('.right-content>h1::text').extract_first() Collection = response.css('.field-name-field-care>p::text').extract() Temp_Dict['CARE_SETTING']=self.Filter_Text_From_Collection(Collection) Collection = response.css('.field-name-field-age>p::text').extract() Temp_Dict['AGES'] = self.Filter_Text_From_Collection(Collection) Collection = response.css('.field-name-field-info>p').extract() for Field in Collection: Soup = BeautifulSoup(Field, 'html.parser') Title = self.Try_Assign(self.Get_Title,self.Try_Assign(self.Get_Text,Soup.text,"Findall")) Value = self.Try_Assign(self.Get_Text,Soup.text,"Findall",1) Temp_Dict[Title] = Value yield Temp_Dict
StarcoderdataPython
3242366
<gh_stars>1-10 from grit.common.model.core.rich_version import RichVersion class LineageGraphVersion(RichVersion): def __init__(self, json_payload): super().__init__(json_payload) self._lineage_graph_id = json_payload.get('lineageGraphId', 0) self._lineage_edge_version_ids = json_payload.get('lineageEdgeVersionIds', []) @classmethod def from_lineage_graph_version(cls, _id, other_lineage_graph_version): return LineageGraphVersion.from_lineage_graph_version_and_rich_version( _id, other_lineage_graph_version, other_lineage_graph_version ) @classmethod def from_lineage_graph_version_and_rich_version( cls, _id, other_rich_version, other_lineage_graph_version): return cls({ 'id': _id, 'tags': other_rich_version.get_tags(), 'structureVersionId': other_rich_version.get_structure_version_id(), 'reference': other_rich_version.get_reference(), 'referenceParameters': other_rich_version.get_parameters(), 'lineageGraphId': other_lineage_graph_version.get_lineage_graph_id(), 'lineageEdgeVersionIds': other_lineage_graph_version.get_lineage_edge_version_ids(), }) def get_lineage_graph_id(self): return self._lineage_graph_id def get_lineage_edge_version_ids(self): return self._lineage_edge_version_ids def __eq__(self, other): return ( isinstance(other, LineageGraphVersion) and self._lineage_graph_id == other._lineage_graph_id and self._lineage_edge_version_ids == other._lineage_edge_version_ids and super().__eq__(other) )
StarcoderdataPython
3337589
import base64 import os import smtplib from email.header import Header from email.mime.text import MIMEText import requests from lxml import etree requests = requests.session() # 设置变量开始 user_id = os.environ.get('login_account') # 教务系统登录账号 user_pwd = os.environ.get('password') # 教务系统登录密码 term = os.environ.get('score_term') # 查分学期 mail_user = os.environ.get("mail_account") # 邮箱账号 mail_pass = os.environ.get("mail_key") # 邮箱授权码 url_wan = "https://jiaowu3.nsmc.edu.cn/jsxsd/" id_base = str(base64.b64encode(user_id.encode('utf-8')))[2:-1] pwd_base = str(base64.b64encode(user_pwd.encode('utf-8')))[2:-1] user_encoded = "{}%%%{}".format(id_base, pwd_base) # 设置变量结束 def login(url): headers = { "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "accept-encoding": "gzip, deflate, br", "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6", "cache-control": "max-age=0", "content-length": "124", "content-type": "application/x-www-form-urlencoded", "origin": "https://jiaowu3.nsmc.edu.cn", "referer": "https://jiaowu3.nsmc.edu.cn/jsxsd/", "upgrade-insecure-requests": "1", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.67" } data = { 'userAccount': user_id, 'userPassword': <PASSWORD>, 'encoded': user_encoded } url_login = url + "xk/LoginToXk" _res = requests.post(url=url_login, headers=headers, data=data) def get_score(url): # 获得用户成绩 login(url) headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "Content-Type": "application/x-www-form-urlencoded", "Origin": "https://jiaowu3.nsmc.edu.cn", "Referer": "https://jiaowu3.nsmc.edu.cn/jsxsd/kscj/cjcx_query", "Upgrade-Insecure-Requests": "1", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.64" } data = {'kksj': {term}, 'kcxz': '', 'kcmc': '', 'xsfs': 'all'} url_post = url + "kscj/cjcx_list" response = requests.post(url=url_post, headers=headers, data=data) response.encoding = 'utf-8' score_html = response.text score_html = etree.HTML(score_html) # 格式化成绩单 score_dict = {} for i in range(2, 25): score_table = score_html.xpath('//table[@id="dataList"]/tr[{}]/td//text()'.format(i)) if len(score_table) == 0: break score_table[4] = score_table[4].replace('\r', '').replace('\n', '').replace('\t', '').replace(' ', '') score_dict[i - 2] = score_table a = "你%s学期的成绩为:\n" % term subject_name = [elem[3] for elem in score_dict.values()] subject_score = [elem[4] for elem in score_dict.values()] if len(score_dict) == 14: exam_property = [elem[11] for elem in score_dict.values()] subject_property = [elem[12] for elem in score_dict.values()] else: exam_property = [elem[10] for elem in score_dict.values()] subject_property = [elem[11] for elem in score_dict.values()] for _ in range(len(subject_name)): a += ("科目:%s 成绩:%s 考试性质:%s 课程属性:%s" % ( subject_name[_], subject_score[_], exam_property[_], subject_property[_])) + "\n" return a def mail(url): # 发送邮件 sendmsg = get_score(url) mail_host = "smtp.qq.com" # 设置服务器 sender = mail_user receivers = [mail_user] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 message = MIMEText(sendmsg) message['From'] = Header("GithubAction", 'utf-8') message['To'] = Header("user", 'utf-8') subject = 'Final Exam Score' message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号 smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) print("邮件发送成功") except smtplib.SMTPException: print("Error: 无法发送邮件") if __name__ == '__main__': mail(url_wan)
StarcoderdataPython
3334139
<gh_stars>1-10 #!/usr/bin/python # -*- coding: UTF-8 -*- # KagurazakaYashi import sys import urllib import urllib2 class Nikkiup2u3word: argv = [] #可以在init前配置此属性以接入使用 argumentdict = {} datasource = "" output = "" separate = "" def __init__(self): self.argv = sys.argv self.argumentdict = {} self.systemencoding = sys.getfilesystemencoding() #self.datasource = "http://127.0.0.1/nikkiup2u3_data/wardrobe.js" self.datasource = "http://seal100x.github.io/nikkiup2u3_data/wardrobe.js" self.output = "up2u3word.txt" self.separate = "\r\n" #显示关于信息 def about(self): print "\n奇迹暖暖词库合成脚本 v1.0 for py2\n如需帮助,请加入 -h 参数。\n神楽坂雅詩\n" #,self.argv[0] def help(self): self.about() print "参数说明:" print "python nikkiup2u3word.py <--help> <--source (url)> <--output (file)> <--separate (string)>" print "不加任何参数:全部参数按照默认值进行提取。" print "--help 或 -h 或 /? :显示此帮助文本。" print "--source 或 -s 或 /s <网址> :指定数据源。\n  默认值:"+self.datasource print "--output 或 -o 或 /o <文件路径> :指定输出到文件。\n  默认值:"+self.output print "--separate 或 -e 或 /e <分隔符>:修改分隔符。\n  默认值:Windows换行符(\\r\\n)" #程序起点 def start(self): if self.argumentparsing() == False: print "\n" exit(0) self.about() print "数据源:"+self.datasource print "文件路径:"+self.output print "分隔符:"+self.separate print "开始下载..." data = self.download() print "下载完成,正在解析..." data = self.analysis(data) data = self.compose(data) print "解析完成,写入文件..." self.save(data) print "完成。" #写入 def save(self,data): file(self.output, 'wb+').write(data) #合成 def compose(self,data): str1 = data[3] ii = 0 for i in range(4, len(data)): nstr = data[i] if nstr != "": str1 = str1+self.separate+data[i] ii=ii+1 print "数量:"+str(ii) return str1 #网络操作 def download(self): req = urllib2.Request(self.datasource) res_data = urllib2.urlopen(req) return res_data.read() #解析 def analysis(self,data): larr = data.split(';') larr = larr[0].split('\n') names = {} for i in range(0, len(larr)): nstr = larr[i][3:-3] darr = nstr.split(",") name = darr[0][1:-1] names[i] = name return names #完全解析 # for j in range(0, len(darr)): # pr = darr[j][1:-1] # print pr #处理参数 def argumentparsing(self): argvlen = len(self.argv) if (argvlen == 1): return True nk = "" #当前得到的参数Key nv = "" #当前得到的参数value if argvlen > 1: for i in range(1, len(self.argv)): nowp = self.argv[i] #当前参数 if nk == "": #应输入nk if self.argumentiskey(nowp) == False: return False nk = nowp else: #应输入nv if self.argumentiskey(nowp) == True: #这是下一个nk self.argumentdict[nk] = nv nk = nowp nv = "" else: nv = nowp #print "nk =",nk,"nv =",nv self.argumentdict[nk] = nv nk = "" nv = "" if nk != "": self.argumentdict[nk] = nv return self.argumentkv() #判断是否为key def argumentiskey(self,key): onechar = key[0] if onechar == "-" or onechar == "/": return True return False #处理nknv def argumentkv(self): keys = self.argumentdict.keys() for ni in range(0, len(keys)): nk = keys[ni] nv = self.argumentdict[nk] if nk == "--help" or nk == "-h" or nk == "/?": self.help() return False elif nk == "--source" or nk == "-s" or nk == "/s": self.datasource = nv elif nk == "--output" or nk == "-o" or nk == "/o": self.output = nv elif nk == "--separate" or nk == "-e" or nk == "/e": self.separate = nv #程序执行 pobj = Nikkiup2u3word() pobj.start() exit()
StarcoderdataPython
1682686
import os import shutil import subprocess import sys from pathlib import Path URL_PREFIX = "aurin://" ILLEGAL_PKG_NAME_CONTENTS = (".", "..", "/") temp_dir = Path("/var", "tmp", "aurin") def error_out(message: str): print(f"ERROR: {message}", file=sys.stderr) sys.exit(1) def notify(icon: str, title: str, message: str): # Respect the user's settings by querying the variable that is already set. # If not, use the value computed by the script xdg_runtime_dir = os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}") subprocess.check_call( [ "notify-send", "-i", icon, title, message ], env={ "XDG_RUNTIME_DIR": xdg_runtime_dir } ) if len(sys.argv) < 1: error_out(f"Invalid number of arguments, you must provide a package name") input_pkg_name = sys.argv[1] # Only accept input values that are an actual valid URI if not input_pkg_name.startswith(URL_PREFIX): error_out(f"Input URL {input_pkg_name} does not start with {URL_PREFIX}") # Use slicing to extract the package name. pkg_name = input_pkg_name[len(URL_PREFIX):] # Deny certain characters to avoid path pollution that can enable path traversal and such. for thing in ILLEGAL_PKG_NAME_CONTENTS: if thing in pkg_name: error_out(f"Illegal character pattern {thing} in package name {pkg_name}") # Make sure the temporary directory for aurin always exists temp_dir.mkdir(parents=True, exist_ok=True) build_root = temp_dir / pkg_name subprocess.check_call([ "git", "clone", f"https://aur.archlinux.org/{pkg_name}.git", str(build_root) ]) subprocess.check_call( [ "bash", "/opt/aurin/installpkg.sh", str(build_root) ], cwd=build_root ) os.chdir(os.environ.get("HOME", "/")) shutil.rmtree(build_root, ignore_errors=True) notify("/opt/aurin/aurin48.png", "Install Successful", f"{pkg_name} has been installed!")
StarcoderdataPython
3311165
<gh_stars>0 import unittest from app import app import json from app.views import user_info class CreateUserTestCase(unittest.TestCase): def setUp(self): self.client = app.test_client self.user = {"username": "patrick", "password": "<PASSWORD>!@#", "first_name": "patrick", "last_name": "migot"} def tearDown(self): """ clear data after every test""" user_info.users.clear() def test_user_creation(self): """ Test API can create a user (POST request) """ initial_count = len(user_info.users) res = self.client().post('/api/v1/register', data=json.dumps(self.user), headers={"content-type": 'application/json'}) final_count = len(user_info.users) self.assertEqual(res.status_code, 201) self.assertEqual(final_count - initial_count, 1) def test_cannot_create_duplicate_user(self): """ Tests that duplicate usernames cannot be created """ user1 = self.client().post('/api/v1/register', data=json.dumps(self.user), content_type='application/json') user2 = self.client().post('/api/v1/register', data=json.dumps(self.user), content_type='application/json') self.assertIn('Sorry!! Username taken!', str(user2.data)) def test_details_missing(self): """test username and password required""" res = self.client().post('/api/v1/register', data=json.dumps({ "username": " ", "password": " ", "first_name": "patrick", "last_name": "migot" }), headers={"content-type": 'application/json'}) self.assertIn('username or password missing' ,str(res.data)) def test_bad_request(self): """test returns bad request if all fields not available""" res = self.client().post('/api/v1/register', data=json.dumps({"username": "migot", "last_name": "patrick"}), headers={"content-type": 'application/json'}) self.assertEqual(res.status_code,400) self.assertIn("check you are sending correct information",str(res.data)) def test_password_validation(self): """Test password must be 6-20 characters, alphanumeric""" res = self.client().post('/api/v1/register', data=json.dumps({ "username": "patrick", "password":"<PASSWORD>", "first_name": "patrick", "last_name": "migot" }), headers={"content-type": 'application/json'}) self.assertEqual(res.status_code, 406) self.assertIn( "Password must be 6-20 Characters", str(res.data) ) if __name__ == "__main__": unittest.main()
StarcoderdataPython
4823895
<filename>tests/integration/__init__.py altapay_account = '' altapay_password = '' altapay_url = '' altapay_test_terminal_name = '' altapay_invoice_test_terminal_name = '' altapay_contract_identifier = ''
StarcoderdataPython
160428
from django.urls import path from . import views urlpatterns = [ path('', views.about_page, name='about_page_uid'), path('hidden/', views.hidden_about, name='about_page_hidden_uid'), ]
StarcoderdataPython
157482
#!/usr/bin/env python # -*- coding: utf-8 -*- class PodiumUser(object): """ Object that represents a particular User. **Attributes:** **user_id** (int): User id **uri** (string): URI for the User. **username** (string): The User's username. **description** (string): The User's description. **avatar_url** (string): User's avatar image url. **links** (list): 3rd party links for the user. **friendships_uri** (string): URI to friends list. **followers_uri** (string): URI to followers list. **friendship_uri** (string): If this User has been friended **events_uri** (string): URI to events for this user **venues_uri** (string): URI to venues this user particiated at by the user this attr will have a value, otherwise None. Defaults to None. """ def __init__(self, user_id, uri, username, description, avatar_url, profile_image_url, links, friendships_uri, followers_uri, friendship_uri, events_uri, venues_uri): self.user_id = user_id self.uri = uri self.username = username self.description = description self.avatar_url = avatar_url self.profile_image_url = profile_image_url self.links = links self.friendships_uri = friendships_uri self.followers_uri = followers_uri self.friendship_uri = friendship_uri self.events_uri = events_uri self.venues_uri = venues_uri def get_user_from_json(json): """ Returns a PodiumUser object from the json dict received from podium api. Args: json (dict): Dict of data from REST api Return: PodiumUser: The PodiumUser object for the data. """ return PodiumUser(json['id'], json['URI'], json['username'], json['description'], json['avatar_url'], json['profile_image_url'], json['links'], json['friendships_uri'], json['followers_uri'], json.get("friendship_uri", None), json['events_uri'], json['venues_uri'] )
StarcoderdataPython
165946
from unittest import mock, TestCase from mort.download_utils import get_filename_from_url, download class TestUtils(TestCase): URL = "https://www.browserstack.com/screenshots/fdd01e6683e0474ede370b753f870542f364f8ba/" + \ "android_Google-Nexus-6_5.0_portrait.jpg" def test_get_filename_from_url(self): self.assertEqual( "android_Google-Nexus-6_5.0_portrait.jpg", get_filename_from_url(self.URL)) @mock.patch("httplib2.Http.request") def test_download(self, request): request.return_value = (None, b"abc") file_path = download(self.URL, "/tmp") self.assertEqual("/tmp/android_Google-Nexus-6_5.0_portrait.jpg", file_path)
StarcoderdataPython
109412
<gh_stars>10-100 from setuptools import setup, find_packages, Command import re import sys import subprocess install_requires = [] pyversion = sys.version_info[:2] def read_module_contents(): with open('ceph_medic/__init__.py') as f: return f.read() module_file = read_module_contents() metadata = dict(re.findall("__([a-z]+)__\s*=\s*'([^']+)'", module_file)) long_description = open('README.rst').read() version = metadata['version'] class BumpCommand(Command): """ Bump the __version__ number and commit all changes. """ user_options = [('version=', 'v', 'version number to use')] def initialize_options(self): new_version = metadata['version'].split('.') new_version[-1] = str(int(new_version[-1]) + 1) # Bump the final part self.version = ".".join(new_version) def finalize_options(self): pass def run(self): try: print('old version: %s new version: %s' % (metadata['version'], self.version)) raw_input('Press enter to confirm, or ctrl-c to exit >') except KeyboardInterrupt: raise SystemExit("\nNot proceeding") old = "__version__ = '%s'" % metadata['version'] new = "__version__ = '%s'" % self.version module_file = read_module_contents() with open('ceph_medic/__init__.py', 'w') as fileh: fileh.write(module_file.replace(old, new)) # Commit everything with a standard commit message cmd = ['git', 'commit', '-a', '-m', 'version %s' % self.version] print(' '.join(cmd)) subprocess.check_call(cmd) class ReleaseCommand(Command): """ Tag and push a new release. """ user_options = [('sign', 's', 'GPG-sign the Git tag and release files')] def initialize_options(self): self.sign = False def finalize_options(self): pass def run(self): # Create Git tag tag_name = 'v%s' % version cmd = ['git', 'tag', '-a', tag_name, '-m', 'version %s' % version] if self.sign: cmd.append('-s') print(' '.join(cmd)) subprocess.check_call(cmd) # Push Git tag to origin remote cmd = ['git', 'push', 'origin', tag_name] print(' '.join(cmd)) subprocess.check_call(cmd) # Push package to pypi cmd = ['python', 'setup.py', 'sdist', 'upload'] if self.sign: cmd.append('--sign') print(' '.join(cmd)) #subprocess.check_call(cmd) # Push master to the remote cmd = ['git', 'push', 'origin', 'master'] print(' '.join(cmd)) subprocess.check_call(cmd) setup( name='ceph-medic', version=version, packages=find_packages(), author='<NAME>', author_email='<EMAIL>', description='detect common issues with ceph clusters', long_description=long_description, license='MIT', keywords='ceph doctor', url="https://github.com/ceph/ceph-medic", zip_safe=False, install_requires=[ 'execnet', 'tambo', 'remoto>=1.1.2', ] + install_requires, tests_require=[ 'pytest >=2.1.3', 'tox', 'mock', ], scripts=['bin/ceph-medic'], cmdclass={'bump': BumpCommand, 'release': ReleaseCommand}, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Build Tools', 'Topic :: Utilities', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ] )
StarcoderdataPython
173721
""" Mocsár Environment File name: envs/gmocsar.py Author: <NAME> Date created: 3/27/2020 """ from rlcard3 import models from rlcard3.envs.env import Env from rlcard3.games.mocsar.game import MocsarGame as Game from rlcard3.games.mocsar.utils import action_to_string, \ string_to_action, payoff_func, print_state, encode_to_obs from typing import List class MocsarEnv(Env): """ GinRummy Environment """ state_shape: List[int] # Dimensions of state numpy array def __init__(self, config): self.game = Game() self.state_shape = [3, 9, 14] super().__init__(config=config) def _extract_state(self, state): # 200213 don't use state ??? """ Extract useful information from state for RL. Must be implemented in the child class. numpy(3,9,14) Menaing: x,y,z z: 1/0, 1 means, the hand contains y amount of card. y: rank of cards in some hand. x=0: player's hand x=1: others hand x=2: target x>2: history, not implemented.... :param state: dict, the raw state :return: dict: 'obs':the extracted state, numpy.array, 'legal_actions': list of actions """ obs = encode_to_obs(state=state) extracted_state = {'obs': obs, 'legal_actions': self._get_legal_actions(), 'is_extract': True # State is extracted> } return extracted_state def get_payoffs(self): """ Get the payoffs of players. Must be implemented in the child class. First one scores 1, Last one scores 0. Other ith player scores 0.5 ^^i :return: A list of payoffs for each player. """ num_players = self.game.num_players # winnersben a győzelmek sorrendje van # List indexed by PlayerID instead of OrderId, pl [1,3,2,0] win_id = [self.game.players.winners.index(i) for i in range(num_players)] # win_id-ben, meg az, hogy az adott indexű játékos hányadik, pl [3,0,2,1], mivel a 0-ik indexű játékos utolsó=3 payoffs = [payoff_func(position=win_id[i], num_players=num_players) for i in range(num_players)] return payoffs def _decode_action(self, action_id): """ Decode Action id to the action in the game. :param action_id: The id of the action :return: The action that will be passed to the game engine. """ return action_to_string(action=action_id) def _get_legal_actions(self): """ Get all legal actions for current state. :return: A list of legal actions' id. """ return [string_to_action(action) for action in self.game.get_legal_actions()] def _load_model(self): """ Load pretrained/rule model :return: A Model object """ return models.load('mocsar-rule-v1', num_players=self.game.get_player_num()) def print_state(self, player: int): """ Print out the state of a given player :param player: Player Id to print """ state = self.game.get_state(player) print_state(state) def print_result(self, player): """ Print the game result when the game is over :param player: Player Id to print """ payoffs = self.get_payoffs() for player_ in self.game.players.players: print(f"Player {player_.__str__()} : points {payoffs[player_.player_id]}") @staticmethod def print_action(action: str): """ Print out an action in a nice form :param action: Code of the action """ if type(action) is tuple: action, _ = action print(f"\nAction code:{string_to_action(action)}, action:{action}")
StarcoderdataPython
3339625
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import logout from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .models import Viagem, Motorista, Veiculo from .form import VeiculoForm, MotoristaForm, ViagemForm from docx import Document def home(request): # Ordenadas as viagens por data, da mais recente para a mais antiga viagens = Viagem.objects.all().order_by('-data') veiculos = Veiculo.objects.all().order_by('nome') motoristas = Motorista.objects.all().order_by('nome') termo_busca = request.POST.get('pesquisa') page = request.GET.get('page', 1) if termo_busca != None: viagens = viagens.filter(motorista__nome__icontains=termo_busca) | viagens.filter(veiculo__nome__icontains=termo_busca) | viagens.filter(veiculo__marca__icontains=termo_busca) | viagens.filter(veiculo__tipo_veiculo__icontains=termo_busca) | viagens.filter(observacoes__icontains=termo_busca) veiculos = veiculos.filter(nome__icontains=termo_busca) | veiculos.filter(tipo_veiculo__icontains=termo_busca) | veiculos.filter(marca__icontains=termo_busca) | veiculos.filter(ano__icontains=termo_busca) | veiculos.filter(placa__icontains=termo_busca) | veiculos.filter(observacoes__icontains=termo_busca) motoristas = motoristas.filter(nome__icontains=termo_busca) | motoristas.filter(observacoes__icontains=termo_busca) # Filtro por data sempre sera aplicado independente da busca data_inicial = request.POST.get('data_inicial') data_final = request.POST.get('data_final') if data_inicial and data_final != '': viagens = viagens.filter(data__range=[data_inicial, data_final]) elif data_inicial != '' and data_final == '': viagens = viagens.filter(data__gte=data_inicial) elif data_inicial == '' and data_final != '': viagens = viagens.filter(data__lte=data_final) # Nao alterar - Lista ordenada para documento docx viagens_docx = viagens.order_by('data') # Paginador paginador_viagem = Paginator(viagens, 4) paginador_veiculo = Paginator(veiculos, 3) paginador_motorista = Paginator(motoristas, 3) try: viagens = paginador_viagem.page(page) except PageNotAnInteger: viagens = paginador_viagem.page(1) except EmptyPage: viagens = Viagem.objects.filter(id__contains='s1fs3a51f53as1f5s1a5f31') try: veiculos = paginador_veiculo.page(page) except PageNotAnInteger: veiculos = paginador_veiculo.page(1) except EmptyPage: veiculos = Veiculo.objects.filter(nome__contains='s1fs3a51f53as1f5s1a5f31') try: motoristas = paginador_motorista.page(page) except PageNotAnInteger: motoristas = paginador_motorista.page(1) except EmptyPage: motoristas = Motorista.objects.filter(nome__contains='s1fs3a51f53as1f5s1a5f31') # Criando relatorio das buscas em docx document = Document() for motorista in motoristas: document.add_heading(f'{motorista}', 0) resultados_tabela = [] for viagem in viagens_docx: if viagem.motorista == motorista: resultados_tabela.append(( viagem.data.strftime("%d/%m/%Y"), f"{viagem.saida.strftime('%H:%M')} ~ {viagem.retorno.strftime('%H:%M')}", viagem.observacoes )) tabela = document.add_table(rows=1, cols=3) tabela.style = 'TableGrid' hdr_cells = tabela.rows[0].cells hdr_cells[0].paragraphs[0].add_run('Data').bold = True hdr_cells[1].paragraphs[0].add_run('Horario').bold = True hdr_cells[2].paragraphs[0].add_run('Observações').bold = True for data, horario, observacoes in resultados_tabela: row_cells = tabela.add_row().cells row_cells[0].text = str(data) row_cells[1].text = horario row_cells[2].text = observacoes document.add_paragraph('') document.save('staticfiles/docx/relatorio.docx') document.save('static/docx/relatorio.docx') return render(request, 'fleet/index.html', { 'viagens': viagens, 'veiculos': veiculos, 'motoristas': motoristas, 'termo_busca': termo_busca }) def meu_logout(request): logout(request) return redirect('home') def teste(request): return redirect('home') @login_required def nova_viagem(request): form = ViagemForm(request.POST or None) if form.is_valid(): form.save() return redirect('home') return render(request, 'fleet/formularios/form_cadastro.html', {'form': form}) @login_required def atualizar_viagem(request, id): viagem = get_object_or_404(Viagem, pk=id) form = ViagemForm(request.POST or None, instance=viagem) if form.is_valid(): form.save() return redirect('home') return render(request, 'fleet/formularios/form_cadastro.html', {'form': form}) @login_required def apagar_viagem(request, id): viagem = Viagem.objects.get(pk=id) if request.method == 'POST': viagem.delete() return redirect('home') return render(request, 'fleet/delete/confirmacao.html', {'viagem': viagem}) @login_required def novo_motorista(request): form = MotoristaForm(request.POST or None) if form.is_valid(): form.save() return redirect('home') return render(request, 'fleet/formularios/form_cadastro.html', {'form': form}) @login_required def atualizar_motorista(request, id): motorista = get_object_or_404(Motorista, pk=id) form = MotoristaForm(request.POST or None, instance=motorista) if form.is_valid(): form.save() return redirect('home') return render(request, 'fleet/formularios/form_cadastro.html', {'form': form}) @login_required def apagar_motorista(request, id): motorista = Motorista.objects.get(pk=id) if request.method == "POST": motorista.delete() return redirect('home') return render(request, 'fleet/delete/confirmacao.html', {'motorista': motorista}) @login_required def novo_veiculo(request): form = VeiculoForm(request.POST or None) if form.is_valid(): form.save() return redirect('home') return render(request, 'fleet/formularios/form_cadastro.html', {'form': form}) @login_required def atualizar_veiculo(request, id): veiculo = get_object_or_404(Veiculo, pk=id) form = VeiculoForm(request.POST or None, instance=veiculo) if form.is_valid(): form.save() return redirect('home') return render(request, 'fleet/formularios/form_cadastro.html', {'form': form}) @login_required def apagar_veiculo(request, id): veiculo = Veiculo.objects.get(pk=id) if request.method == 'POST': veiculo.delete() return redirect('home') return render(request, 'fleet/delete/confirmacao.html', {'veiculo': veiculo})
StarcoderdataPython
1606074
<reponame>DumisaniZA/Axelrod<filename>axelrod/tournament.py<gh_stars>10-100 import multiprocessing from game import * from result_set import * from round_robin import * import logging class Tournament(object): game = Game() def __init__(self, players, name='axelrod', game=None, turns=200, repetitions=10, processes=None, prebuilt_cache=False): self.name = name self.players = players self.nplayers = len(self.players) if game is not None: self.game = game self.turns = turns self.repetitions = repetitions self.processes = processes self.prebuilt_cache=prebuilt_cache self.logger = logging.getLogger(__name__) self.result_set = ResultSet( players=players, turns=turns, repetitions=repetitions) self.deterministic_cache = {} def play(self): payoffs_list = [] if self.processes is None: self.run_serial_repetitions(payoffs_list) else: if len(self.deterministic_cache) == 0 or not self.prebuilt_cache: self.logger.debug('Playing first round robin to build cache') payoffs = self.play_round_robin() payoffs_list.append(payoffs) self.repetitions -= 1 self.run_parallel_repetitions(payoffs_list) self.result_set.finalise(payoffs_list) return self.result_set def run_serial_repetitions(self, payoffs_list): self.logger.debug('Playing %d round robins' % self.repetitions) for repetition in range(self.repetitions): payoffs = self.play_round_robin() payoffs_list.append(payoffs) return True def run_parallel_repetitions(self, payoffs_list): # At first sight, it might seem simpler to use the multiprocessing Pool # Class rather than Processes and Queues. However, Pool can only accept # target functions which can be pickled and instance methods cannot. work_queue = multiprocessing.Queue() done_queue = multiprocessing.Queue() if self.processes < 2 or self.processes > multiprocessing.cpu_count(): workers = multiprocessing.cpu_count() else: workers = self.processes for repetition in range(self.repetitions): work_queue.put(repetition) self.logger.debug( 'Playing %d round robins with %d parallel processes' % (self.repetitions, workers)) self.start_workers(workers, work_queue, done_queue) self.process_done_queue(workers, done_queue, payoffs_list) return True def start_workers(self, workers, work_queue, done_queue): for worker in range(workers): process = multiprocessing.Process( target=self.worker, args=(work_queue, done_queue)) work_queue.put('STOP') process.start() return True def process_done_queue(self, workers, done_queue, payoffs_list): stops = 0 while stops < workers: payoffs = done_queue.get() if payoffs == 'STOP': stops += 1 else: payoffs_list.append(payoffs) return True def worker(self, work_queue, done_queue): for repetition in iter(work_queue.get, 'STOP'): payoffs = self.play_round_robin(cache_mutable=False) done_queue.put(payoffs) done_queue.put('STOP') return True def play_round_robin(self, cache_mutable=True): round_robin = RoundRobin( players=self.players, game=self.game, turns=self.turns, deterministic_cache=self.deterministic_cache, cache_mutable=cache_mutable) payoffs = round_robin.play() return payoffs
StarcoderdataPython
83244
import torch from morphosearch.core import Explorer from tqdm import tqdm class RandomExplorer(Explorer): """Performs random explorations of a system.""" def run(self, n_exploration_runs): print('Exploration: ') for run_idx in tqdm(range(n_exploration_runs)): if run_idx not in self.data: policy_parameters = self.system.sample_policy_parameters() self.system.reset(policy=policy_parameters) with torch.no_grad(): observations = self.system.run() # save results self.db.add_run_data(id=run_idx, policy_parameters=policy_parameters, observations=observations) if self.db.config.save_rollout_render: self.system.render_rollout(observations, filepath=os.path.join(self.db.config.db_directory, f'run_{run_idx}_rollout'))
StarcoderdataPython
15523
<reponame>feevos/incubator-mxnet<gh_stars>0 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # coding: utf-8 """Context management API of mxnet.""" from __future__ import absolute_import import threading import warnings from .base import classproperty, with_metaclass, _MXClassPropertyMetaClass class Context(with_metaclass(_MXClassPropertyMetaClass, object)): """Constructs a context. MXNet can run operations on CPU and different GPUs. A context describes the device type and ID on which computation should be carried on. One can use mx.cpu and mx.gpu for short. See also ---------- `How to run MXNet on multiple CPU/GPUs <http://mxnet.io/faq/multi_devices.html>` for more details. Parameters ---------- device_type : {'cpu', 'gpu'} or Context. String representing the device type. device_id : int (default=0) The device id of the device, needed for GPU. Note ---- Context can also be used as a way to change the default context. Examples -------- >>> # array on cpu >>> cpu_array = mx.nd.ones((2, 3)) >>> # switch default context to GPU(2) >>> with mx.Context(mx.gpu(2)): ... gpu_array = mx.nd.ones((2, 3)) >>> gpu_array.context gpu(2) One can also explicitly specify the context when creating an array. >>> gpu_array = mx.nd.ones((2, 3), mx.gpu(1)) >>> gpu_array.context gpu(1) """ # static class variable _default_ctx = threading.local() devtype2str = {1: 'cpu', 2: 'gpu', 3: 'cpu_pinned', 5: 'cpu_shared'} devstr2type = {'cpu': 1, 'gpu': 2, 'cpu_pinned': 3, 'cpu_shared': 5} def __init__(self, device_type, device_id=0): if isinstance(device_type, Context): self.device_typeid = device_type.device_typeid self.device_id = device_type.device_id else: self.device_typeid = Context.devstr2type[device_type] self.device_id = device_id self._old_ctx = None @property def device_type(self): """Returns the device type of current context. Examples ------- >>> mx.context.current_context().device_type 'cpu' >>> mx.current_context().device_type 'cpu' Returns ------- device_type : str """ return Context.devtype2str[self.device_typeid] def __hash__(self): """Compute hash value of context for dictionary lookup""" return hash((self.device_typeid, self.device_id)) def __eq__(self, other): """Compares two contexts. Two contexts are equal if they have the same device type and device id. """ return isinstance(other, Context) and \ self.device_typeid == other.device_typeid and \ self.device_id == other.device_id def __str__(self): return '%s(%d)' % (self.device_type, self.device_id) def __repr__(self): return self.__str__() def __enter__(self): if not hasattr(Context._default_ctx, "value"): Context._default_ctx.value = Context('cpu', 0) self._old_ctx = Context._default_ctx.value Context._default_ctx.value = self return self def __exit__(self, ptype, value, trace): Context._default_ctx.value = self._old_ctx #pylint: disable=no-self-argument @classproperty def default_ctx(cls): warnings.warn("Context.default_ctx has been deprecated. " "Please use Context.current_context() instead. " "Please use test_utils.set_default_context to set a default context", DeprecationWarning) if not hasattr(Context._default_ctx, "value"): cls._default_ctx.value = Context('cpu', 0) return cls._default_ctx.value @default_ctx.setter def default_ctx(cls, val): warnings.warn("Context.default_ctx has been deprecated. " "Please use Context.current_context() instead. " "Please use test_utils.set_default_context to set a default context", DeprecationWarning) cls._default_ctx.value = val #pylint: enable=no-self-argument # initialize the default context in Context Context._default_ctx.value = Context('cpu', 0) def cpu(device_id=0): """Returns a CPU context. This function is a short cut for ``Context('cpu', device_id)``. For most operations, when no context is specified, the default context is `cpu()`. Examples ---------- >>> with mx.cpu(): ... cpu_array = mx.nd.ones((2, 3)) >>> cpu_array.context cpu(0) >>> cpu_array = mx.nd.ones((2, 3), ctx=mx.cpu()) >>> cpu_array.context cpu(0) Parameters ---------- device_id : int, optional The device id of the device. `device_id` is not needed for CPU. This is included to make interface compatible with GPU. Returns ------- context : Context The corresponding CPU context. """ return Context('cpu', device_id) def cpu_pinned(device_id=0): """Returns a CPU pinned memory context. Copying from CPU pinned memory to GPU is faster than from normal CPU memory. This function is a short cut for ``Context('cpu_pinned', device_id)``. Examples ---------- >>> with mx.cpu_pinned(): ... cpu_array = mx.nd.ones((2, 3)) >>> cpu_array.context cpu_pinned(0) >>> cpu_array = mx.nd.ones((2, 3), ctx=mx.cpu_pinned()) >>> cpu_array.context cpu_pinned(0) Parameters ---------- device_id : int, optional The device id of the device. `device_id` is not needed for CPU. This is included to make interface compatible with GPU. Returns ------- context : Context The corresponding CPU pinned memory context. """ return Context('cpu_pinned', device_id) def gpu(device_id=0): """Returns a GPU context. This function is a short cut for Context('gpu', device_id). The K GPUs on a node are typically numbered as 0,...,K-1. Examples ---------- >>> cpu_array = mx.nd.ones((2, 3)) >>> cpu_array.context cpu(0) >>> with mx.gpu(1): ... gpu_array = mx.nd.ones((2, 3)) >>> gpu_array.context gpu(1) >>> gpu_array = mx.nd.ones((2, 3), ctx=mx.gpu(1)) >>> gpu_array.context gpu(1) Parameters ---------- device_id : int, optional The device id of the device, needed for GPU. Returns ------- context : Context The corresponding GPU context. """ return Context('gpu', device_id) def current_context(): """Returns the current context. By default, `mx.cpu()` is used for all the computations and it can be overridden by using `with mx.Context(x)` statement where x can be cpu(device_id) or gpu(device_id). Examples ------- >>> mx.current_context() cpu(0) >>> with mx.Context('gpu', 1): # Context changed in `with` block. ... mx.current_context() # Computation done here will be on gpu(1). ... gpu(1) >>> mx.current_context() # Back to default context. cpu(0) Returns ------- default_ctx : Context """ if not hasattr(Context._default_ctx, "value"): Context._default_ctx.value = Context('cpu', 0) return Context._default_ctx.value
StarcoderdataPython
123979
class Solution1: def maxSubArray(self, nums: List[int]) -> int: total_max, total = -1e10, 0 for i in range( len(nums) ): if total > 0: total += nums[i] else: total = nums[i] if total > total_max: total_max = total return total_max class Solution2: ## divide and conquer approach def middlemax( self, nums, LL, mid, RR ): totalL, totalR, totalL_max, totalR_max = 0, 0, nums[mid], nums[mid+1] # Left for i in range( mid, LL-1, -1 ): totalL += nums[i] if( totalL_max < totalL ): totalL_max = totalL # Right for i in range( mid+1, RR+1 ): totalR += nums[i] if( totalR_max < totalR ): totalR_max = totalR return totalR_max + totalL_max def findmax( self, nums, LL, RR ): if LL >= RR: return nums[LL] mid = LL + (RR-LL)//2 mmax = self.middlemax( nums, LL, mid, RR ) lmax = self.findmax( nums, LL, mid ) rmax = self.findmax( nums, mid+1, RR ) return max( [mmax, lmax, rmax] ) def maxSubArray(self, nums: List[int]) -> int: Length = len(nums) return self.findmax( nums, 0, Length-1 )
StarcoderdataPython
89728
"""Setup script for SWITCH. Use "pip install --upgrade ." to install a copy in the site packages directory. Use "pip install --upgrade --editable ." to install SWITCH to be run from its current location. Optional dependencies can be added during the initial install or later by running a command like this: pip install --upgrade --editable .[advanced,database_access] Use "pip uninstall switch" to uninstall switch from your system. """ import os from setuptools import setup, find_packages # Get the version number. Strategy #3 from https://packaging.python.org/single_source_version/ version_path = os.path.join(os.path.dirname(__file__), 'switch_model', 'version.py') version = {} with open(version_path) as f: exec(f.read(), version) __version__ = version['__version__'] def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() setup( name='switch_model', version=__version__, maintainer='Switch Authors', maintainer_email='<EMAIL>', url='http://switch-model.org', license='Apache v2', platforms=["any"], description='SWITCH Power System Planning Model', long_description=read('README'), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Education', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX :: Linux', 'Operating System :: Unix', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', 'Topic :: Software Development :: Libraries :: Python Modules' ], packages=find_packages(include=['switch_model', 'switch_model.*']), keywords=[ 'renewable', 'power', 'energy', 'electricity', 'production cost', 'capacity expansion', 'planning', 'optimization' ], install_requires=[ 'Pyomo>=4.4.1', # We need a version that works with glpk 4.60+ 'testfixtures', # used for standard tests 'pandas', # used for input upgrades and testing that functionality ], extras_require={ # packages used for advanced demand response, progressive hedging 'advanced': ['numpy', 'scipy', 'rpy2', 'sympy'], 'plotting': ['ggplot'], 'database_access': ['psycopg2'] }, entry_points={ 'console_scripts': ['switch = switch_model.main:main'] }, )
StarcoderdataPython
1750897
handle = '20141103\ All\ IRD' def get_header(n_nodes): header = '\ #!/bin/sh \n\ #$ -S /bin/sh \n\ #$ -cwd \n\ #$ -V\n\ #$ -m e\n\ #$ -M <EMAIL> \n\ #$ -pe whole_nodes {0}\n\ #$ -l mem_free=2G\n\ #############################################\n\n'.format(n_nodes) return header import os import pickle as pkl import numpy as np def check_dirs(dirname): if dirname not in os.listdir(os.getcwd()): os.mkdir(dirname) else: pass check_dirs('shell_scripts') check_dirs('reassortant_edges') with open('20141103 All IRD Isolates for Source Pair Search.pkllist', 'r') as f: isolates = pkl.load(f) num_per_batch = 20 # number of isolates to process at a time. total_isolates = len(isolates) # Check to see which isolates have been completed. os.chdir('reassortant_edges') completed = [int(f.split('.')[0].split(' '.format(handle))[5]) for f in os.listdir(os.getcwd()) if f.split('.')[1] == 'pkl'] print(completed) os.chdir('..') not_completed = [] for start in np.arange(0, total_isolates): if start not in completed: not_completed.append(start) with open('shell_scripts/source_pair/source_pair{0}.sh'.format(start), 'w') as f: f.write(get_header(1)) f.write('cd ..\n') f.write('cd ..\n') f.write('python source_pair.py {0} {1} {2}'.format(handle, start, start + 1)) with open('shell_scripts/source_pair_manual.sh', 'w') as f: f.write(get_header(1)) f.write('cd source_pair\n') for start in not_completed: f.write('qsub source_pair{0}.sh\n'.format(start))
StarcoderdataPython
3206648
<gh_stars>10-100 import torch import torch.nn as nn import torch.optim as optim import numpy as np import random import os import logging from transformers import get_cosine_schedule_with_warmup, DistilBertTokenizer from args import get_args from model.multimodal_transformer import MMT_VideoQA from loss import LogSoftmax from util import compute_a2v from train.train_videoqa import train, eval from data.videoqa_loader import get_videoqa_loaders # args, logging args = get_args() if not (os.path.isdir(args.save_dir)): os.mkdir(os.path.join(args.save_dir)) logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)-8s %(message)s" ) logFormatter = logging.Formatter("%(asctime)s %(levelname)-8s %(message)s") rootLogger = logging.getLogger() fileHandler = logging.FileHandler(os.path.join(args.save_dir, "stdout.log"), "w+") fileHandler.setFormatter(logFormatter) rootLogger.addHandler(fileHandler) logging.info(args) # set random seeds torch.manual_seed(args.seed) np.random.seed(args.seed) random.seed(args.seed) # get answer embeddings bert_tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased") a2id, id2a, a2v = None, None, None if not args.mc: a2id, id2a, a2v = compute_a2v( vocab_path=args.vocab_path, bert_tokenizer=bert_tokenizer, amax_words=args.amax_words, ) logging.info(f"Length of Answer Vocabulary: {len(a2id)}") # Model model = MMT_VideoQA( feature_dim=args.feature_dim, word_dim=args.word_dim, N=args.n_layers, d_model=args.embd_dim, d_ff=args.ff_dim, h=args.n_heads, dropout=args.dropout, T=args.max_feats, Q=args.qmax_words, baseline=args.baseline, ) model.cuda() logging.info("Using {} GPUs".format(torch.cuda.device_count())) # Load pretrain path model = nn.DataParallel(model) if args.pretrain_path != "": model.load_state_dict(torch.load(args.pretrain_path)) logging.info(f"Loaded checkpoint {args.pretrain_path}") logging.info( f"Nb of trainable params:{sum(p.numel() for p in model.parameters() if p.requires_grad)}" ) # Dataloaders features = torch.load(args.features_path) ( train_dataset, train_loader, val_dataset, val_loader, test_dataset, test_loader, ) = get_videoqa_loaders(args, features, a2id, bert_tokenizer) logging.info("number of train instances: {}".format(len(train_loader.dataset))) logging.info("number of val instances: {}".format(len(val_loader.dataset))) logging.info("number of test instances: {}".format(len(test_loader.dataset))) # Loss + Optimizer if args.dataset == "ivqa": criterion = LogSoftmax(dim=1) else: criterion = nn.CrossEntropyLoss() params_for_optimization = list(p for p in model.parameters() if p.requires_grad) optimizer = optim.Adam( params_for_optimization, lr=args.lr, weight_decay=args.weight_decay ) criterion.cuda() # Training if not args.test: scheduler = get_cosine_schedule_with_warmup( optimizer, 0, len(train_loader) * args.epochs ) logging.info( f"Set cosine schedule with {len(train_loader) * args.epochs} iterations" ) eval(model, test_loader, a2v, args, test=True) # zero-shot VideoQA best_val_acc = -float("inf") best_epoch = 0 for epoch in range(args.epochs): train(model, train_loader, a2v, optimizer, criterion, scheduler, epoch, args) val_acc = eval(model, val_loader, a2v, args, test=False) if val_acc > best_val_acc: best_val_acc = val_acc best_epoch = epoch torch.save( model.state_dict(), os.path.join(args.save_dir, "best_model.pth") ) logging.info(f"Best val model at epoch {best_epoch + 1}") model.load_state_dict( torch.load( os.path.join(args.checkpoint_predir, args.checkpoint_dir, "best_model.pth") ) ) # Evaluate on test set eval(model, test_loader, a2v, args, test=True)
StarcoderdataPython
3204729
<gh_stars>1-10 from django.contrib import admin from django.urls import path, include from rest_framework import routers, serializers, viewsets from rest_framework.authtoken.views import obtain_auth_token from surfsara.views import user, tasks, shares, permissions # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register("users", user.UserViewSet, basename="user") router.register("shares", shares.ViewShares, basename="shares") router.register("tasks", tasks.Tasks, basename="tasks") router.register("permissions", permissions.Permissions, basename="permissions") urlpatterns = [ path("api/", include(router.urls)), path("admin/", admin.site.urls), path("api-auth/", include("rest_framework.urls")), ]
StarcoderdataPython
88245
<reponame>Xenovortex/Text-Analytics-Project import os from os.path import abspath, dirname, join, exists import multiprocessing import time import pickle import torch import numpy as np from sklearn.metrics import r2_score from torch.utils.data import DataLoader, TensorDataset import torch.optim as opt import matplotlib.pyplot as plt from utils import BERT, evaluater, gpu, regression, to_dataframe, sentencestats, architectures from tqdm import tqdm def train_model( filename, num_epoch, step_epochs, batch_size, lr, save_name, engineered_features=False, multiple_dataset=False, pretask_epoch=None, pretask_file=None, dropout=False, batchnorm=False, no_freeze=False ): """Train a model on the given dataset Written by <NAME>. Contact Xenovortex, if problems arises. Args: filename (str): name of h5 file containing dataset num_epoch (int): number of epochs step_epochs (list): list of epoch number, where learning rate will be reduce by a factor of 10 batch_size (int): batch size lr (float): learning rate save_name (str): name under which to save trained model and results engineered_features (bool, optional): contenate engineered features to vectorized sentence multiple_dataset (bool, optional): use multiple datasets for conditional training pretask_epoch (int, optional): integer provided will be the number of epochs spent on the pretask pretask_file (str, optional): filename of dataset for pretask dropout (bool, optional): use network architecture with dropout batchnorm (bool, optional): use network architecture with batch normalization no_freeze (bool, optional): in pretask training, don't freeze first layer """ # save paths model_path = join(dirname(dirname(dirname(abspath(__file__)))), "model", "BERT") log_path = join(dirname(dirname(dirname(abspath(__file__)))), "result", "BERT") fig_path = join(dirname(dirname(dirname(abspath(__file__)))), "figures", "BERT") # create directories for path in [model_path, log_path, fig_path]: if not exists(dirname(path)): os.makedirs(dirname(path)) if not exists(path): os.makedirs(path) # set device device = gpu.check_gpu() num_workers = multiprocessing.cpu_count() print("Training on:", device) print("Number of CPU cores detected:", num_workers) # read data df_train, df_test = to_dataframe.read_augmented_h5(filename) # setup BERT model bert_model = BERT.BERT() # prepare BERT input train_sentences = df_train.raw_text.values test_sentences = df_test.raw_text.values train_input_tensor, train_segment_tensor = bert_model.preprocessing(train_sentences) test_input_tensor, test_segment_tensor = bert_model.preprocessing(test_sentences) # extract labels and cast to PyTorch tensor train_labels = torch.tensor( list(df_train.rating.values), dtype=torch.float ).unsqueeze_(1) test_labels = torch.tensor( list(df_test.rating.values), dtype=torch.float ).unsqueeze_(1) # prepare dataset if engineered_features and multiple_dataset: extra_train_feat = torch.from_numpy( np.nan_to_num(sentencestats.construct_features(df_train.raw_text).values) ).float() extra_test_feat = torch.from_numpy( np.nan_to_num(sentencestats.construct_features(df_test.raw_text).values) ).float() train_dataset_label = torch.tensor( list(df_train.source.values), dtype=torch.float ).unsqueeze_(1) test_dataset_label = torch.tensor( list(df_test.source.values), dtype=torch.float ).unsqueeze_(1) trainset = TensorDataset( train_input_tensor, train_segment_tensor, train_labels, extra_train_feat, train_dataset_label, ) testset = TensorDataset( test_input_tensor, test_segment_tensor, test_labels, extra_test_feat, test_dataset_label, ) elif engineered_features: extra_train_feat = torch.from_numpy( np.nan_to_num(sentencestats.construct_features(df_train.raw_text).values) ).float() extra_test_feat = torch.from_numpy( np.nan_to_num(sentencestats.construct_features(df_test.raw_text).values) ).float() trainset = TensorDataset( train_input_tensor, train_segment_tensor, train_labels, extra_train_feat ) testset = TensorDataset( test_input_tensor, test_segment_tensor, test_labels, extra_test_feat ) elif multiple_dataset: train_dataset_label = torch.tensor( list(df_train.source.values), dtype=torch.float ).unsqueeze_(1) test_dataset_label = torch.tensor( list(df_test.source.values), dtype=torch.float ).unsqueeze_(1) trainset = TensorDataset( train_input_tensor, train_segment_tensor, train_labels, train_dataset_label ) testset = TensorDataset( test_input_tensor, test_segment_tensor, test_labels, test_dataset_label ) else: trainset = TensorDataset(train_input_tensor, train_segment_tensor, train_labels) testset = TensorDataset(test_input_tensor, test_segment_tensor, test_labels) # dataloader trainloader = DataLoader( trainset, batch_size=batch_size, shuffle=True, num_workers=num_workers, pin_memory=True, ) testloader = DataLoader( testset, batch_size=batch_size, shuffle=False, num_workers=num_workers, pin_memory=True, ) # setup pretask if pretask_epoch is not None and pretask_file is not None: # read data df_pretask, _ = to_dataframe.read_augmented_h5(pretask_file) # prepare BERT input pretask_sentences = df_pretask.raw_text.values pretask_input_tensor, pretask_segment_tensor = bert_model.preprocessing(pretask_sentences) # extract labels + cast to PyTorch tensors pretask_labels = torch.tensor( list(df_pretask.rating.values), dtype=torch.float ).unsqueeze_(1) # prepare dataset if engineered_features: extra_pretask_feat = torch.from_numpy( sentencestats.construct_features(pretask_sentences) ) pretask_set = TensorDataset( pretask_input_tensor, pretask_segment_tensor, pretask_labels, extra_pretask_feat ) else: pretask_set = TensorDataset(pretask_input_tensor, pretask_segment_tensor, pretask_labels) # dataloader pretask_loader = DataLoader( pretask_set, batch_size=batch_size, shuffle=True, num_workers=num_workers, pin_memory=True, ) # prepare regression model feat_size = 768 if engineered_features: feat_size += 21 if multiple_dataset: feat_size += 1 if dropout and batchnorm: reg_model = architectures.BN_Dropout_Net(feat_size, 512, 1) elif batchnorm: reg_model = architectures.BN_Net(feat_size, 512, 1) elif dropout: reg_model = architectures.Dropout_Net(feat_size, 512, 1) else: reg_model = architectures.Net(feat_size, 512, 1) reg_model = reg_model.to(device) # optimizer optimizer = torch.optim.Adam(reg_model.parameters(), lr=lr) # criterion criterion = torch.nn.MSELoss() pretask_criterion = torch.nn.BCELoss() # scheduler scheduler = opt.lr_scheduler.MultiStepLR(optimizer, step_epochs, 0.1) if pretask_epoch is not None and pretask_file is not None: # training on pretask reg_model = train_pretask(pretask_epoch, reg_model, bert_model, pretask_loader, pretask_criterion, optimizer, engineered_features, log_path, fig_path, model_path, save_name) if not no_freeze: # freeze first layer of the model for params in reg_model.model[0].parameters(): params.requires_grad = False # log loss_log = [] train_MSE_log = [] train_RMSE_log = [] train_MAE_log = [] train_r2_log = [] test_MSE_log = [] test_RMSE_log = [] test_MAE_log = [] test_r2_log = [] for epoch in range(num_epoch): start = time.time() reg_model.train() print("Training:") # training for i, data in enumerate(tqdm(trainloader)): # move batch and model to device reg_model.to(device) input_id = data[0].to(device) segment = data[1].to(device) label = data[2].to(device) if engineered_features and multiple_dataset: extra_feat = data[3].to(device) dataset_label = data[4].to(device) elif engineered_features: extra_feat = data[3].to(device) elif multiple_dataset: dataset_label = data[3].to(device) # clear gradients optimizer.zero_grad() # BERT feature extraction features = bert_model.get_features(input_id, segment) # add engineered features if engineered_features: features = torch.cat((features, extra_feat), 1) # add dataset conditional label if multiple_dataset: features = torch.cat((features, dataset_label), 1) # prediction output = reg_model(features) # loss evaluation loss = criterion(output, label) loss.backward() # backpropagation optimizer.step() # record loss curr_loss = torch.mean(loss).item() running_loss = ( curr_loss if ((i == 0) and (epoch == 0)) else running_loss + curr_loss ) # update training schedule scheduler.step() # evaluation print("Evaluation:") reg_model.eval() running_loss /= len(trainloader) MSE_train, RMSE_train, MAE_train, r2_train = evaluater.evaluate_model( reg_model, bert_model, trainloader, engineered_features, multiple_dataset ) MSE_test, RMSE_test, MAE_test, r2_test = evaluater.evaluate_model( reg_model, bert_model, testloader, engineered_features, multiple_dataset ) # log evaluation result loss_log.append(running_loss) train_MSE_log.append(MSE_train) train_RMSE_log.append(RMSE_train) train_MAE_log.append(MAE_train) train_r2_log.append(r2_train) test_MSE_log.append(MSE_test) test_RMSE_log.append(RMSE_test) test_MAE_log.append(MAE_test) test_r2_log.append(r2_test) # save logs file = open(join(log_path, save_name + ".txt"), "w") print("Last Epoch:", epoch + 1, file=file) print("Final Loss:", loss_log[-1], file=file) print("Final Train MSE:", train_MSE_log[-1], file=file) print("Final Train RMSE:", train_RMSE_log[-1], file=file) print("Final Train MAE:", train_MAE_log[-1], file=file) print("Final Train R2:", train_r2_log[-1], file=file) print("Final Test MSE:", test_MSE_log[-1], file=file) print("Final Test RMSE:", test_RMSE_log[-1], file=file) print("Final Test MAE:", test_MAE_log[-1], file=file) print("Final Test R2:", test_r2_log[-1], file=file) # save variables with open(join(log_path, save_name + ".pkl"), "wb") as f: pickle.dump( [ loss_log, train_MSE_log, train_RMSE_log, train_MAE_log, train_r2_log, test_MSE_log, test_RMSE_log, test_MAE_log, test_r2_log, ], f, ) # save model weights torch.save( reg_model.to("cpu").state_dict(), join(model_path, save_name + ".pt") ) # print stats print( "epoch {} \t loss {:.5f} \t train_r2 {:.3f} \t test_r2 {:.3f} \t time {:.1f} sec".format( epoch + 1, running_loss, r2_train, r2_test, time.time() - start ) ) # plots plot_names = [ "loss", "train_MSE", "train_RMSE", "train_MAE", "train_r2", "test_MSE", "test_RMSE", "test_MAE", "test_r2", ] for i, log in enumerate( [ loss_log, train_MSE_log, train_RMSE_log, train_MAE_log, train_r2_log, test_MSE_log, test_RMSE_log, test_MAE_log, test_r2_log, ] ): plt.figure(num=None, figsize=(15, 10)) plt.plot(log) plt.grid(True, which="both") plt.xlabel("epoch", fontsize=14) plt.ylabel(plot_names[i], fontsize=14) plt.savefig(join(fig_path, save_name + "_" + plot_names[i] + ".png")) plt.close("all") def train_pretask(pretask_epoch, model, bert_model, dataloader, criterion, optimizer, engineered_features, log_path, fig_path, model_path, save_name): """Train a model on a pretask Written by <NAME>. Contact Xenovortex, if problems arises. Args: pretask_epoch (int): integer provided will be the number of epochs spent on the pretask model (torch.nn.Module): PyTorch model of a Regression Neural Network bert_model (torch.nn.Module): BERT PyTorch model for feature extraction dataloader (PyTorch dataloader): PyTorch dataloader of dataset criterion (function): loss function optimizer (PyTorch optimizer): optimizer of model parameters engineered_features (bool): contenate engineered features to vectorized sentence log_path (str): path to save log files fig_path (str): path to save figures model_path (str): path to save model save_name (str): name under which to save trained model and results Return: model (torch.nn.Module): trained PyTorch model """ # log pretask_loss_log = [] pretask_acc_log = [] # set device device = gpu.check_gpu() print("Pretask Training on:", device) # sigmoid sigmoid = torch.nn.Sigmoid() # create directories for path in [model_path, log_path, fig_path]: if not exists(join(path, "pretask")): os.makedirs(join(path, "pretask")) for epoch in range(pretask_epoch): start = time.time() model.train() print("Training:") # training for i, data in enumerate(tqdm(dataloader)): # move batch and model to device model.to(device) input_id = data[0].to(device) segment = data[1].to(device) label = data[2].to(device) if engineered_features: extra_feat = data[3].to(device) # clear gradients optimizer.zero_grad() # BERT feature extraction features = bert_model.get_features(input_id, segment) # add engineered features if engineered_features: features = torch.cat((features, extra_feat), 1) # prediction output = sigmoid(model(features)) # loss evaluation loss = criterion(output, label) loss.backward() # backpropagation optimizer.step() # record loss curr_loss = torch.mean(loss).item() running_loss = ( curr_loss if ((i == 0) and (epoch == 0)) else running_loss + curr_loss ) # evaluation print("Evaluation:") model.eval() running_loss /= len(dataloader) accuracy = evaluater.evaluate_acc(model, bert_model, dataloader, engineered_features) # log evaluation result pretask_loss_log.append(running_loss) pretask_acc_log.append(accuracy) # save logs file = open(join(log_path, "pretask", save_name + ".txt"), "w") print("Last Epoch:", epoch + 1, file=file) print("Final Loss:", pretask_loss_log[-1], file=file) print("Final Train Accuracy:", pretask_acc_log[-1], file=file) # save variables with open(join(log_path, "pretask", save_name + ".pkl"), "wb") as f: pickle.dump( [ pretask_loss_log, pretask_acc_log, ], f, ) # save model weights torch.save( model.to("cpu").state_dict(), join(model_path, "pretask", save_name + ".pt") ) # print stats print( "epoch {} \t loss {:.5f} \t train_acc {:.3f} \t time {:.1f} sec".format( epoch + 1, running_loss, accuracy, time.time() - start ) ) # plots plot_names = [ "loss", "accuracy", ] for i, log in enumerate( [ pretask_loss_log, pretask_acc_log ] ): plt.figure(num=None, figsize=(15, 10)) plt.plot(log) plt.grid(True, which="both") plt.xlabel("epoch", fontsize=14) plt.ylabel(plot_names[i], fontsize=14) plt.savefig(join(fig_path, "pretask", save_name + "_" + plot_names[i] + ".png")) plt.close("all") return model
StarcoderdataPython
3378382
<filename>Tfidf/SVM/test.py # -*- coding: utf-8 -*- """crtest.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/19z0CxLn52gS1kQjdA-JhmSkp1-uWSjOg """ from google.colab import drive drive.mount('/content/drive') # Download the StanfordCoreNLP package # We will use this package to extract verb phrases from sentences !wget http://nlp.stanford.edu/software/stanford-corenlp-full-2018-10-05.zip import zipfile fh = open('stanford-corenlp-full-2018-10-05.zip', 'rb') z = zipfile.ZipFile(fh) for name in z.namelist(): outpath = "/content/drive/My Drive/Causal_Relation_Extraction/Production/stanfordcorenlp" z.extract(name, outpath) fh.close() pip install stanfordcorenlp import pandas as pd import numpy as np from nltk.tokenize import word_tokenize from nltk import pos_tag from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from sklearn.preprocessing import LabelEncoder from collections import defaultdict from nltk.corpus import wordnet as wn from sklearn.feature_extraction.text import TfidfVectorizer from sklearn import model_selection, svm from sklearn.metrics import accuracy_score import pickle import re import json from stanfordcorenlp import StanfordCoreNLP from nltk.tree import Tree nlp = StanfordCoreNLP('/content/drive/My Drive/cicd/Production/stanfordcorenlp/stanford-corenlp-full-2018-10-05') import nltk nltk.download('punkt') nltk.download('wordnet') nltk.download('averaged_perceptron_tagger') nltk.download('stopwords') # form a parse tree of the sentence # Extract the phrases def extract_phrase(tree_str, label): phrases = [] trees = Tree.fromstring(tree_str) for tree in trees: for subtree in tree.subtrees(): if subtree.label() == label: t = subtree t = ' '.join(t.leaves()) phrases.append(t) return phrases # Check if the sentence contains a noun phrase and a verb phrase def is_npvp(sentence): tree_str = nlp.parse(sentence) nps = extract_phrase(tree_str, 'NP') vps = extract_phrase(tree_str, 'VP') if len(nps) == 0 or len(vps) == 0: return False else: vpl = vps[0].split(" ") if len(vpl) > 1: return True else: return False def get_sent_token(Sent): # Step - a : Remove blank rows if any. rawSent = Sent.copy() rawSent['sentences'].dropna(inplace=True) # Step - b : Change all the sentences to lower case. This is required as python interprets 'dog' and 'DOG' differently rawSent['sentences'] = [entry.lower() for entry in rawSent['sentences']] # Step - c : Remove all special symbols s_list = [] for sentence in rawSent['sentences']: for k in sentence.split("\n"): s_list.append(re.sub(r"[^a-zA-Z0-9]+", ' ', k)) # Find the name of the column by index n = rawSent.columns[0] # Drop that column rawSent.drop(n, axis = 1, inplace = True) # Put whatever series you want in its place rawSent[n] = s_list rel = [' consequently', ' as a result ', ' therefore', ' as a consequence', ' for this reason', ' for all these reasons', ' thus', ' because', ' since ', ' cause of', ' because of', ' after', ' as ' ] vsent = [] loc = [] for sent in rawSent['sentences']: if any(x in sent for x in rel): if is_npvp(sent): vsent.append(sent) i = rawSent.sentences[rawSent.sentences == sent].index.tolist() loc.append(i[0]) if len(vsent) == 0: emp = pd.DataFrame() return emp else: polSent = pd.DataFrame(list(zip(vsent, loc)), columns =['sentences', 'loc']) # Step - d : Tokenization : In this each entry in the rawSent will be broken into set of words polSent['sentences']= [word_tokenize(entry) for entry in polSent['sentences']] # Step - e : Remove Numeric symbols and perfom Word Stemming/Lemmenting. # WordNetLemmatizer requires Pos tags to understand if the word is noun or verb or adjective etc. By default it is set to Noun tag_map = defaultdict(lambda : wn.NOUN) tag_map['J'] = wn.ADJ tag_map['V'] = wn.VERB tag_map['R'] = wn.ADV for index,entry in enumerate(polSent['sentences']): # Declaring Empty List to store the words that follow the rules for this step Final_words = [] # Initializing WordNetLemmatizer() word_Lemmatized = WordNetLemmatizer() # pos_tag function below will provide the 'tag' i.e if the word is Noun(N) or Verb(V) or something else. for word, tag in pos_tag(entry): # Below condition is to check for Stop words and consider only alphabets if word.isalpha(): word_Final = word_Lemmatized.lemmatize(word,tag_map[tag[0]]) Final_words.append(word_Final) # The final processed set of words for each iteration will be stored in 'sentences_final' polSent.loc[index,'sentences_final'] = str(Final_words) return polSent def test(): from sklearn.externals import joblib # Load the model from the file cfcd = joblib.load('/content/drive/My Drive/Causal_Relation_Extraction/Production/cr_model.pkl') text = input("Enter text: ") if not text: print("No text entered") else: from nltk import tokenize sentences = tokenize.sent_tokenize(text) label = [] for i in range(len(sentences)): label.append(0) rawSentences = pd.DataFrame(list(zip(sentences, label)), columns =['sentences', 'label']) sent_tokens = get_sent_token(rawSentences) if sent_tokens.empty: print("No causes found") text_and_causes = get_json_from_pd(text, sent_tokens) print(text_and_causes) else: ind = sent_tokens['loc'].tolist() rawSentences = rawSentences.loc[ ind , : ] rawSentences.reset_index(drop = True, inplace = True) # Testing phase tf_features = pickle.load(open("/content/drive/My Drive/Causal_Relation_Extraction/Production/cr_features.pkl", 'rb')) sent_Tfidf = tf_features.transform(sent_tokens['sentences_final']) label_predictions = cfcd.predict(sent_Tfidf) n = rawSentences.columns[1] # Drop that column rawSentences.drop(n, axis = 1, inplace = True) rawSentences[n] = label_predictions.tolist() print(rawSentences) #convert to json format text_and_causes = get_json_from_pd(text, rawSentences) print(text_and_causes) def get_json_from_pd(text, rawSentences): if rawSentences.empty: thisdict = { "text": text, "causes": [] } else: causes_df = rawSentences[rawSentences.label == 1] causes = causes_df['sentences'].tolist() thisdict = { "text": text, "causes": causes } text_and_causes = json.dumps(thisdict) return text_and_causes test()
StarcoderdataPython
3206712
<reponame>iiasceri/people-app-api from django.urls import path from django.conf.urls import url from user import views app_name = 'user' urlpatterns = [ path('create/', views.CreateUserView.as_view(), name='create'), path('token/', views.CreateTokenView.as_view(), name='token'), path('me/', views.ManageUserView.as_view(), name='me'), url('creategroup/', views.create_group), url('get-groups/', views.get_groups), url('get-group/(?P<pk>[0-9]+)/$', views.get_group), ]
StarcoderdataPython
4814991
import os,time, pdb import datetime as dt import sqlalchemy import numpy as np import pandas as pd import statsmodels.api as sm class LongShortWeighted(object): def __init__(self): self._industry_styles = ['Bank','RealEstate','Health','Transportation','Mining', 'NonFerMetal','HouseApp','LeiService','MachiEquip','BuildDeco', 'CommeTrade','CONMAT','Auto','Textile','FoodBever','Electronics', 'Computer','LightIndus','Utilities','Telecom','AgriForest','CHEM', 'Media','IronSteel','NonBankFinan','ELECEQP','AERODEF','Conglomerates'] self._risk_styles = ['BETA','MOMENTUM','SIZE','EARNYILD','RESVOL','GROWTH','BTOP', 'LEVERAGE','LIQUIDTY','SIZENL'] #暂时写此处,去极值 def winsorize(self, total_data, method='sigma', limits=(3.0, 3.0), drop=True): se = total_data.copy() if method == 'quantile': down, up = se.quantile([limits[0], 1.0 - limits[1]]) elif method == 'sigma': std, mean = se.std(), se.mean() down, up = mean - limits[0]*std, mean + limits[1]*std if drop: se[se<down] = np.NaN se[se>up] = np.NaN else: se[se<down] = down se[se>up] = up return se #标准化 def standardize(self, total_data): try: res = (total_data - total_data.mean()) / total_data.std() except: res = pd.Series(data=np.NaN, index=total_data.index) return res #中性化 def neutralize(self, total_data, risk_df): se = total_data.dropna() # se = total_data.copy() risk = risk_df.loc[se.index,:] # use numpy for neu, which is faster x = np.linalg.lstsq(risk.values, np.matrix(se).T)[0] se_neu = se - risk.dot(x)[0] return se_neu def _to_weights(self, group): demeaned_vals = group - group.mean() return demeaned_vals / demeaned_vals.abs().sum() def _to_ls_count(self, group, long=True): demeaned_vals = group - group.mean() if long: count = len(demeaned_vals[demeaned_vals>0]) else: count = len(demeaned_vals[demeaned_vals<0]) return count def returns(self, total_data, forward_returns, init_capital=100000): weights = total_data.groupby(level=['trade_date']).apply(self._to_weights) weighted_returns = forward_returns.multiply(weights, axis=0) factor_ret = weighted_returns.groupby(level='trade_date').sum() pnl = init_capital*2*factor_ret turnover = weights.unstack().T.diff().abs().sum(axis=1) long_count = total_data.groupby(level=['trade_date']).apply(self._to_ls_count) short_count = total_data.groupby(level=['trade_date']).apply(lambda x: self._to_ls_count(x, long=False)) return factor_ret, pnl, turnover, long_count, short_count def run(self, factor_data, risk_data, forward_returns, factor_name, horizon=1, method='quantile', up_limit=0.025, down_limit=0.025, init_capital=100000): """ 参数: horizon: 调仓期,按照交易日计算。 """ factor_se = factor_data.set_index(['code','trade_date']) risk_se = risk_data.set_index(['code','trade_date']) forward_returns = forward_returns.set_index(['code','trade_date']) # risk_df = risk_se.reindex(factor_se.index)[self._industry_styles + ['SIZE'] + ['COUNTRY']] risk_df = risk_se.reindex(factor_se.index)[self._industry_styles + ['SIZE']] risk_df.dropna(inplace=True) factor_se = factor_se.loc[risk_df.index][factor_name] returns = forward_returns.loc[risk_df.index] factor_se = factor_se.groupby(level='trade_date').apply(lambda x: self.winsorize(x, method=method, limits=(up_limit, down_limit))) # factor_se = factor_se.groupby(level='trade_date').apply(lambda x: self.neutralize(x, risk_df)) # index 多了一项 grouped = factor_se.groupby(level='trade_date') res = [] for trade_date, g in grouped: neu = self.neutralize(g, risk_df) res.append(neu) factor_se = pd.concat(res, axis=0) factor_se = factor_se.groupby(level='trade_date').apply(lambda x: self.standardize(x)) factor_ret, pnl, turnover_se, lc, sc = self.returns(factor_se, forward_returns['ret'], init_capital=init_capital) #计算指标 ir = factor_ret.mean()/factor_ret.std() sharpe = np.sqrt(252/horizon)*ir turnover = turnover_se.mean() returns = factor_ret.sum()*252/horizon/len(factor_ret) fitness = sharpe * np.sqrt(abs(returns)/turnover) margin = factor_ret.sum()/turnover_se.sum() capital = pnl + init_capital running_max = np.maximum.accumulate(capital) drawback_data = -((running_max - capital) / running_max) max_drawdown = np.min(drawback_data) return {'ir':ir, 'sharpe':sharpe, 'turnover':turnover, 'returns':returns, 'fitness':fitness, 'margin':margin, 'max_drawdown':max_drawdown}
StarcoderdataPython
1784028
<gh_stars>1-10 #!python import sys import gzip ctl_filename = sys.argv[1] max_length = 100 def shorten_conll_file(filename): assert (filename.endswith('.gz')) new_filename = "%s.%d.gz"%(filename[:-3], max_length) file = gzip.open(filename) new_file = gzip.open(new_filename, 'wb') count = 0 for line in file: if line == "\n": count += 1 if count == max_length: break new_file.write(line) counter = 0 for line in open(ctl_filename): counter += 1 if counter % 1000 == 0: print "Shortened %d files."%counter line = line[:-1] shorten_conll_file(line)
StarcoderdataPython
4809797
<reponame>avim2809/CameraSiteBlocker # encoding: utf-8 try: import ttk except ImportError: # For some reason the future version of tkinter.ttk does not seem to have Widget! from tkinter import ttk class Spinbox(ttk.Widget): def __init__(self, master, **kw): ttk.Widget.__init__(self, master, 'ttk::spinbox', kw)
StarcoderdataPython
24940
#<NAME> #<EMAIL> #12/Sept/2018 myList = ['Hi', 5, 6 , 3.4, "i"] #Create the list myList.append([4, 5]) #Add sublist [4, 5] to myList myList.insert(2,"f") #Add "f" in the position 2 print(myList) myList = [1, 3, 4, 5, 23, 4, 3, 222, 454, 6445, 6, 4654, 455] myList.sort() #Sort the list from lowest to highest print(myList) myList.sort(reverse = True) #Sort the list from highest to lowest print(myList) myList.extend([5, 77]) #Add 5 and 77 to myList print(myList) #List comprehension myList = [] for value in range(0, 50): myList.append(value) print(myList) myList = ["f" for value in range(0,20)] print(myList) myList = [value for value in range(0,20)] print(myList) myList = [value for value in range(0,60,3) if value % 2 == 0] print(myList)
StarcoderdataPython
3227588
<gh_stars>0 # Copyright 2018 Google LLC # # 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. # [START docs_quickstart] from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import sys import converters.latex import converters.markdown # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/documents.readonly'] def auth_and_download_body(doc_id, doc_pickle_file): """Shows basic usage of the Docs API. Prints the title of a sample document. """ creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_console() # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('docs', 'v1', credentials=creds) # Retrieve the documents contents from the Docs service. document = service.documents().get(documentId=doc_id).execute() print('The title of the document is: {}'.format(document.get('title'))) with open(doc_pickle_file, 'wb') as body_pickle: pickle.dump(document.get('body'), body_pickle) if __name__ == '__main__': if len(sys.argv) != 4: print("Usage: docker run [...] download-doc.py [doc-id] [latex,markdown] [out-file]") sys.exit(1) doc_id = sys.argv[1] format = sys.argv[2] out_file = sys.argv[3] doc_pickle_file = 'document-body-' + doc_id + '.pickle' if not os.path.exists(doc_pickle_file): print("Downloading document ... ") auth_and_download_body(doc_id, doc_pickle_file) if format == "latex": converters.latex.process_body(doc_pickle_file, out_file) if format == "markdown": converters.markdown.process_body(doc_pickle_file, out_file) # [END docs_quickstart]
StarcoderdataPython
117547
# coding: utf-8 import pytest if __name__ == "__main__": # import os # import sys # sys.path.append(os.path.realpath('..')) pytest.main([__file__]) from tests.import_check import ImportCheck def test_single(): # from ooobuild.lo.document.filter_options_request import FilterOptionsRequest # ns = "ooobuild.lo.document.filter_options_request.FilterOptionsRequest" ns = "ooobuild.lo.ucb.open_command_argument.OpenCommandArgument" imc = ImportCheck() assert imc.load_import(ns) == True
StarcoderdataPython
1638526
from logging import getLogger import httpx from fastapi import FastAPI from app.models.orm import Base, Entry, RegisteredActor from app.services.service_worker import ServiceWorker from app.util.data_import.data_importer import create_regular logger = getLogger(__name__) def clear_db(session): engine = session.bind.engine Base.metadata.drop_all(engine) Base.metadata.create_all(engine) def run_app_tests(app: FastAPI, sw: ServiceWorker): logger.warning("TEST: RUN APP TESTS") test_template = sw.db_session.query(Entry).filter(Entry.slug == "test_template",Entry.language=="en").first() template = sw.template_codes.to_proper_model(test_template) admin = sw.db_session.query(RegisteredActor).filter(RegisteredActor.registered_name == "admin").first() entry = create_regular(template, sw, "admin") #sw.entry.process_entry_post(entry, admin) # httpx.get("http://localhost:8000/api/v1/slug/test_template",params={"language":"en"}) if __name__ == "__main__": resp = httpx.get("http://localhost:8100/api/v1/slug/test_template",params={"language":"en"}) print(resp.status_code)
StarcoderdataPython
3311246
# 角谷定理。输入一个自然数,若为偶数,则把它除以2, # 若为奇数,则把它乘以3加1。经过如此有限次运算后,总可以得到自然数值1。求经过多少次可得到自然数1 # 如:输入22, # # 输出 STEP=16 def caculateStep(step, number): if number == 1: return step + 1 if number % 2 == 0: number = number / 2 else: number = number * 3 + 1 return caculateStep(step + 1, number) input = input() print(caculateStep(0, int(input)))
StarcoderdataPython
1607368
<gh_stars>1-10 #!/usr/bin/env python def get_help_data_12586(): """ Vocabulary help. Data store of information to be presented when a help request is made for port 12586. Returns a list of dictionaries associated with various requests supported on that port. Sample response: [ { "@class" : ".VocabRecord", "model" : "", "manufacturer" : "", "vocabId" : 1, "refdes" : "CE01ISSM", "instrument" : "", "tocL1" : "Coastal Endurance", "tocL2" : "Oregon Inshore Surface Mooring", "tocL3" : "", "mindepth" : 0.0, "maxdepth" : 25.0 }, { "@class" : ".VocabRecord", "model" : "", "manufacturer" : "", "vocabId" : 2, "refdes" : "CE01ISSM-MFC31", "instrument" : "", "tocL1" : "Coastal Endurance", "tocL2" : "Oregon Inshore Surface Mooring", "tocL3" : "Seafloor Multi-Function Node (MFN)", "mindepth" : 25.0, "maxdepth" : 25.0 }, . . . ] """ help_data = [ { 'root': 'vocab', 'endpoint': 'vocab', 'method': 'GET', 'permission_required': False, 'description': 'Returns a list of dictionaries for OOI vocabulary. ' + 'An abbreviated response is provided below.', 'data_required': False, 'data_format': None, 'sample_request': 'vocab', 'sample_response': [ { "@class" : ".VocabRecord", "model" : "", "manufacturer" : "", "vocabId" : 1, "refdes" : "CE01ISSM", "instrument" : "", "tocL1" : "Coastal Endurance", "tocL2" : "Oregon Inshore Surface Mooring", "tocL3" : "", "mindepth" : 0.0, "maxdepth" : 25.0 }, { "@class" : ".VocabRecord", "model" : "", "manufacturer" : "", "vocabId" : 2, "refdes" : "CE01ISSM-MFC31", "instrument" : "", "tocL1" : "Coastal Endurance", "tocL2" : "Oregon Inshore Surface Mooring", "tocL3" : "Seafloor Multi-Function Node (MFN)", "mindepth" : 25.0, "maxdepth" : 25.0 }, ] }, { 'root': 'vocab', 'endpoint': 'vocab/inv', 'method': 'GET', 'permission_required': False, 'description': 'Returns a list of all subsite entries in the vocabulary. ' + 'An abbreviated response is provided below.', 'data_required': False, 'data_format': None, 'sample_request': 'vocab/inv', 'sample_response': ["CE01ISSM", "CE01ISSP", "CE02SHBP", "CE02SHSM", "CE02SHSP", "CE04OSBP"] }, { 'root': 'vocab', 'endpoint': 'vocab/inv/{subsite}', 'method': 'GET', 'permission_required': True, 'description': 'Returns a list of all nodes for the given subsite. ' + 'An abbreviated response is provided below.', 'data_required': False, 'data_format': [ { 'name': 'subsite', 'type': 'str', 'description': 'The subsite entry whose nodes are to be returned.', 'valid_values': None, 'default': None } ], 'sample_request': 'vocab/inv/CE01ISSM', 'sample_response': ["MFC31", "MFD35", "MFD37", "RID16", "SBC11", "SBD17"] }, { 'root': 'vocab', 'endpoint': 'vocab/inv/{subsite}/{node}', 'method': 'GET', 'permission_required': False, 'description': 'Returns a list of all sensors for the given subsite and node. ' + 'An abbreviated response is provided below.', 'data_required': True, 'data_format': [ { 'name': 'subsite', 'type': 'str', 'description': 'The subsite whose sensors are to be returned.', 'valid_values': None, 'default': None }, { 'name': 'node', 'type': 'str', 'description': 'The node whose sensors are to be returned.', 'valid_values': None, 'default': None } ], 'samples': [{ 'sample_request': 'vocab/inv/CE01ISSM/MFC31', 'sample_response': ["00-CPMENG000"] }] }, { 'root': 'vocab', 'endpoint': 'vocab/inv/{subsite}/{node}/{sensor}', 'method': 'GET', 'permission_required': False, 'description': 'Returns the single vocab record for a given subsite. node, and sensor' + 'An abbreviated response is provided below.', 'data_required': True, 'data_format': [ { 'name': 'subsite', 'type': 'str', 'description': 'The subsite used to get the vocabulary record.', 'valid_values': None, 'default': None }, { 'name': 'node', 'type': 'str', 'description': 'The node used to get the vocabulary record.', 'valid_values': None, 'default': None }, { 'name': 'sensor', 'type': 'str', 'description': 'The sensor used to get the vocabulary record.', 'valid_values': None, 'default': None } ], 'samples': [{ 'sample_request': 'vocab/inv/CE01ISSM/MFC31/00-CPMENG000', 'sample_response': [{ "@class" : ".VocabRecord", "model" : "Communications and Power Manager", "manufacturer" : "WHOI", "vocabId" : 3, "refdes" : "CE01ISSM-MFC31-00-CPMENG000", "instrument" : "Platform Controller", "tocL1" : "Coastal Endurance", "tocL2" : "Oregon Inshore Surface Mooring", "tocL3" : "Seafloor Multi-Function Node (MFN)", "mindepth" : 25.0, "maxdepth" : 25.0 }] }] } ] return help_data
StarcoderdataPython
1779667
<filename>settings.py #Please create a local_settings.py which should include, at least: # - ADMINS # - DEFAULT_FROM_EMAIL # - DATABASES # - SECRET_KEY # - FT_DOMAIN_KEY # - FT_DOMAIN_SECRET # - EMAIL_HOST # - EMAIL_HOST_USER # - EMAIL_HOST_PASSWORD # - EMAIL_PORT # - EMAIL_USE_TLS import os DEBUG = True TEMPLATE_DEBUG = DEBUG STATIC_DATA = os.path.join(os.path.dirname(__file__), 'static/') SHP_UPLOAD_DIR = '/tmp/' ADMINS = ( ('Admin1', 'your_email_address'), ) MANAGERS = ADMINS DEFAULT_FROM_EMAIL = 'your_email_addressm' EMAIL_MANAGERS = False CACHE_BACKEND = 'file:///tmp/shapeft_cache' DATABASE_NAME = 'shapeft' DATABASES = { 'default': { 'NAME': DATABASE_NAME, 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'USER': 'postgres', 'PASSWORD': '<PASSWORD>' } } TIME_ZONE = 'America/Vancouver' LANGUAGE_CODE = 'en-us' SITE_ID = 1 USE_I18N = False MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media/') MEDIA_URL = '' ADMIN_MEDIA_PREFIX = '/admin_media/' SECRET_KEY = 'store-in-local-settings' TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', ) from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS TEMPLATE_CONTEXT_PROCESSORS += ( 'django.core.context_processors.request', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.csrf.middleware.CsrfViewMiddleware', 'django.contrib.csrf.middleware.CsrfResponseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = 'urls' TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.databrowse', 'django.contrib.gis', 'django.contrib.humanize', 'django.contrib.webdesign', 'shapeft', 'shapes', 'contact', 'ft_auth', ) FT_DOMAIN_KEY = 'shpescape.com' FT_DOMAIN_SECRET = 'foo' try: from local_settings import * except ImportError, exp: pass
StarcoderdataPython
117542
import frappe def execute(): for i in frappe.get_all('Asset',{'docstatus':1},['location','name','serial_no']): if len(frappe.get_all('Asset Serial No',{'name':i.get("serial_no")})) == 0: if i.get("serial_no"): print("1111",i.get("serial_no")) asset_srl_no = frappe.new_doc("Asset Serial No") asset_srl_no.update({ "name": i.get("serial_no"), "location": i.get("location"), "asset":i.get("name"), "serial_no":i.get("serial_no") }) asset_srl_no.save() # doc = frappe.get_doc('Asset Serial No',{'name':x}) print("******",i.get("serial_no")) #mfi_customization.mfi.patch.make_serial_no.execute
StarcoderdataPython
24857
#Template of the Purkinje cell model, Zang et al. 2018 #Templating by Lungsi 2019 based on ~/PC2018Zang/purkinje.hoc #purkinje.hoc has been converted from original purkinje_demo and using readme.html as a guide from neuron import h #from pdb import set_trace as breakpoint from random import randint class Purkinje(object): """Multi-compartment cell """ def __init__(self): h.xopen("purkinje.hoc") # There are 1088 compartments and the following are chosen as # attributes to this python class for potential recording self.soma = h.somaA self.ais = h.AIS # Based on last 50 or so lines of Purkinje19b972-1.nrn self.dend_root = h.dendA1_0 # see Fig.2A of paper # Reverse eng. from Purkinje19b972-1.nrn and dendv_arnd21.ses dend_sm = [ sec for sec in h.maindend ] # len(dend_sm) -> 30 dend_sp = [ sec for sec in h.spinydend ] # len(dend_sp) -> 1105 # note that for either self.dend_sm or self.dend_sp # the first element of its list is a dendrite section closest to soma # and last element is the dendrite section farthest away. # also potentially #self.cf = [ sec for sec in h.cf ] # for climbing fibre #self.pf = [ sec for sec in h.pf ] # for paraller fibre # self.dend_sm = dend_sm[ randint(0, len(dend_sm)-1) ] self.dend_sp = dend_sp[ randint(0, len(dend_sp)-1) ]
StarcoderdataPython
4814985
<filename>main.py # -*- coding: utf-8 -*- """ Created on Sun Jan 19 23:54:40 2020 @author: Tarit """ import pandas as pd import sys import topsis as tp cla=sys.argv datafile=str(cla[1]) weights=cla[2].split(',') pn=cla[3].split(',') ds=pd.read_csv(datafile) n=len(ds.columns) if len(weights)!=n-1 or len(pn)!=n-1: print("Number of column weights or column +/- is incorrect") sys.exit() for temp in pn: if temp!='+' and temp!='-': print("Incorect argument type") sys.exit() i=tp.calbest(ds,weights,pn) print("It is clear that the optimal choice with the highest performance score is :",ds.iloc[i,0])
StarcoderdataPython
75484
#!/usr/bin/env python3 import argparse from game.game import Game def main(): """ Reversi game with human player vs AI player. """ parser = argparse.ArgumentParser() parser.add_argument('--timeout', help="Number of seconds the brain is allowed to think before making its move", type=int, default=1) parser.add_argument('--text', help="Display the game in text mode", action='store_false') parser.add_argument('--player', help="Player first", action='store_true') parser.add_argument('--ai', help="AI first", action='store_true') parser.add_argument('--verify', help="Verify AI using a random player", action='store_true') args = parser.parse_args() if args.timeout < 0: exit() players=['player', 'player'] if args.player: players = ['player', 'ai'] if args.ai: players = ['ai', 'player'] elif args.verify: players = ['ai', 'random'] game = Game(timeout=args.timeout, colour=args.text, players=players) game.run() if __name__ == "__main__": main()
StarcoderdataPython
181760
from __future__ import absolute_import, division, print_function import cv2 import numpy as np import six def figure(fnum=None, pnum=(1, 1, 1), title=None, figtitle=None, doclf=False, docla=False, projection=None, **kwargs): """ http://matplotlib.org/users/gridspec.html Args: fnum (int): fignum = figure number pnum (int, str, or tuple(int, int, int)): plotnum = plot tuple title (str): (default = None) figtitle (None): (default = None) docla (bool): (default = False) doclf (bool): (default = False) Returns: mpl.Figure: fig CommandLine: python -m plottool.custom_figure --exec-figure:0 --show python -m plottool.custom_figure --exec-figure:1 --show Example: >>> fnum = 1 >>> fig = figure(fnum, (2, 2, 1)) >>> gca().text(0.5, 0.5, "ax1", va="center", ha="center") >>> fig = figure(fnum, (2, 2, 2)) >>> gca().text(0.5, 0.5, "ax2", va="center", ha="center") >>> ut.show_if_requested() Example: >>> fnum = 1 >>> fig = figure(fnum, (2, 2, 1)) >>> gca().text(0.5, 0.5, "ax1", va="center", ha="center") >>> fig = figure(fnum, (2, 2, 2)) >>> gca().text(0.5, 0.5, "ax2", va="center", ha="center") >>> fig = figure(fnum, (2, 4, (1, slice(1, None)))) >>> gca().text(0.5, 0.5, "ax3", va="center", ha="center") >>> ut.show_if_requested() """ import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec def ensure_fig(fnum=None): if fnum is None: try: fig = plt.gcf() except Exception as ex: fig = plt.figure() else: try: fig = plt.figure(fnum) except Exception as ex: fig = plt.gcf() return fig def _convert_pnum_int_to_tup(int_pnum): # Convert pnum to tuple format if in integer format nr = int_pnum // 100 nc = int_pnum // 10 - (nr * 10) px = int_pnum - (nr * 100) - (nc * 10) pnum = (nr, nc, px) return pnum def _pnum_to_subspec(pnum): if isinstance(pnum, six.string_types): pnum = list(pnum) nrow, ncols, plotnum = pnum # if kwargs.get('use_gridspec', True): # Convert old pnums to gridspec gs = gridspec.GridSpec(nrow, ncols) if isinstance(plotnum, (tuple, slice, list)): subspec = gs[plotnum] else: subspec = gs[plotnum - 1] return (subspec,) def _setup_subfigure(pnum): if isinstance(pnum, int): pnum = _convert_pnum_int_to_tup(pnum) if doclf: fig.clf() axes_list = fig.get_axes() if docla or len(axes_list) == 0: if pnum is not None: assert pnum[0] > 0, 'nRows must be > 0: pnum=%r' % (pnum,) assert pnum[1] > 0, 'nCols must be > 0: pnum=%r' % (pnum,) subspec = _pnum_to_subspec(pnum) ax = fig.add_subplot(*subspec, projection=projection) if len(axes_list) > 0: ax.cla() else: ax = plt.gca() else: if pnum is not None: subspec = _pnum_to_subspec(pnum) ax = plt.subplot(*subspec) else: ax = plt.gca() fig = ensure_fig(fnum) if pnum is not None: _setup_subfigure(pnum) # Set the title / figtitle if title is not None: ax = plt.gca() ax.set_title(title) if figtitle is not None: fig.suptitle(figtitle) return fig def pandas_plot_matrix(df, rot=90, ax=None, grid=True, label=None, zerodiag=False, cmap='viridis', showvals=False, logscale=True): import matplotlib as mpl import copy from matplotlib import pyplot as plt if ax is None: fig = figure(fnum=1, pnum=(1, 1, 1)) fig.clear() ax = plt.gca() ax = plt.gca() values = df.values if zerodiag: values = values.copy() values = values - np.diag(np.diag(values)) # aximg = ax.imshow(values, interpolation='none', cmap='viridis') if logscale: from matplotlib.colors import LogNorm vmin = df[df > 0].min().min() norm = LogNorm(vmin=vmin, vmax=values.max()) else: norm = None cmap = copy.copy(mpl.cm.get_cmap(cmap)) # copy the default cmap cmap.set_bad((0, 0, 0)) aximg = ax.matshow(values, interpolation='none', cmap=cmap, norm=norm) # aximg = ax.imshow(values, interpolation='none', cmap='viridis', norm=norm) # ax.imshow(values, interpolation='none', cmap='viridis') ax.grid(False) cax = plt.colorbar(aximg, ax=ax) if label is not None: cax.set_label(label) ax.set_xticks(list(range(len(df.index)))) ax.set_xticklabels([lbl[0:100] for lbl in df.index]) for lbl in ax.get_xticklabels(): lbl.set_rotation(rot) for lbl in ax.get_xticklabels(): lbl.set_horizontalalignment('center') ax.set_yticks(list(range(len(df.columns)))) ax.set_yticklabels([lbl[0:100] for lbl in df.columns]) for lbl in ax.get_yticklabels(): lbl.set_horizontalalignment('right') for lbl in ax.get_yticklabels(): lbl.set_verticalalignment('center') # Grid lines around the pixels if grid: offset = -.5 xlim = [-.5, len(df.columns)] ylim = [-.5, len(df.index)] segments = [] for x in range(ylim[1]): xdata = [x + offset, x + offset] ydata = ylim segment = list(zip(xdata, ydata)) segments.append(segment) for y in range(xlim[1]): xdata = xlim ydata = [y + offset, y + offset] segment = list(zip(xdata, ydata)) segments.append(segment) bingrid = mpl.collections.LineCollection(segments, color='w', linewidths=1) ax.add_collection(bingrid) if showvals: x_basis = np.arange(len(df.columns)) y_basis = np.arange(len(df.index)) x, y = np.meshgrid(x_basis, y_basis) for c, r in zip(x.flatten(), y.flatten()): val = df.iloc[r, c] ax.text(c, r, val, va='center', ha='center', color='white') return ax def axes_extent(axs, pad=0.0): """ Get the full extent of a group of axes, including axes labels, tick labels, and titles. """ import itertools as it import matplotlib as mpl def axes_parts(ax): yield ax for label in ax.get_xticklabels(): if label.get_text(): yield label for label in ax.get_yticklabels(): if label.get_text(): yield label xlabel = ax.get_xaxis().get_label() ylabel = ax.get_yaxis().get_label() for label in (xlabel, ylabel, ax.title): if label.get_text(): yield label items = it.chain.from_iterable(axes_parts(ax) for ax in axs) extents = [item.get_window_extent() for item in items] #mpl.transforms.Affine2D().scale(1.1) extent = mpl.transforms.Bbox.union(extents) extent = extent.expanded(1.0 + pad, 1.0 + pad) return extent def extract_axes_extents(fig, combine=False, pad=0.0): # Make sure we draw the axes first so we can # extract positions from the text objects import matplotlib as mpl fig.canvas.draw() # Group axes that belong together atomic_axes = [] seen_ = set([]) for ax in fig.axes: if ax not in seen_: atomic_axes.append([ax]) seen_.add(ax) dpi_scale_trans_inv = fig.dpi_scale_trans.inverted() axes_bboxes_ = [axes_extent(axs, pad) for axs in atomic_axes] axes_extents_ = [extent.transformed(dpi_scale_trans_inv) for extent in axes_bboxes_] # axes_extents_ = axes_bboxes_ if combine: # Grab include extents of figure text as well # FIXME: This might break on OSX # http://stackoverflow.com/questions/22667224/bbox-backend renderer = fig.canvas.get_renderer() for mpl_text in fig.texts: bbox = mpl_text.get_window_extent(renderer=renderer) extent_ = bbox.expanded(1.0 + pad, 1.0 + pad) extent = extent_.transformed(dpi_scale_trans_inv) # extent = extent_ axes_extents_.append(extent) axes_extents = mpl.transforms.Bbox.union(axes_extents_) else: axes_extents = axes_extents_ # if True: # axes_extents.x0 = 0 # # axes_extents.y1 = 0 return axes_extents def adjust_subplots(left=None, right=None, bottom=None, top=None, wspace=None, hspace=None, fig=None): """ Kwargs: left (float): left side of the subplots of the figure right (float): right side of the subplots of the figure bottom (float): bottom of the subplots of the figure top (float): top of the subplots of the figure wspace (float): width reserved for blank space between subplots hspace (float): height reserved for blank space between subplots """ from matplotlib import pyplot as plt kwargs = dict(left=left, right=right, bottom=bottom, top=top, wspace=wspace, hspace=hspace) kwargs = {k: v for k, v in kwargs.items() if v is not None} if fig is None: fig = plt.gcf() subplotpars = fig.subplotpars adjust_dict = subplotpars.__dict__.copy() del adjust_dict['validate'] adjust_dict.update(kwargs) fig.subplots_adjust(**adjust_dict) def render_figure_to_image(fig, **savekw): import io import cv2 import matplotlib as mpl axes_extents = extract_axes_extents(fig) extent = mpl.transforms.Bbox.union(axes_extents) with io.BytesIO() as stream: # This call takes 23% - 15% of the time depending on settings fig.savefig(stream, bbox_inches=extent, **savekw) # fig.savefig(stream, **savekw) stream.seek(0) data = np.fromstring(stream.getvalue(), dtype=np.uint8) im_bgra = cv2.imdecode(data, cv2.IMREAD_UNCHANGED) return im_bgra def savefig2(fig, fpath, **kwargs): """ Does a tight layout and saves the figure with transparency """ import matplotlib as mpl if 'transparent' not in kwargs: kwargs['transparent'] = True if 'extent' not in kwargs: axes_extents = extract_axes_extents(fig) extent = mpl.transforms.Bbox.union(axes_extents) kwargs['extent'] = extent fig.savefig(fpath, **kwargs) def copy_figure_to_clipboard(fig): """ References: https://stackoverflow.com/questions/17676373/python-matplotlib-pyqt-copy-image-to-clipboard """ print('Copying figure %d to the clipboard' % fig.number) import matplotlib as mpl app = mpl.backends.backend_qt5.qApp QtGui = mpl.backends.backend_qt5.QtGui im_bgra = render_figure_to_image(fig, transparent=True) im_rgba = cv2.cvtColor(im_bgra, cv2.COLOR_BGRA2RGBA) im = im_rgba QImage = QtGui.QImage qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGBA8888) clipboard = app.clipboard() clipboard.setImage(qim) # size = fig.canvas.size() # width, height = size.width(), size.height() # qim = QtGui.QImage(fig.canvas.buffer_rgba(), width, height, QtGui.QImage.Format_ARGB32) # QtWidgets = mpl.backends.backend_qt5.QtWidgets # pixmap = QtWidgets.QWidget.grab(fig.canvas) # clipboard.setPixmap(pixmap)
StarcoderdataPython
3267439
'''Copyright (c) 2020, TDK Electronics All rights reserved. Author: <NAME>, https://github.com/mciepluc Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met (The BSD 2-Clause License): 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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 POTENTIAL VENTURES LTD 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. ''' """ Example packet switch testbench with functional coverage and constrained randomization. Simple packet switch is a module that routes packets from the input interface to output interfaces (1 or 2) depending on configured address or length based filter. Test generates random packets and checks if it has been transmitted correctly. """ import cocotb from cocotb.triggers import Timer, RisingEdge, ReadOnly from cocotb.drivers import BusDriver from cocotb.monitors import BusMonitor from cocotb_coverage.coverage import * from cocotb_coverage.crv import * import numpy as np class Packet(Randomized): def __init__(self, data = [0, 3, 0]): Randomized.__init__(self) self.addr = data[0] self.len = len(data) self.payload = data[2:] self.add_rand("addr", list(range(256))) self.add_rand("len", list(range(3,32))) def post_randomize(self): self.payload = [np.random.randint(256) for _ in range(self.len-2)] class PacketIFDriver(BusDriver): ''' Packet Interface Driver ''' _signals = ["data", "valid"] def __init__(self, entity, name, clock): BusDriver.__init__(self, entity, name, clock) self.clock = clock self.bus.data.setimmediatevalue(0) self.bus.valid.setimmediatevalue(0) @cocotb.coroutine def send(self, packet): self.bus.valid <= 1 # transmit header self.bus.data <= packet.addr yield RisingEdge(self.clock) self.bus.data <= packet.len yield RisingEdge(self.clock) for byte in packet.payload: self.bus.data <= byte yield RisingEdge(self.clock) self.bus.valid <= 0 yield RisingEdge(self.clock) class PacketIFMonitor(BusMonitor): ''' Packet Interface Monitor ''' _signals = ["data", "valid"] def __init__(self, entity, name, clock): BusMonitor.__init__(self, entity, name, clock) self.clock = clock @cocotb.coroutine def _monitor_recv(self): pkt_receiving = False received_data = [] while True: yield RisingEdge(self.clock) yield ReadOnly() if (self.bus.valid == 1): pkt_receiving = True received_data.append(int(self.bus.data)) elif pkt_receiving and (self.bus.valid == 0): # packet ended pkt = Packet(received_data) self._recv(pkt) pkt_receiving = False received_data = [] # simple clock generator @cocotb.coroutine def clock_gen(signal, period=10000): while True: signal <= 0 yield Timer(period/2) signal <= 1 yield Timer(period/2) @cocotb.test() def pkt_switch_test(dut): """ PKT_SWITCH Test """ log = cocotb.logging.getLogger("cocotb.test") # logger instance cocotb.fork(clock_gen(dut.clk, period=100)) # start clock running # reset & init dut.rst_n <= 1 dut.datain_data <= 0 dut.datain_valid <= 0 dut.ctrl_addr <= 0 dut.ctrl_data <= 0 dut.ctrl_wr <= 0 yield Timer(1000) dut.rst_n <= 0 yield Timer(1000) dut.rst_n <= 1 # procedure of writing configuration registers @cocotb.coroutine def write_config(addr, data): for [a, d] in zip(addr, data): dut.ctrl_addr <= a dut.ctrl_data <= d dut.ctrl_wr <= 1 yield RisingEdge(dut.clk) dut.ctrl_wr <= 0 enable_transmit_both = lambda: write_config([0], [4]) disable_filtering = lambda: write_config([0], [0]) @cocotb.coroutine def enable_addr_filtering(addr, mask): yield write_config([0, 2, 3], [1, addr, mask]) @cocotb.coroutine def enable_len_filtering(low_limit, up_limit): yield write_config([0, 4, 5], [2, low_limit, up_limit]) driver = PacketIFDriver(dut, name="datain", clock=dut.clk) monitor0 = PacketIFMonitor(dut, name="dataout0", clock=dut.clk) monitor1 = PacketIFMonitor(dut, name="dataout1", clock=dut.clk) expected_data0 = [] # queue of expeced packet at interface 0 expected_data1 = [] # queue of expeced packet at interface 1 def scoreboarding(pkt, queue_expected): assert pkt.addr == queue_expected[0].addr assert pkt.len == queue_expected[0].len assert pkt.payload == queue_expected[0].payload queue_expected.pop() monitor0.add_callback(lambda _ : scoreboarding(_, expected_data0)) monitor1.add_callback(lambda _ : scoreboarding(_, expected_data1)) monitor0.add_callback(lambda _ : log.info("Receiving packet on interface 0 (packet not filtered)")) monitor1.add_callback(lambda _ : log.info("Receiving packet on interface 1 (packet filtered)")) # functional coverage - check received packet @CoverPoint( "top.packet_length", xf = lambda pkt, event, addr, mask, ll, ul: pkt.len, # packet length bins = list(range(3,32)) # may be 3 ... 31 bytes ) @CoverPoint("top.event", vname="event", bins = ["DIS", "TB", "AF", "LF"]) @CoverPoint( "top.filt_addr", xf = lambda pkt, event, addr, mask, ll, ul: # filtering based on particular bits in header (addr & mask & 0x0F) if event == "AF" else None, # check only if event is "address filtering" bins = list(range(16)), # check only 4 LSBs if all options tested ) @CoverPoint( "top.filt_len_eq", xf = lambda pkt, event, addr, mask, ll, ul: ll == ul, # filtering of a single packet length bins = [True, False] ) @CoverPoint( "top.filt_len_ll", vname = "ll", # lower limit of packet length bins = list(range(3,32)) # 3 ... 31 ) @CoverPoint( "top.filt_len_ul", vname = "ul", # upper limit of packet length bins = list(range(3,32)) # 3 ... 31 ) @CoverCross( "top.filt_len_ll_x_packet_length", items = ["top.packet_length", "top.filt_len_ll"] ) @CoverCross( "top.filt_len_ul_x_packet_length", items = ["top.packet_length", "top.filt_len_ul"] ) def log_sequence(pkt, event, addr, mask, ll, ul): log.info("Processing packet:") log.info(" ADDRESS: %X", pkt.addr) log.info(" LENGTH: %d", pkt.len) log.info(" PAYLOAD: " + str(pkt.payload)) if event is "DIS": log.info("Filtering disabled") elif event is "TB": log.info("Transmit on both interfaces") elif event is "AF": log.info("Address filtering, address: %02X, mask: %02X", addr, mask) elif event is "LF": log.info("Length filtering, lower limit: %d, upper limit: %d", ll, ul) # main loop for _ in range(1000): # is that enough repetitions to ensure coverage goal? Check out! event = np.random.choice(["DIS", "TB", "AF", "LF"]) # DIS - disable filtering : expect all packets on interface 0 # TB - transmit bot : expect all packets on interface 0 and 1 # AF - address filtering : expect filtered packets on interface 1, others on 0 # LF - length filtering : expect filtered packets on interface 1, others on 0 # randomize test data pkt = Packet(); pkt.randomize() addr = np.random.randint(256) # 0x00 .. 0xFF mask = np.random.randint(256) # 0x00 .. 0xFF low_limit = np.random.randint(3,32) # 3 ... 31 up_limit = np.random.randint(low_limit,32) # low_limit ... 31 # expect the packet on the particular interface if event == "DIS": yield disable_filtering() expected_data0.append(pkt) elif event == "TB": yield enable_transmit_both() expected_data0.append(pkt) expected_data1.append(pkt) elif event == "AF": yield enable_addr_filtering(addr, mask) if ((pkt.addr & mask) == (addr & mask)): expected_data1.append(pkt) else: expected_data0.append(pkt) elif event == "LF": yield enable_len_filtering(low_limit, up_limit) if (low_limit <= pkt.len <= up_limit): expected_data1.append(pkt) else: expected_data0.append(pkt) # wait DUT yield driver.send(pkt) yield RisingEdge(dut.clk) yield RisingEdge(dut.clk) # LOG the action log_sequence(pkt, event, addr, mask, low_limit, up_limit) # print coverage report coverage_db.report_coverage(log.info, bins=False) # export coverage_db.export_to_xml(filename="coverage_pkt_switch.xml") coverage_db.export_to_yaml(filename="coverage_pkt_switch.yml")
StarcoderdataPython
3299053
<gh_stars>0 #!/usr/bin/env python3 # Copyright 2019 RaptorRants # This was for inputing dice but only accepted dice in format x x instead of x'd'x # print(DiceMainC) # UniqueCount = 'Y' # print("Provide your die rolls in format diecount dies1ize (Example: 2 12 is 2d12)") # count = 1 # while UniqueCount == 'Y' or UniqueCount == 'y': # while True: # try: # var2, var1 = [int(x) for x in input(f"Enter details of roll {count}: ").split()] # var1 and var2 will be passed as DieType nad DieSize. This value is swopped in this line to capture rolls before size but will be passed as Size/Rolls later to ensure the first variable is passed to dict as a unique key # except ValueError: # print('Invalid dice selection. Try again') # continue # else: # break # print(var1) # print(var2) # DiceMainS.append(var1) # adds var1 to DiceMainS list # DiceMainC.append(var2) # adds var2 to DiceMainC list # print(DiceMainS) # print(DiceMainC) # UniqueCount = input('Add another set? Y / N: ') # count += 1 # if UniqueCount == 'N' or UniqueCount == 'n': # break # else: # print('invalid option selected. Rolling dice selected so far') # print() #def print_history(self): # way 1 # for key, group in groupby(self.DiceHist(), key=itemgetter(1)): # print() # print(f'Starting with set {key}:') # print() # for item in group: # unpack_item0 =[item[0]] # for a, b, c in unpack_item0: # print(f'd{a} roll {c} result: {b}') # way 2 # count = 1 # for Result, Set in self.DiceHist(): # Display_Results =[ [x, v] for x, v in self.DiceHist() if v == count] # if len(Display_Results) != 0: # print() # print(f'Set {count}') # for Results, Set in Display_Results: # finalout = [Results] # for a,b,c in finalout: # print(f'd{a}, roll {c} :{b}') # print() # count += 1 # else: # break # Way 3 # ResultList = dict() # for res, n in self.DiceHist(): # ResultList[n] = ResultList.get(n, []) + [res] # for k, v in ResultList.items(): # print() # print(f'Results of Set {k}:') # Results = v # for a,b,c in Results: # print(f'd{a}, roll{c} = {b}') # print() # with open('Actions/DiceMainC.txt','a+') as WritetoFile, open('Actions/DiceMainS.txt','a+') as WritetoFile2: # for i in var1: # WritetoFile.write(str(i)) # WritetoFile.write(' ') # for i in var2: # WritetoFile2.write(str(i)) # WritetoFile2.write(' ')
StarcoderdataPython
3251488
<reponame>JongGuk/BOJ '''예전에는 운영체제에서 크로아티아 알파벳을 입력할 수가 없었다. 따라서, 다음과 같이 크로아티아 알파벳을 변경해서 입력했다. 예를 들어, ljes=njak은 크로아티아 알파벳 6개(lj, e, š, nj, a, k)로 이루어져 있다. 단어가 주어졌을 때, 몇 개의 크로아티아 알파벳으로 이루어져 있는지 출력한다. dž는 무조건 하나의 알파벳으로 쓰이고, d와 ž가 분리된 것으로 보지 않는다. lj와 nj도 마찬가지이다. 위 목록에 없는 알파벳은 한 글자씩 센다. 첫째 줄에 최대 100글자의 단어가 주어진다. 알파벳 소문자와 '-', '='로만 이루어져 있다. 단어는 크로아티아 알파벳으로 이루어져 있다. 문제 설명의 표에 나와있는 알파벳은 변경된 형태로 입력된다. 입력으로 주어진 단어가 몇 개의 크로아티아 알파벳으로 이루어져 있는지 출력한다.''' alpha = input() alpha = alpha.replace("c=","a") alpha = alpha.replace("c-","a") alpha = alpha.replace("dz=","a") alpha = alpha.replace("d-","a") alpha = alpha.replace("lj","a") alpha = alpha.replace("nj","a") alpha = alpha.replace("s=","a") replaced_alpha = alpha.replace("z=","a") print(len(replaced_alpha))
StarcoderdataPython
3318503
<filename>code/hf_creator.py import glob import json import cv2 import h5py import numpy as np import tqdm IMAGE_SIZE = (512, 256) # Resolution of the images in the annotation_set SKELETON_SIZE = 20 HOME = 'C:/Users/<NAME>/Desktop/IntellIj Local Files/Convert-BADJA-json/' def replace_slash(path): return path.replace('\\', '/') def images_sampler(url_list): frames = [] img_idx = 0 dict_img = {} for url in url_list: for image_file in tqdm.tqdm(glob.glob(url)): dict_img[replace_slash(image_file)] = img_idx img_idx += 1 img = cv2.imread(image_file) img = cv2.resize(img, IMAGE_SIZE) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) frames.append(img) return frames, dict_img, img_idx def delete_useless_joints(xy_list): new_xy_list = [] for i in range(8, 11): new_xy_list.append(xy_list[i]) for i in range(12, 16): new_xy_list.append(xy_list[i]) for i in range(18, 21): new_xy_list.append(xy_list[i]) for i in range(22, 26): new_xy_list.append(xy_list[i]) for i in range(28, 29): new_xy_list.append(xy_list[i]) for i in range(31, 34): new_xy_list.append(xy_list[i]) for i in range(35, 37): new_xy_list.append(xy_list[i]) return new_xy_list def swap_coordinates(xy_list): for i in range(len(xy_list)): x = xy_list[i][0] xy_list[i][0] = xy_list[i][1] xy_list[i][1] = x return xy_list def resize_coordinates(xy_list, rx, ry): resized_xy_list = [] for xy in xy_list: resized_xy_list.append([xy[0] * rx, xy[1] * ry]) return resized_xy_list def insert_nan(joints_list, skeleton_size, index): for idx in range(skeleton_size): if joints_list[index][idx][0] + joints_list[index][idx][1] == 0: joints_list[index][idx] = [np.nan, np.nan] return joints_list def fill_annotations_ds(original_res, badja_json_paths, index_dict, hf_file): for json_p, res in zip(badja_json_paths, original_res): resize_ratio_x = IMAGE_SIZE[0] / res[0] resize_ratio_y = IMAGE_SIZE[1] / res[1] joints_coordinates = [] num_ann = 0 j_file = open(json_p) j_data = json.load(j_file) for xy in j_data: joints = delete_useless_joints(xy['joints']) joints = swap_coordinates(joints) joints = resize_coordinates(joints, resize_ratio_x, resize_ratio_y) joints_coordinates.append(joints) image_name = xy['segmentation_path'] image_index = index_dict.get(HOME + image_name) joints_coordinates = insert_nan(joints_coordinates, SKELETON_SIZE, num_ann) hf_file["annotations"][image_index] = joints_coordinates[num_ann] hf_file["annotated"][image_index] = np.ones(SKELETON_SIZE, int) num_ann += 1 j_file.close() if __name__ == '__main__': hf = h5py.File(HOME + 'datasets/annotation_set_{}_{}.h5'.format(IMAGE_SIZE[0], IMAGE_SIZE[1]), 'w') # Creating 'skeleton' dataset. Make sure you have run the java file "skeleton_extractor" first. skeleton_hf = h5py.File(HOME + 'skeleton.h5', 'r') hf.create_dataset('skeleton', data=skeleton_hf['skeleton']) # Creating 'images' dataset urls = [HOME + 'extra_videos/rs_dog/segmentations/*.png', HOME + 'DAVIS/Annotations/Full-Resolution/dog/*.png', HOME + 'DAVIS/Annotations/Full-Resolution/dog-agility/*.png'] sampled_frames, idx_dict, num_images = images_sampler(urls) sampled_frames = np.concatenate(sampled_frames) sampled_frames = np.reshape(sampled_frames, (num_images, IMAGE_SIZE[1], IMAGE_SIZE[0], 1)) hf.create_dataset('images', data=sampled_frames) print('images dataset created') # Creating 'annotations' and 'annotated' datasets none_matrix = np.zeros((num_images, SKELETON_SIZE, 2)) for i in range(num_images): for j in range(SKELETON_SIZE): none_matrix[i][j] = np.nan hf.create_dataset('annotations', dtype=np.float64, data=none_matrix) hf.create_dataset('annotated', shape=(num_images, SKELETON_SIZE), dtype=bool) # Maybe you want to convert different json(s), well: # change the json files inside the directory and modify this row of code. fill_annotations_ds([(1280, 720), (1920, 1080), (1920, 1080)], [HOME + 'rs_dog.json', HOME + 'dog.json', HOME + 'dog_agility.json'], idx_dict, hf) print('annotations dataset created') print('annotated dataset created') hf.close()
StarcoderdataPython
4809892
import logging from pydano.cardano_cli import CardanoCli class PolicyIDTransaction(CardanoCli): def __init__(self, testnet: bool = True): super().__init__(testnet) @property def base_command(self): return ["cardano-cli", "transaction", "policyid"] def policyID(self, script_file): command = self.base_command command.append("--script-file") command.append(script_file) capturedout = self.run_command(command) policyid = capturedout.stdout.strip().decode("utf-8") logging.info(f"Policy ID for minting script {script_file} is {policyid}") return policyid
StarcoderdataPython
1629350
import gin import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten,\ BatchNormalization from tensorflow.keras.initializers import GlorotUniform tf.random.set_seed(1234) def conv_net(nbr_classes, img_size = 128): """Reproduce the CNN used in the MAML paper. It was originally designed in Vinyals and al. (2016) . Conv layers kernels are initialized with Glorot Uniform by default.""" model = Sequential() model.add(Conv2D(128, (3, 3), strides = (1, 1), activation='relu',\ input_shape=(img_size, img_size, 3), kernel_initializer=GlorotUniform(seed=1234))) model.add(BatchNormalization()) model.add(MaxPooling2D((2, 2))) model.add(Conv2D(64, (3, 3), strides = (1, 1), activation='relu', kernel_initializer=GlorotUniform(seed=1234))) model.add(BatchNormalization()) model.add(MaxPooling2D((2, 2))) model.add(Conv2D(64, (3, 3), strides = (1, 1), activation='relu', kernel_initializer=GlorotUniform(seed=1234))) model.add(BatchNormalization()) model.add(MaxPooling2D((2, 2))) model.add(Conv2D(64, (3, 3), strides = (1, 1), activation='relu', kernel_initializer=GlorotUniform(seed=1234))) model.add(BatchNormalization()) model.add(MaxPooling2D((2, 2))) model.add(Conv2D(64, (3, 3), strides = (1, 1), activation='relu', kernel_initializer=GlorotUniform(seed=1234))) model.add(BatchNormalization()) model.add(MaxPooling2D((2, 2))) model.add(Flatten()) return model
StarcoderdataPython
3792
from django.test import TestCase # Create your tests here. from crawler.download import * from crawler.models import * class AnimalDownloadTestCase(TestCase): def setUp(self): self.stopWords = ["CVPR 2019", "Computer Vision Foundation."] self.url = "/Users/tuannguyenanh/Desktop/cvpr2019.html"#"http://openaccess.thecvf.com/CVPR2019.py" self.root = "http://openaccess.thecvf.com/" self.event = Event.objects.filter(shortname='CVPR2019').first() if self.event is None: self.event = Event(shortname='CVPR2019') self.event.save() def test_animal_can_download(self): #print(get_html(self.url)) f = open(self.url) soup = parse_html(f.read()) f.close() f = open('cvpr2019.bib', 'w') print(soup.title) bibtexs = soup.find_all("div", attrs={"class": "bibref"}) #print(bibtexs) for bib in bibtexs: print(bib.text) f.write(bib.text.replace('<br>', '\n')) f.close()
StarcoderdataPython
4807794
<reponame>jmhubbard/quote_of_the_day_custom_user from shows.models import Show #Returns a QuerySet of only active shows def getActiveShows(): return Show.objects.filter(is_active = True)
StarcoderdataPython
1693343
from django import forms from django.contrib.auth.forms import UserCreationForm from .models import User class Signupform(UserCreationForm): class Meta: model=User fields=('email','first_name','last_name','role','avatar','Mobile_Number','profession')
StarcoderdataPython
4802380
from fastapi import FastAPI app = FastAPI() @app.get("/users") async def get_user(page: int = 1, size: int = 10): return {"page": page, "size": size}
StarcoderdataPython
3355721
<filename>txircd/modules/server/metadatasync.py from twisted.plugin import IPlugin from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from txircd.utils import timestamp from zope.interface import implements from datetime import datetime class ServerMetadata(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "ServerMetadata" core = True def actions(self): return [ ("usermetadataupdate", 10, self.propagateUserMetadata), ("channelmetadataupdate", 10, self.propagateChannelMetadata) ] def serverCommands(self): return [ ("METADATA", 1, self) ] def propagateMetadata(self, targetID, targetTime, key, value, visibility, setByUser, fromServer): serverPrefix = fromServer.serverID if fromServer else self.ircd.serverID if value is None: self.ircd.broadcastToServers(fromServer, "METADATA", targetID, targetTime, key, visibility, "1" if setByUser else "0", prefix=serverPrefix) else: self.ircd.broadcastToServers(fromServer, "METADATA", targetID, targetTime, key, visibility, "1" if setByUser else "0", value, prefix=serverPrefix) def propagateUserMetadata(self, user, key, oldValue, value, visibility, setByUser, fromServer): self.propagateMetadata(user.uuid, str(timestamp(user.connectedSince)), key, value, visibility, setByUser, fromServer) def propagateChannelMetadata(self, channel, key, oldValue, value, visibility, setByUser, fromServer): self.propagateMetadata(channel.name, str(timestamp(channel.existedSince)), key, value, visibility, setByUser, fromServer) def clearMetadata(self, target, server): metadataToClear = target.metadataList() for key, value, visibility, setByUser, in metadataToClear: target.setMetadata(key, None, visibility, setByUser, server) def parseParams(self, server, params, prefix, tags): if len(params) not in (5, 6): return None data = {} if params[0] in self.ircd.users: data["user"] = self.ircd.users[params[0]] elif params[0] in self.ircd.channels: data["channel"] = self.ircd.channels[params[0]] elif params[0] in self.ircd.recentlyQuitUsers or params[0] in self.ircd.recentlyDestroyedChannels: return { "losttarget": True } else: return None try: data["time"] = datetime.utcfromtimestamp(int(params[1])) except ValueError: return None data["key"] = params[2] data["visibility"] = params[3] try: data["setbyuser"] = int(params[4]) > 0 except ValueError: return None if len(params) == 6: data["value"] = params[5] return data def execute(self, server, data): if "losttarget" in data: return True if "user" in data: target = data["user"] if data["time"] > target.connectedSince: self.clearMetadata(target, server) return True else: target = data["channel"] if data["time"] > target.existedSince: self.clearMetadata(target, server) return True if "value" in data: value = data["value"] else: value = None return target.setMetadata(data["key"], value, data["visibility"], data["setbyuser"], server) serverMetadata = ServerMetadata()
StarcoderdataPython
126227
<filename>layers/pool.py """ Pooling layers. """ import numpy as np import tensorflow as tf from central import layers_base class Pooling(layers_base.NNLayer): """ Maxpool and Averagepool layers. """ def __init__(self, input_var, layer_name, kernel_size, strides, padding='SAME', pool='MAX'): # Either 'MAX' or 'AVG' self._input_var = input_var self._kernel_size = kernel_size self._strides = strides self._pad = padding self._layer_type = pool super(Pooling, self).__init__( name=layer_name, input_shape=input_var.get_shape().as_list(), use_bias=False ) def forward(self): with tf.variable_scope(self._name): if len(self._inputs_shape) == 4: if self._layer_type == 'MAX': pool = tf.nn.max_pool( value=self._input_var, ksize=self._kernel_size, strides=self._strides, padding=self._pad, ) elif self._layer_type == 'AVG': pool = tf.nn.avg_pool( value=self._input_var, ksize=self._kernel_size, strides=self._strides, padding=self._pad, ) elif len(self._inputs_shape) == 5: if self._layer_type == 'MAX': pool = tf.nn.max_pool3d( input=self._input_var, ksize=self._kernel_size, strides=self._strides, padding=self._pad, ) elif self._layer_type == 'AVG': pool = tf.nn.avg_pool3d( input=self._input_var, ksize=self._kernel_size, strides=self._strides, padding=self._pad, ) return pool
StarcoderdataPython
95073
<filename>crawler/python newwork data collection/3/3.2.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- from urllib.request import urlopen from bs4 import BeautifulSoup import re pages = set() def getLinks(pageUrl): global pages html = urlopen('http://en.wikipedia.org'+pageUrl) bsobj = BeautifulSoup(html) try: print(bsobj.h1.get_text()) print(bsobj.find(id='mw-content-text').findAll('p')[0]) print(bsobj.find(id='ca-edit').find('span').find('a').attrs['href']) except AttributeError: print('页面缺少一些属性') for link in bsobj.findAll('a', href=re.compile('^(/wiki/)')): if 'href' in link.attrs: if link.attrs['href'] not in pages: newpage = link.attrs['href'] print('----\n'+newpage) pages.add(newpage) getLinks(newpage) getLinks('')
StarcoderdataPython
3378773
<filename>xlson/scheme/setup_xlson.py from functools import reduce from operator import getitem from jsondler import JsonEntry class XLSonScheme(JsonEntry): # json keys main_sheet_key = "main_sheet" supp_sheets_key = "supp_sheets" source_path_key = "source_path" # default values main_sheet_0 = dict() supp_sheets_0 = list() source_path_0 = None def __init__(self, main_sheet=None, supp_sheets=None, source_path=source_path_0): if main_sheet is None: main_sheet = self.main_sheet_0 if supp_sheets is None: supp_sheets = self.supp_sheets_0 self.main_sheet = main_sheet self.supp_sheets = supp_sheets self.source_path = source_path @classmethod def attr_scheme(cls): """ json scheme (the keys must match attribute names defined in __init__) CAUTION: if attribute is not defined in __init__ method (sublevel key in a json) don't include it to the result dict :return: {attr_name: (path, in, json, entry,), ...} """ return { "main_sheet": (cls.main_sheet_key,), "supp_sheets": (cls.supp_sheets_key,), "source_path": (cls.source_path_key,), } class XLSonSheetScheme(JsonEntry): # json keys data_df_key = "data_df" meta_df_key = "meta_df" entites_key = "entities" supp_sheets_key = XLSonScheme.supp_sheets_key cell_default_meta_key = "cell_default_meta" sheet_name_key = "sheet_name" # default values data_df_0 = list() meta_df_0 = list() entites_0 = list() cell_default_meta_0 = dict() supp_sheets_0 = list() sheet_name_0 = None main_sheet = False def __init__(self, data_df=None, meta_df=None, entities=None, cell_default_meta=None, sheet_name=sheet_name_0, **kwargs): if data_df is None: data_df = self.data_df_0 if meta_df is None: meta_df = self.meta_df_0 if entities is None: entities = self.entites_0 if cell_default_meta is None: cell_default_meta = self.cell_default_meta_0 self.data_df = data_df self.meta_df = meta_df self.entities = entities self.cell_default_meta = cell_default_meta self._sheet_name = sheet_name if self.main_sheet: self.supp_sheets = kwargs.get("supp_sheets", self.supp_sheets_0) @classmethod def attr_scheme(cls): """ json scheme (the keys must match attribute names defined in __init__) CAUTION: if attribute is not defined in __init__ method (sublevel key in a json) don't include it to the result dict :return: {attr_name: (path, in, json, entry,), ...} """ attr_scheme = { "data_df": (cls.data_df_key,), "meta_df": (cls.meta_df_key,), "entities": (cls.entites_key,), "cell_default_meta": (cls.cell_default_meta_key,), "_sheet_name": (cls.sheet_name_key,), } if cls.main_sheet: attr_scheme["supp_sheets"] = (cls.supp_sheets_key,) return attr_scheme def get_json(self): got_json = super(XLSonSheetScheme, self).get_json() if self.main_sheet: supp_sheets_path = (self.supp_sheets_key,) # WARNING: duplication reduce(getitem, supp_sheets_path[:-1], got_json)[supp_sheets_path[-1]] = self.supp_sheets return got_json class EntityInfo(JsonEntry): # json keys id_key = "id" type_key = "type" location_key = "location" content_key = "content" row_key = "row" col_key = "col" start_key = "start" end_key = "end" content_full_key = "full" other_cells_key = "other_cells" # default values ent_id_0 = int() ent_type_0 = None ent_content_full_0 = None, ent_content_start_0 = 0, ent_content_end_0 = -1, ent_loc_row_0 = int(), ent_loc_col_0 = int(), ent_loc_start_0 = 0, ent_loc_end_0 = -1, ent_loc_other_cells_0 = None additional_attrs = list() def __init__(self, ent_id=ent_id_0, ent_type=ent_type_0, ent_content_full=ent_content_full_0, ent_content_start=ent_content_start_0, ent_content_end=ent_content_end_0, ent_loc_row=ent_loc_row_0, ent_loc_col=ent_loc_col_0, ent_loc_start=ent_loc_start_0, ent_loc_end=ent_loc_end_0, ent_loc_other_cells=ent_loc_other_cells_0, **kwargs): self.ent_id = ent_id self.ent_type = ent_type self.ent_content_full = ent_content_full self.ent_content_start = ent_content_start self.ent_content_end = ent_content_end self.ent_loc_row = ent_loc_row self.ent_loc_col = ent_loc_col self.ent_loc_start = ent_loc_start self.ent_loc_end = ent_loc_end self.ent_loc_other_cells = ent_loc_other_cells used_attrs = list(self.__dict__.keys()) for attr in kwargs: if attr not in used_attrs: self.__dict__[attr] = kwargs[attr] used_attrs.append(attr) if attr not in self.additional_attrs: self.additional_attrs.append(attr) for attr in self.additional_attrs: if attr not in used_attrs: self.__dict__[attr] = None used_attrs.append(attr) def __getitem__(self, item): return self.get_json()[item] def __setitem__(self, key, value): got_json = self.get_json() got_json[key] = value self.__dict__ = self.load_from_dict(got_json).__dict__ @classmethod def attr_scheme(cls): """ json scheme (the keys must match attribute names defined in __init__) CAUTION: if attribute is not defined in __init__ method (sublevel key in a json) don't include it to the result dict :return: {attr_name: (path, in, json, entry,), ...} """ attr_scheme = { "ent_id": (cls.id_key,), "ent_type": (cls.type_key,), "ent_content_full": (cls.content_key, cls.content_full_key), "ent_content_start": (cls.content_key, cls.start_key), "ent_content_end": (cls.content_key, cls.end_key), "ent_loc_row": (cls.location_key, cls.row_key), "ent_loc_col": (cls.location_key, cls.col_key), "ent_loc_start": (cls.location_key, cls.start_key), "ent_loc_end": (cls.location_key, cls.end_key), "ent_loc_other_cells": (cls.location_key, cls.other_cells_key), } attr_scheme.update({attr: (attr,) for attr in cls.additional_attrs}) return attr_scheme @property def ent_content(self): return EntityContent(self) @property def ent_location(self): return EntityLocation(self) class EntityContent(object): def __init__(self, entity_info): assert isinstance(entity_info, EntityInfo) self._entity_info = entity_info @property def full(self): return self._entity_info.ent_content_full @full.setter def full(self, value): self._entity_info.ent_content_full = value @property def start(self): return self._entity_info.ent_content_start @start.setter def start(self, value): self._entity_info.ent_content_start = value @property def end(self): return self._entity_info.ent_content_end @end.setter def end(self, value): self._entity_info.ent_content_end = value class EntityLocation(object): def __init__(self, entity_info): assert isinstance(entity_info, EntityInfo) self._entity_info = entity_info @property def row(self): return self._entity_info.ent_loc_row @row.setter def row(self, value): self._entity_info.ent_loc_row = value @property def col(self): return self._entity_info.ent_loc_col @col.setter def col(self, value): self._entity_info.ent_loc_col = value @property def start(self): return self._entity_info.ent_loc_start @start.setter def start(self, value): self._entity_info.ent_loc_start = value @property def end(self): return self._entity_info.ent_loc_end @end.setter def end(self, value): self._entity_info.ent_loc_end = value @property def other_cells(self): return self._entity_info.ent_loc_other_cells @other_cells.setter def other_cells(self, value): self._entity_info.ent_loc_other_cells = value
StarcoderdataPython
198626
<gh_stars>0 def convert(s): s_split = s.split(' ') return s_split def niceprint(s): for i, elm in enumerate(s): print('Element #', i + 1, ' = ', elm, sep='') return None c1 = 10 c2 = 's'
StarcoderdataPython
59732
<filename>web/backend/models.py from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles from pygments.lexers import get_lexer_by_name from pygments.formatters.html import HtmlFormatter from pygments import highlight from django.conf import settings from django.contrib.auth.models import User from django.core.files.storage import FileSystemStorage import os import logging from pathlib import Path import pathlib from pyadlml.dataset.activities import _create_activity_df from django.core.files import File from django.http import FileResponse from backend.util import create_zip logger = logging.getLogger(__name__) #from django.db.models.signals import post_save #from django.dispatch import receiver #from rest_framework.authtoken.models import Token def person_path(instance, filename): # file will be uploaded to MEDIA_ROOT/activities_subject_<person.name>.csv return settings.ACTIVITY_FILE_NAME%(instance.name) class OverwriteStorage(FileSystemStorage): ''' this is used to overwrite existing files in a put request for FileField cases as in Person and model ''' def get_available_name(self, name, max_length): if self.exists(name): os.remove(os.path.join(settings.MEDIA_ROOT, name)) return name class Dataset(models.Model): # todo mark for deletion line below name = models.CharField(null=True, max_length=100) path_to_folder = models.CharField(null=True, max_length=100) start_time = models.DateTimeField(null=True) end_time = models.DateTimeField(null=True) num_devices = models.IntegerField(null=True) num_recorded_events = models.IntegerField(null=True) data_size = models.IntegerField(null=True) plot_hist_counts = models.ImageField(null=True) plot_hist_on_off = models.ImageField(null=True) plot_boxplot_on_duration = models.ImageField(null=True) plot_heatmap_trigger_one_day = models.ImageField(null=True) plot_heatmap_trigger_time = models.ImageField(null=True) plot_hist_trigger_time_diff = models.ImageField(null=True) plot_heatmap_cross_correlation = models.ImageField(null=True) def delete(self, *args, **kwargs): """ perform additional cleanup when deleting a dataset """ import shutil # cleanup the mediafiles/plots associated with the person statistics and dataset try: shutil.rmtree(settings.MEDIA_ROOT + self.name) except FileNotFoundError: pass super().delete(*args, **kwargs) def get_fileResponse(self): """ zips the dataset and returns a fileResponse object that is served to the user Returns ------- fp : FileResponse a reponse object that servers a ZIP file """ # create zip at location path_to_zip = settings.MEDIA_ROOT + self.name + ".zip" create_zip(self.path_to_folder, path_to_zip) # create response zip_file = open(path_to_zip, 'rb') response = FileResponse(zip_file) # cleanup zip file rem_file = pathlib.Path(path_to_zip) rem_file.unlink() return response class PersonStatistic(models.Model): name = models.CharField(null=True, max_length=100) dataset = models.ForeignKey(Dataset, related_name="person_statistics", on_delete=models.CASCADE) activity_file = models.FileField(null=True) num_activities = models.IntegerField(null=True) num_recorded_activities = models.IntegerField(null=True) plot_hist_counts = models.ImageField(null=True) plot_hist_cum_duration = models.ImageField(null=True) plot_boxplot_duration = models.ImageField(null=True) plot_ridge_line = models.ImageField(null=True) plot_heatmap_transitions = models.ImageField(null=True) def get_activity_fp(self): """ returns filepath to activity file """ return os.path.join(self.dataset.path_to_folder, settings.ACTIVITY_FILE_NAME%(self.name) ) class Person(models.Model): name = models.CharField(max_length=20, blank=True, default='') hass_name = models.CharField(max_length=20, blank=True, default='') person_statistic = models.OneToOneField(PersonStatistic, null=True, on_delete=models.SET_NULL, related_name='person') prediction = models.BooleanField(default=False, blank=True) activity_file = models.FileField(null=True, upload_to=person_path, storage=OverwriteStorage()) def save(self, *args, **kwargs): # create additional user with one to one relationship so that # one device can't alter the anything but its own person #User.objects.create_user(username=self.name, email='<EMAIL>', password='<PASSWORD>') super(Person, self).save(*args, **kwargs) # check if there is a file attached to person if not create empty one try: self.activity_file.path except ValueError: self.reset_activity_file() def reset_activity_file(self): """ creates inital and assigns activity file File looks like this start_time, end_time, activity """ fp = settings.MEDIA_ROOT + settings.ACTIVITY_FILE_NAME%(self.name) output_dir = Path(settings.MEDIA_ROOT) output_dir.mkdir(parents=True, exist_ok=True) tmp = _create_activity_df() tmp.to_csv(fp, sep=',', index=False) self.activity_file = File(open(fp)) self.save() # A Location presents a vertice in a Graph # Graph := (G, E) # v\in E class Location(models.Model): node_id = models.IntegerField() x = models.IntegerField() y = models.IntegerField() name = models.CharField(max_length=40) class Meta: ordering = ["name"] # an edge connects to locations with each other # e = (v,w) | v,w \in G class Edge(models.Model): # if a node is deleted, the edge is also deleted source = models.ForeignKey(Location, on_delete=models.CASCADE, related_name='source') sink = models.ForeignKey(Location, on_delete=models.CASCADE) distance = models.IntegerField(default=0) class Meta: ordering = ["source"] # is something like a sensor, switch, or whatever class Device(models.Model): name = models.CharField(max_length=40) #area = models.ForeignKey(Location, null=True, on_delete=models.SET_NULL) # many to one relation with person # many persons can do the same activity, but a person can do only one activity at once class Activity(models.Model): name = models.CharField(max_length=40) #locations = models.ManyToManyField(Location, related_name='activities') class Meta: ordering = ["name"] class ActivityPrediction(models.Model): person = models.ForeignKey(Person, null=True, blank=True, on_delete=models.CASCADE, related_name='predicted_activities') predicted_activity = models.ForeignKey(Activity, null=True, blank=True, on_delete=models.SET_NULL, related_name='%(class)s_predicted') score = models.FloatField() class SyntheticActivity(models.Model): person = models.ForeignKey(Person, null=True, blank=True, on_delete=models.CASCADE, related_name='synthetic_activities') #synthetic_activity = models.ForeignKey(Activity, null=True, blank=True, on_delete=models.SET_NULL, related_name='%(class)s_predicted') synthetic_activity = models.ForeignKey(Activity, null=False, blank=False, on_delete=models.CASCADE, related_name='%(class)s_predicted') # day of week (0 - 6) Sunday - Saturday day_of_week = models.IntegerField() start = models.TimeField() end = models.TimeField() class Smartphone(models.Model): """ represents the android app installed on one smartphone there can be persons without smartphone there can be no smartphone without a person """ #owner = models.ForeignKey('auth.User', related_name='smartphones', on_delete=models.CASCADE) name = models.CharField(max_length=40) # if a person is deleted so should the smartphone person = models.OneToOneField(Person, blank=True, on_delete=models.CASCADE)#, primary_key=True) logging = models.BooleanField(default=False) synchronized = models.BooleanField(default=False) logged_activity = models.ForeignKey(Activity, null=True, on_delete=models.SET_NULL, related_name='%(class)s_logged') class Model(models.Model): person = models.ForeignKey(Person, null=True, on_delete=models.CASCADE) # TODO rename file to sth more accurate file = models.FileField(null=True) visualization = models.ImageField(null=True) train_loss = models.FileField(null=True) train_loss_graph = models.ImageField(null=True) class RealTimeNode(models.Model): pid = models.IntegerField(default=0) model = models.ForeignKey(Model, on_delete=models.CASCADE) status = models.CharField(max_length=10, null=True) class DevicePrediction(models.Model): rt_node = models.ForeignKey(RealTimeNode, blank=True, on_delete=models.CASCADE, related_name='predicted_devices') predicted_state = models.ForeignKey(Device, null=True, blank=True, on_delete=models.CASCADE, related_name='%(class)s_predicted') score = models.FloatField() class Server(models.Model): server_address = models.CharField(max_length=40, null=True) hass_api_token = models.CharField(max_length=200, null=True) hass_comp_installed = models.BooleanField(default=False) hass_db_url = models.CharField(max_length=200, null=True) selected_model = models.ForeignKey(Model, null=True, on_delete=models.SET_NULL, related_name='model') realtime_node = models.ForeignKey(RealTimeNode, null=True, on_delete=models.SET_NULL) setup = models.CharField(max_length=10, null=True, default='step 0') is_polling = models.BooleanField(default=False) poll_interval = models.CharField(max_length=10, default='10m') dataset = models.ForeignKey(Dataset, null=True, blank=True, on_delete=models.CASCADE, related_name='synthetic_activities') zero_conf_pid = models.IntegerField(null=True) poll_service_pid = models.IntegerField(null=True) plot_gen_service_pid = models.IntegerField(null=True) time_zone = models.CharField(max_length=20, null=True) webhook_count = models.IntegerField(default=0)
StarcoderdataPython
132995
<reponame>Daph1986/postfly_jouw_online_drukkerij<gh_stars>0 # Generated by Django 3.2.6 on 2021-11-17 13:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('checkout', '0014_alter_order_artwork'), ] operations = [ migrations.AlterField( model_name='order', name='artwork', field=models.FileField(default='', upload_to='artwork/%Y/%m/%d'), ), ]
StarcoderdataPython
1600545
<filename>test/test_add_contact.py # -*- coding: utf-8 -*- from model.contact import Contact def test_enter_contact(app): app.session.login(username = "admin", password = "<PASSWORD>") app.contact.create(Contact(firstname ="Anton", middlename ="Wiktor", lastname ="Lund", nickname ="alund", title ="Cola", company ="Coca Cola", address ="Kungsgatan 11, lgh 4", home ="City", mobile = "46(67)324-23-23", work = "test", fax = "41", email = "<EMAIL>", email2 = "<EMAIL>", homepage = "www.tut.by", email3 = "<EMAIL>", bday = "5", bmonth = "January", byear = "1980", new_group = "group1", notes = "Test note", phone2 = "123123132", address2 = "adress 2", ayear = "1990", amonth = "January", aday = "5")) app.session.logout()
StarcoderdataPython
177441
<reponame>pwwang/biopipen from bioprocs.utils import FileConn infile = {{i.infile | quote}} outfile = {{o.outfile | quote}} chrom = {{args.chr | quote}} with FileConn(infile) as f, open(outfile, 'w') as fout: for line in f: if line.startswith('##contig='): contig = line.rstrip('>\n')[10:].split(',') items = [] for cont in contig: name, val = cont.split('=', 1) if name == 'ID': val = chrom + val if not val.startswith(chrom) else val items.append('{}={}'.format(name, val)) fout.write('##contig=<{}>\n'.format(','.join(items))) elif line.startswith('#') or line.startswith(chrom): fout.write(line) else: fout.write(chrom + line)
StarcoderdataPython
1722890
#!/usr/bin/env python import pytest """ Test 1771. Maximize Palindrome Length From Subsequences """ @pytest.fixture(scope="session") def init_variables_1771(): from src.leetcode_1771_maximize_palindrome_length_from_subsequences import Solution solution = Solution() def _init_variables_1771(): return solution yield _init_variables_1771 class TestClass1771: def test_solution_0(self, init_variables_1771): assert init_variables_1771().longestPalindrome("cacb", "cbba") == 5 def test_solution_1(self, init_variables_1771): assert init_variables_1771().longestPalindrome("ab", "ab") == 3 def test_solution_2(self, init_variables_1771): assert init_variables_1771().longestPalindrome("aa", "bb") == 0
StarcoderdataPython
3317927
<reponame>OCHA-DAP/hdx-data-freshness<filename>tests/hdx/freshness/test_freshness_day0.py """ Unit tests for the freshness class. """ import os from os.path import join import pytest from hdx.database import Database from hdx.freshness.database.dbdataset import DBDataset from hdx.freshness.database.dbinfodataset import DBInfoDataset from hdx.freshness.database.dborganization import DBOrganization from hdx.freshness.database.dbresource import DBResource from hdx.freshness.database.dbrun import DBRun from hdx.freshness.datafreshness import DataFreshness from hdx.freshness.testdata.dbtestresult import DBTestResult from hdx.freshness.testdata.serialize import ( deserialize_datasets, deserialize_hashresults, deserialize_now, deserialize_results, ) class TestFreshnessDay0: @pytest.fixture(scope="function") def nodatabase(self): dbpath = join("tests", "test_freshness.db") try: os.remove(dbpath) except FileNotFoundError: pass return {"driver": "sqlite", "database": dbpath} @pytest.fixture(scope="class") def serializedbsession(self): dbpath = join("tests", "fixtures", "day0", "test_serialize.db") return Database.get_session(f"sqlite:///{dbpath}") @pytest.fixture(scope="function") def now(self, serializedbsession): return deserialize_now(serializedbsession) @pytest.fixture(scope="function") def datasets(self, serializedbsession): return deserialize_datasets(serializedbsession) @pytest.fixture(scope="function") def results(self, serializedbsession): return deserialize_results(serializedbsession) @pytest.fixture(scope="function") def hash_results(self, serializedbsession): return deserialize_hashresults(serializedbsession) @pytest.fixture(scope="function") def forced_hash_ids(self, serializedbsession): forced_hash_ids = serializedbsession.query(DBTestResult.id).filter_by( force_hash=1 ) return [x[0] for x in forced_hash_ids] def test_generate_dataset( self, configuration, nodatabase, now, datasets, results, hash_results, forced_hash_ids, resourcecls, ): with Database(**nodatabase) as session: freshness = DataFreshness(session=session, datasets=datasets, now=now) freshness.spread_datasets() freshness.add_new_run() datasets_to_check, resources_to_check = freshness.process_datasets( hash_ids=forced_hash_ids ) results, hash_results = freshness.check_urls( resources_to_check, "test", results=results, hash_results=hash_results ) resourcecls.populate_resourcedict(datasets) datasets_lastmodified = freshness.process_results( results, hash_results, resourcecls=resourcecls ) freshness.update_dataset_latest_of_modifieds( datasets_to_check, datasets_lastmodified ) output = freshness.output_counts() assert ( output == """ *** Resources *** * total: 660 *, api: 4, error: 27, first hash: 9, firstrun: 564, internal-firstrun: 56 *** Datasets *** * total: 103 *, 0: Fresh, Updated firstrun: 67, 1: Due, Updated firstrun: 1, 2: Overdue, Updated firstrun: 1, 3: Delinquent, Updated firstrun: 25, 3: Delinquent, Updated firstrun,error: 5, Freshness Unavailable, Updated firstrun: 4 15 datasets have update frequency of Live 19 datasets have update frequency of Never 0 datasets have update frequency of Adhoc""" ) dbsession = freshness.session dbrun = dbsession.query(DBRun).one() assert str(dbrun) == "<Run number=0, Run date=2017-12-18 16:03:33.208327>" dbresource = dbsession.query(DBResource).first() assert ( str(dbresource) == """<Resource(run number=0, id=b21d6004-06b5-41e5-8e3e-0f28140bff64, name=Topline Numbers.csv, dataset id=a2150ad9-2b87-49f5-a6b2-c85dff366b75, url=https://docs.google.com/spreadsheets/d/e/2PACX-1vRjFRZGLB8IMp0anSGR1tcGxwJgkyx0bTN9PsinqtaLWKHBEfz77LkinXeVqIE_TsGVt-xM6DQzXpkJ/pub?gid=0&single=true&output=csv, last modified=2017-12-16 15:11:15.202742, metadata modified=2017-12-16 15:11:15.202742, latest of modifieds=2017-12-16 15:11:15.202742, what updated=first hash, http last modified=None, MD5 hash=be5802368e5a6f7ad172f27732001f3a, hash last modified=None, when checked=2017-12-18 16:03:33.208327, api=False, error=None)>""" ) count = ( dbsession.query(DBResource) .filter(DBResource.url.like("%data.humdata.org%")) .count() ) assert count == 56 count = ( dbsession.query(DBResource) .filter_by(what_updated="internal-firstrun", error=None, api=None) .count() ) assert count == 56 count = ( dbsession.query(DBResource) .filter_by(what_updated="internal-firstrun,hash", error=None, api=False) .count() ) assert count == 0 count = ( dbsession.query(DBResource) .filter_by( what_updated="internal-firstrun,http header,hash", error=None, api=False, ) .count() ) assert count == 0 count = ( dbsession.query(DBResource) .filter_by(what_updated="firstrun", error=None, api=None) .count() ) assert count == 564 count = ( dbsession.query(DBResource) .filter_by(what_updated="firstrun", error=None, api=True) .count() ) assert count == 4 count = ( dbsession.query(DBResource) .filter(DBResource.error.isnot(None)) .filter_by(what_updated="firstrun") .count() ) assert count == 27 count = ( dbsession.query(DBResource) .filter_by(what_updated="first hash", error=None, api=False) .count() ) assert count == 9 count = ( dbsession.query(DBResource) .filter_by(what_updated="http header", error=None, api=None) .count() ) assert count == 0 count = ( dbsession.query(DBResource) .filter_by(what_updated="http header,hash", error=None, api=False) .count() ) assert count == 0 dbdataset = dbsession.query(DBDataset).first() assert ( str(dbdataset) == """<Dataset(run number=0, id=a2150ad9-2b87-49f5-a6b2-c85dff366b75, dataset date=09/21/2017, update frequency=1, review date=None, last modified=2017-12-16 15:11:15.204215, metadata modified=2017-12-16 15:11:15.204215, updated by script=None, latest of modifieds=2017-12-16 15:11:15.204215, what updated=firstrun, Resource b21d6004-06b5-41e5-8e3e-0f28140bff64: last modified=2017-12-16 15:11:15.202742, Dataset fresh=2, error=False)>""" ) count = ( dbsession.query(DBDataset) .filter_by(fresh=0, what_updated="firstrun", error=False) .count() ) assert count == 67 count = ( dbsession.query(DBDataset) .filter_by(fresh=0, what_updated="firstrun", error=True) .count() ) assert count == 0 count = ( dbsession.query(DBDataset) .filter_by(fresh=0, what_updated="http header", error=False) .count() ) assert count == 0 count = ( dbsession.query(DBDataset) .filter_by(fresh=0, what_updated="http header", error=True) .count() ) assert count == 0 count = ( dbsession.query(DBDataset) .filter_by(fresh=1, what_updated="firstrun") .count() ) assert count == 1 count = ( dbsession.query(DBDataset) .filter_by(fresh=2, what_updated="firstrun", error=False) .count() ) assert count == 1 count = ( dbsession.query(DBDataset) .filter_by(fresh=2, what_updated="firstrun", error=True) .count() ) assert count == 0 count = ( dbsession.query(DBDataset) .filter_by(fresh=3, what_updated="firstrun", error=False) .count() ) assert count == 25 count = ( dbsession.query(DBDataset) .filter_by(fresh=3, what_updated="firstrun", error=True) .count() ) assert count == 5 count = ( dbsession.query(DBDataset) .filter_by(fresh=3, what_updated="http header") .count() ) assert count == 0 count = ( dbsession.query(DBDataset) .filter_by(fresh=None, what_updated="firstrun", error=False) .count() ) assert count == 4 count = ( dbsession.query(DBDataset) .filter_by(fresh=None, what_updated="firstrun", error=True) .count() ) assert count == 0 dbinfodataset = dbsession.query(DBInfoDataset).first() assert ( str(dbinfodataset) == """<InfoDataset(id=a2150ad9-2b87-49f5-a6b2-c85dff366b75, name=rohingya-displacement-topline-figures, title=Rohingya Displacement Topline Figures, private=False, organization id=hdx, maintainer=7d7f5f8d-7e3b-483a-8de1-2b122010c1eb, location=bgd)>""" ) count = dbsession.query(DBInfoDataset).count() assert count == 103 dborganization = dbsession.query(DBOrganization).first() assert ( str(dborganization) == """<Organization(id=hdx, name=hdx, title=HDX)>""" ) count = dbsession.query(DBOrganization).count() assert count == 40
StarcoderdataPython
1746879
# ************************************************************************* # # Copyright (c) 2021 <NAME>. All rights reserved. # # This file is licensed under the terms of the MIT license. # For a copy, see: https://opensource.org/licenses/MIT # # site: https://agramakov.me # e-mail: <EMAIL> # # ************************************************************************* class Register(int): def __new__(cls, address: int, *args, **kwargs): if address < 0: raise ValueError("positive types must not be less than zero") return super().__new__(cls, address) def __init__(self, address: int, access_type: str = "", comment="", *args, **kwargs) -> None: super().__init__() self.access_type = access_type self.comment = comment class Interface(str): pass
StarcoderdataPython
86525
class RoutingRulesList: TITLE = "Maintain case routing rules" CREATE_BUTTON = "Create new routing rule" NO_CONTENT_NOTICE = "There are no registered routing rules at the moment." ACTIVE = "Active" DEACTIVATED = "Deactivated" DEACTIVATE = "Deactivate" REACTIVATE = "Reactivate" EDIT = "Edit" class Table: TEAM = "Team" CASE_STATUS = "Case Status" TIER = "Tier" CASE_TYPES = "Case types" FLAGS = "Flags" COUNTRY = "Country" QUEUE = "Queue" USERS = "Users" STATUS = "Status" ACTIONS = "Actions" class Filter: CASE_STATUS = "case status" TEAM = "team" QUEUE = "queue" TIER = "tier number" ACTIVE_ONLY = "Only show active rules" class AdditionalRules: CASE_TYPES = "Case Types" FLAGS = "Flags" COUNTRY = "Destinations" USERS = "Users" class Forms: CREATE_TITLE = "Routing rule parameters" EDIT_TITLE = "Edit the routing rule" CASE_STATUS = "Select a case status" TEAM = "Select a team to create a rule for" QUEUE = "Select a team work queue" TIER = "Enter a tier number" ADDITIONAL_RULES = "Select the combination of options you need to create the case routing rule" CASE_TYPES = "Select case types" FLAGS = "Select flags" COUNTRY = "Select a country" USER = "Select a team member to assign the case to" BACK_BUTTON = "Back to routing rules" CONFIRM_FORM_ERROR = "Select to confirm or not" class DeactivateForm: TITLE = "Are you sure you want to deactivate this routing rule?" DESCRIPTION = "You are deactivating the routing rule" YES_LABEL = "Deactivate this routing rule" NO_LABEL = "Cancel" class ActivateForm: TITLE = "Are you sure you want to activate this routing rule?" DESCRIPTION = "You are deactivating the routing rule" YES_LABEL = "Activate this routing rule" NO_LABEL = "Cancel"
StarcoderdataPython
149177
<filename>chemotaxis/plots/transport_metabolism.py import os import matplotlib.pyplot as plt from vivarium.plots.simulation_output import set_axes from vivarium.library.dict_utils import get_value_from_path def plot_glc_lcts_environment(timeseries, settings={}, out_dir='out'): external_path = settings.get('external_path', ('environment',)) internal_path = settings.get('internal_path', ('cytoplasm',)) internal_counts_path = settings.get('internal_counts_path', ('cytoplasm_counts',)) reactions_path = settings.get('reactions_path', ('reactions',)) global_path = settings.get('global_path', ('global',)) aspect_ratio = settings.get('aspect_ratio', 1) time = timeseries['time'] environment = get_value_from_path(timeseries, external_path) cell = get_value_from_path(timeseries, internal_path) cell_counts = get_value_from_path(timeseries, internal_counts_path) reactions = get_value_from_path(timeseries, reactions_path) globals = get_value_from_path(timeseries, global_path) # environment lactose = environment['lcts_e'] glucose = environment['glc__D_e'] # internal LacY = cell['LacY'] lacy_RNA = cell['lacy_RNA'] LacY_counts = cell_counts['LacY'] lacy_RNA_counts = cell_counts['lacy_RNA'] # reactions glc_exchange = reactions['EX_glc__D_e'] lac_exchange = reactions['EX_lcts_e'] # global mass = globals['mass'] # settings environment_volume = settings.get('environment_volume') n_cols = 1 n_rows = 3 # make figure and plot width = 5 height = width / aspect_ratio fig = plt.figure(figsize=(width, height)) grid = plt.GridSpec(n_rows, n_cols) ax1 = fig.add_subplot(grid[0, 0]) # grid is (row, column) ax1.plot(time, glucose, label='glucose') ax1.plot(time, lactose, label='lactose') set_axes(ax1) ax1.title.set_text('environment: {}'.format(environment_volume)) ax1.set_ylabel('external \n (mM)') ax1.legend(loc='center left', bbox_to_anchor=(1.0, 0.5)) ax2 = fig.add_subplot(grid[1, 0]) # grid is (row, column) ax2.plot(time, lacy_RNA, label='lacY RNA') ax2.plot(time, LacY, label='LacY protein') set_axes(ax2) ax2.set_ylabel('internal \n (mM)') ax2.legend(loc='center left', bbox_to_anchor=(1.0, 0.5)) ax3 = fig.add_subplot(grid[2, 0]) # grid is (row, column) ax3.plot(time, mass, label='mass') set_axes(ax3, True) ax3.set_ylabel('mass (fg)') ax3.set_xlabel('time (s)') # ax4 = fig.add_subplot(grid[0, 1]) # grid is (row, column) # ax4.plot(time, glc_exchange, label='glucose exchange') # ax4.plot(time, lac_exchange, label='lactose exchange') # set_axes(ax4, True) # ax4.title.set_text('flux'.format(environment_volume)) # ax4.set_xlabel('time (min)') # ax4.legend(loc='center left', bbox_to_anchor=(1.0, 0.5)) # save figure fig_path = os.path.join(out_dir, 'glc_lcts_environment') plt.subplots_adjust(wspace=0.3, hspace=0.3) plt.savefig(fig_path, bbox_inches='tight') plt.close()
StarcoderdataPython
167828
<filename>workflow/scripts/make_conference_schedule.py import pandas as pd tickets = pd.read_csv(snakemake.input["tickets"]) conferences = pd.read_csv(snakemake.input["conferences"]) schedule = conferences[conferences["City"].isin(tickets["city"])] schedule.to_csv(snakemake.output["schedule"])
StarcoderdataPython
1661962
<reponame>czczup/PVT<filename>configs/pvt/pvt_small.py cfg = dict( model='pvt_small', drop_path=0.1, grad_clip=None, output_dir='checkpoints/pvt_small', )
StarcoderdataPython
1620386
from cornell_word_seq2seq_glove_predict import CornellWordGloveChatBot from cornell_word_seq2seq_glove_predict_gru import CornellWordGloveChatBotGRU from cornell_char_seq2seq_predict import CornellCharChatBot from gunthercox_word_seq2seq_glove_predict import GunthercoxWordGloveChatBot from twitter_word_seq2seq_glove_predict import TwitterWordGloveChatBot import os import sys import nltk from datetime import datetime from dotenv import load_dotenv, find_dotenv from flask import Flask, request, send_from_directory, redirect, render_template, flash, url_for, jsonify, \ make_response, abort, session from linebot import ( LineBotApi, WebhookHandler ) from linebot.exceptions import ( InvalidSignatureError ) from linebot.models import ( MessageEvent, PostbackEvent, TextMessage, TextSendMessage, ImageMessage, ImageSendMessage, ButtonsTemplate, URITemplateAction, TemplateSendMessage ) from urllib import parse, request as req import jwt, json load_dotenv(find_dotenv(), override=True) app = Flask(__name__) app.config.from_object(__name__) # load config from this file , flaskr.py # Load default config and override config from an environment variable app.config.from_envvar('FLASKR_SETTINGS', silent=True) app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 type = sys.argv[1] dataset = sys.argv[2] topology = sys.argv[3] if(type == 'char'): cornell_char_chat_bot = CornellCharChatBot() elif(dataset == 'cornell'): if(topology == 'gru'): cornell_word_glove_chat_bot = CornellWordGloveChatBotGRU(type) else: cornell_word_glove_chat_bot = CornellWordGloveChatBot(type) elif(dataset == 'gunthercox'): gunthercox_word_glove_chat_bot = GunthercoxWordGloveChatBot(type) elif(dataset == 'twitter'): twitter_word_glove_chat_bot = TwitterWordGloveChatBot(type) print('Load model succesful') cornell_word_glove_chat_bot_conversations = [] gunthercox_word_glove_chat_bot_conversations = [] twitter_word_glove_chat_bot_conversations = [] # get channel_secret and channel_access_token from your environment variable channel_secret = os.getenv('LINE_CHANNEL_SECRET', None) channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None) if channel_secret is None: print('Specify LINE_CHANNEL_SECRET as environment variable.') sys.exit(1) if channel_access_token is None: print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.') sys.exit(1) line_bot_api = LineBotApi(channel_access_token) handler = WebhookHandler(channel_secret) chatbot_state = {} chatbot_state['dataset'] = 'cornell' @app.route("/callback", methods=['POST']) def callback(): # get X-Line-Signature header value signature = request.headers['X-Line-Signature'] # get request body as text body = request.get_data(as_text=True) app.logger.info("Request body: " + body) # handle webhook body try: handler.handle(body, signature) except InvalidSignatureError: abort(400) return 'OK' @handler.add(MessageEvent, message=TextMessage) def message_text(event): in_text = event.message.text.lower() user_id = event.source.user_id if('set dataset to' in in_text): tokens = nltk.tokenize.word_tokenize(in_text) dataset_name = tokens[len(tokens) - 1] chatbot_state['dataset'] = dataset_name res_text = 'You are now talking with ' + dataset_name + ' chatbot' else: response_data = reply(in_text, 'word-glove', chatbot_state['dataset']) print(response_data['reply']) res_text = response_data['reply'] line_bot_api.reply_message( event.reply_token, TextSendMessage(text=res_text) ) @app.route('/') def home(): return render_template('home.html') @app.route('/about') def about(): return 'About Us' @app.route('/gunthercox_word_glove_reply', methods=['POST', 'GET']) def gunthercox_word_glove_reply(): if request.method == 'POST': if 'sentence' not in request.form: flash('No sentence post') redirect(request.url) elif request.form['sentence'] == '': flash('No sentence') redirect(request.url) else: sent = request.form['sentence'] gunthercox_word_glove_chat_bot_conversations.append('YOU: ' + sent) reply = gunthercox_word_glove_chat_bot.reply(sent) gunthercox_word_glove_chat_bot_conversations.append('BOT: ' + reply) return render_template('gunthercox_word_glove_reply.html', conversations=gunthercox_word_glove_chat_bot_conversations) @app.route('/cornell_word_glove_reply', methods=['POST', 'GET']) def cornell_word_glove_reply(): if request.method == 'POST': if 'sentence' not in request.form: flash('No sentence post') redirect(request.url) elif request.form['sentence'] == '': flash('No sentence') redirect(request.url) else: sent = request.form['sentence'] cornell_word_glove_chat_bot_conversations.append('YOU: ' + sent) reply = cornell_word_glove_chat_bot.reply(sent) cornell_word_glove_chat_bot_conversations.append('BOT: ' + reply) return render_template('cornell_word_glove_reply.html', conversations=cornell_word_glove_chat_bot_conversations) @app.route('/twitter_word_glove_reply', methods=['POST', 'GET']) def twitter_word_glove_reply(): if request.method == 'POST': if 'sentence' not in request.form: flash('No sentence post') redirect(request.url) elif request.form['sentence'] == '': flash('No sentence') redirect(request.url) else: sent = request.form['sentence'] twitter_word_glove_chat_bot_conversations.append('YOU: ' + sent) reply = twitter_word_glove_chat_bot.reply(sent) twitter_word_glove_chat_bot_conversations.append('BOT: ' + reply) return render_template('twitter_word_glove_reply.html', conversations=twitter_word_glove_chat_bot_conversations) @app.route('/chatbot_reply', methods=['POST', 'GET']) def chatbot_reply(): if request.method == 'POST': if not request.json or 'sentence' not in request.json or 'level' not in request.json or 'dialogs' not in request.json: abort(400) sentence = request.json['sentence'] level = request.json['level'] dialogs = request.json['dialogs'] else: sentence = request.args.get('sentence') level = request.args.get('level') dialogs = request.args.get('dialogs') target_text = sentence if level == 'word-glove' and dialogs == 'cornell': target_text = cornell_word_glove_chat_bot.reply(sentence) elif level == 'word-glove' and dialogs == 'gunthercox': target_text = gunthercox_word_glove_chat_bot.reply(sentence) return jsonify({ 'sentence': sentence, 'reply': target_text, 'dialogs': dialogs, 'level': level }) def reply(sentence, level, dialogs): target_text = sentence if level == 'word-glove' and dialogs == 'cornell': target_text = cornell_word_glove_chat_bot.reply(sentence) elif level == 'word-glove' and dialogs == 'gunthercox': target_text = gunthercox_word_glove_chat_bot.reply(sentence) elif level == 'word-glove' and dialogs == 'twitter': target_text = twitter_word_glove_chat_bot.reply(sentence) elif level == 'char' and dialogs == 'cornell': target_text = cornell_char_chat_bot.reply(sentence) return { 'sentence': sentence, 'reply': target_text, 'dialogs': dialogs, 'level': level } @app.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) def get_inputs_and_references(dataset_folder_name, sample_amount): path = "chatbot_train/data/" + dataset_folder_name + "/test.txt" with open(path) as f: lines = f.readlines() i = 1 inputs = [] references = [] for line in lines: if (i % 2 == 1): inputs.append(line[0:len(line)-1]) else: references.append(line) if(i == sample_amount * 2): break i = i + 1 return { 'inputs' : inputs, 'references' : references } def get_outputs_and_references(dataset_folder_name, sample_amount): data = get_inputs_and_references(dataset_folder_name, sample_amount) inputs = data['inputs'] references = data['references'] outputs = [] if(dataset_folder_name == 'cornell-dialogs'): dataset = 'cornell' else: dataset = dataset_folder_name data = [] for i in range(0, len(inputs)): try: if(type == 'char'): data.append({ 'output' : reply(inputs[i], 'char', dataset)['reply'], 'reference' : references[i] }) else: data.append({ 'output' : reply(inputs[i], 'word-glove', dataset)['reply'], 'reference' : references[i] }) except: print("One data skipped because of shape error") return data # CALCULATE BLEU SCORE def bleu_score(dialogs, sample_amount): from nltk.translate.bleu_score import sentence_bleu from nltk.translate.bleu_score import SmoothingFunction smoothie = SmoothingFunction().method4 if(dialogs == 'cornell'): dataset_folder_name = 'cornell-dialogs' else: dataset_folder_name = dialogs data = get_outputs_and_references(dataset_folder_name, sample_amount) # print('DATAAA') # print(data) sum_bleu_score_1 = 0 sum_bleu_score_2 = 0 sum_bleu_score_3 = 0 sum_bleu_score_4 = 0 i = 0 for datum in data: reference = [] reference_str = datum['reference'].lower() output_str = datum['output'] reference_str = reference_str.replace(".", "") reference_str = reference_str.replace(",", "") output_str = output_str.replace(".", "") output_str = output_str.replace(",", "") reference.append(nltk.tokenize.word_tokenize(reference_str)) candidate = nltk.tokenize.word_tokenize(output_str) print(reference) print(candidate) try: bleu_1 = sentence_bleu(reference, candidate, weights=(1, 0, 0, 0), smoothing_function=smoothie) except: bleu_1 = 0.5 try: bleu_2 = sentence_bleu(reference, candidate, weights=(0.5, 0.5, 0, 0), smoothing_function=smoothie) except: bleu_2 = 0.5 try: bleu_3 = sentence_bleu(reference, candidate, weights=(0.33, 0.33, 0.33, 0), smoothing_function=smoothie) except: bleu_3 = 0.5 try: bleu_4 = sentence_bleu(reference, candidate, weights=(0.25, 0.25, 0.25, 0.25), smoothing_function=smoothie) except: bleu_4 = 0.5 print(bleu_1) print(bleu_2) print(bleu_3) print(bleu_4) sum_bleu_score_1 = sum_bleu_score_1 + bleu_1 sum_bleu_score_2 = sum_bleu_score_2 + bleu_2 sum_bleu_score_3 = sum_bleu_score_3 + bleu_3 sum_bleu_score_4 = sum_bleu_score_4 + bleu_4 i = i + 1 print(i) print('BLEU-1 : ' + str(round(sum_bleu_score_1/len(data), 4))) print('BLEU-2 : ' + str(round(sum_bleu_score_2/len(data), 4))) print('BLEU-3 : ' + str(round(sum_bleu_score_3/len(data), 4))) print('BLEU-4 : ' + str(round(sum_bleu_score_4/len(data), 4))) with open(os.environ['CURRENT_CORNELL_MODEL'] + '-' + str(sample_amount) + '.txt', 'w', encoding="latin1") as out_file: out_file.write('BLEU-1 : ' + str(round(sum_bleu_score_1/len(data), 4))) out_file.write('\n') out_file.write('BLEU-2 : ' + str(round(sum_bleu_score_2/len(data), 4))) out_file.write('\n') out_file.write('BLEU-3 : ' + str(round(sum_bleu_score_3/len(data), 4))) out_file.write('\n') out_file.write('BLEU-4 : ' + str(round(sum_bleu_score_4/len(data), 4))) out_file.write('\n') out_file.write('Sample amount : ' + str(sample_amount)) # CALCULATE BLEU SCORE def bleu_score_char(dialogs, sample_amount): from nltk.translate.bleu_score import sentence_bleu from nltk.translate.bleu_score import SmoothingFunction smoothie = SmoothingFunction().method4 if(dialogs == 'cornell'): dataset_folder_name = 'cornell-dialogs' else: dataset_folder_name = dialogs data = get_outputs_and_references(dataset_folder_name, sample_amount) # print('DATAAA') # print(data) sum_bleu_score_1 = 0 sum_bleu_score_2 = 0 sum_bleu_score_3 = 0 sum_bleu_score_4 = 0 i = 0 for datum in data: reference = [] reference_str = datum['reference'].lower() output_str = datum['output'] reference_str = reference_str.replace(".", "") reference_str = reference_str.replace(",", "") output_str = output_str.replace(".", "") output_str = output_str.replace(",", "") reference.append(nltk.tokenize.word_tokenize(reference_str)) candidate = nltk.tokenize.word_tokenize(output_str) print(reference) print(candidate) try: bleu_1 = sentence_bleu(reference, candidate, weights=(1, 0, 0, 0)) except: bleu_1 = 0.5 try: bleu_2 = sentence_bleu(reference, candidate, weights=(0.5, 0.5, 0, 0)) except: bleu_2 = 0.5 try: bleu_3 = sentence_bleu(reference, candidate, weights=(0.33, 0.33, 0.33, 0)) except: bleu_3 = 0.5 try: bleu_4 = sentence_bleu(reference, candidate, weights=(0.25, 0.25, 0.25, 0.25)) except: bleu_4 = 0.5 print(bleu_1) print(bleu_2) print(bleu_3) print(bleu_4) sum_bleu_score_1 = sum_bleu_score_1 + bleu_1 sum_bleu_score_2 = sum_bleu_score_2 + bleu_2 sum_bleu_score_3 = sum_bleu_score_3 + bleu_3 sum_bleu_score_4 = sum_bleu_score_4 + bleu_4 i = i + 1 print(i) print('BLEU-1 : ' + str(round(sum_bleu_score_1/len(data), 4))) print('BLEU-2 : ' + str(round(sum_bleu_score_2/len(data), 4))) print('BLEU-3 : ' + str(round(sum_bleu_score_3/len(data), 4))) print('BLEU-4 : ' + str(round(sum_bleu_score_4/len(data), 4))) def interact(): print('Mulai') print(os.environ['CURRENT_CORNELL_MODEL']) while(True): print('Q:') x = input() print('A : ') print(reply(x, 'word-glove', 'cornell')['reply']) def interact2(): print('Mulai') print(os.environ['CURRENT_CORNELL_CHAR_MODEL']) while(True): print('Q:') x = input() print('A : ') print(reply(x, 'char', 'cornell')['reply']) def main(): app.secret_key = os.urandom(12) try: port = int(os.environ['PORT']) except KeyError: print('Specify PORT as environment variable.') sys.exit(1) except TypeError: print('PORT must be an integer.') sys.exit(1) app.run(host='0.0.0.0', port=port, debug=False) if __name__ == '__main__': if(sys.argv[4] == 'bleu'): if(dataset == 'cornell'): if(type == 'char'): bleu_score('cornell', 2000/2) else: bleu_score('cornell', 2000/2) elif(dataset == 'gunthercox'): bleu_score('gunthercox', 10) elif(dataset == 'twitter'): bleu_score('twitter', 200) elif(sys.argv[4] == 'test'): main() elif(sys.argv[4] == 'terminal'): interact() elif(sys.argv[4] == 'terminal2'): interact2()
StarcoderdataPython
1732956
"""This module reads files from disk""" import os def crawl_files(): file_dic = [] dir = os.path.dirname(__file__) for root, dirs, files in os.walk(dir + '/../articles'): for file in files: file_path = os.path.join(root, file) file_dic.append({'name': file_path}) return file_dic
StarcoderdataPython
3271584
import cxphasing.cxparams.CXParams as CXP import cxphasing.CXPhasing as CXPh import cxphasing.CXData as CXData from data_exchange import DataExchangeFile, DataExchangeEntry import scipy as sp import pdb def pack_data_exchange(): f = DataExchangeFile(CXP.io.data_exchange_filename, mode='w') sim = DataExchangeEntry.simulation( name={'value': 'Simulated Ptycho Data.'}, energy={'value': CXP.experiment.energy, 'units':'keV'}, focusing_optic={'value': CXP.experiment.optic}, probe_modes={'value':CXP.reconstruction.probe_modes}, noise_model={'value': CXP.simulation.noise_model}, gaussian_noise_level={'value': CXP.simulation.gaussian_noise_level}, total_photons={'value': CXP.simulation.total_photons}, beam_stop={'value': CXP.simulation.beam_stop}, beam_stop_size={'value':CXP.simulation.beam_stop_size}, beam_stop_attenuation={'value':CXP.simulation.beam_stop_attenuation}, defocus = {'value':CXP.simulation.defocus}, position_jitter={'value': CXP.reconstruction.initial_position_jitter_radius, 'units':'pixels'} ) f.add_entry(sim) sample = DataExchangeEntry.sample( root='/simulation', name={'value':'ground truth sample complex amplitude'}, data={'value': cxph.sample.data[0], 'units':'sqrt(counts)'}, ) f.add_entry(sample) probe = DataExchangeEntry.sample( root='/simulation', entry_name='probe', ) for mode in range(CXP.reconstruction.probe_modes): setattr(probe, 'mode_{:d}'.format(mode), {'value': cxph.input_probe.modes[mode].data[0], 'units':'counts'}) f.add_entry(probe) detector = DataExchangeEntry.detector( root='/simulation', x_pixel_size={'value': CXP.experiment.dx_d}, y_pixel_size={'value': CXP.experiment.dx_d}, x_dimension={'value': CXP.experiment.px}, y_dimension={'value': CXP.experiment.py}, distance={'value': CXP.experiment.z}, basis_vectors={'value': [[0,-CXP.experiment.dx_d,0],[-CXP.experiment.dx_d,0,0]]}, corner_position={'value': [0,0,0]} ) f.add_entry(detector) data = DataExchangeEntry.data( name={'value': 'simulated_data'}, data={'value': sp.array(cxph.det_mod.data), 'axes':'translation:y:x', 'units':'counts', 'dataset_opts': {'compression': 'gzip', 'compression_opts': 4}}, translation={'value':'/exchange/sample/geometry/translation'} ) f.add_entry(data) # Get scan positions into dex format pos = sp.zeros((cxph.positions.total, 3)) y, x = cxph.positions.correct for i in range(cxph.positions.total): pos[i,0], pos[i, 1] = x[i]*CXP.dx_s, y[i]*CXP.dx_s positions = DataExchangeEntry.translation( root='/exchange/sample/geometry', name={'value':'ptychography scan positions'}, scan_type={'value': CXP.measurement.ptycho_scan_type}, data={'value': pos, 'units': 'm'} ) f.add_entry(positions) f.close() if __name__=='__main__': cxph = CXPh() cxph.positions = CXData(name='positions', data=[]) cxph.ptycho_mesh() cxph.simulate_data(no_save=True) pack_data_exchange()
StarcoderdataPython
1742329
<reponame>wwxFromTju/hierarchical-marl """Implementation of hierarchical cooperative multi-agent RL with skill discovery. High-level Q-function Q(s,\zbf) is trained with QMIX (with decentralized execution) using global environment reward Low-level policies are either 1. parameterized as policy networks pi(a^n|o^n,z^n) and trained with policy gradient using the intrinsic reward log P(z|tau) + entropy or 2. induced from Q-functions Q(o^n,z^n,a^n) and trained with independent Q-learning using only log P(z|tau) as delayed reward """ import tensorflow as tf import numpy as np import sys import networks class Alg(object): def __init__(self, config_alg, config_h, n_agents, l_state, l_obs, l_action, l_z, nn): """ Args: config_alg: dictionary of general RL params config_h: dictionary of HSD params n_agents: number of agents on the team controlled by this alg l_state, l_obs, l_action, l_z: int nn: dictionary with neural net sizes """ self.l_state = l_state self.l_obs = l_obs self.l_action = l_action self.l_z = l_z self.nn = nn self.n_agents = n_agents self.tau = config_alg['tau'] self.lr_Q = config_alg['lr_Q'] self.lr_actor = config_alg['lr_actor'] self.lr_decoder = config_alg['lr_decoder'] self.gamma = config_alg['gamma'] self.traj_length = config_h['steps_per_assign'] self.traj_skip = config_h['traj_skip'] self.traj_length_downsampled = int(np.ceil( self.traj_length / self.traj_skip )) self.use_state_difference = config_h['use_state_difference'] if self.use_state_difference: self.traj_length_downsampled -= 1 # Domain-specific removal of information from agent observation # Either none (deactivate) or scalar index where obs should be truncated for use by decoder self.obs_truncate_length = config_h['obs_truncate_length'] assert( (self.obs_truncate_length is None) or (self.obs_truncate_length <= self.l_obs) ) self.low_level_alg = config_h['low_level_alg'] assert(self.low_level_alg == 'reinforce' or self.low_level_alg == 'iac' or self.low_level_alg == 'iql') if self.low_level_alg == 'iac': self.lr_V = config_alg['lr_V'] # Initialize computational graph self.create_networks() self.list_initialize_target_ops, self.list_update_target_ops, self.list_update_target_ops_low = self.get_assign_target_ops() self.create_train_op_high() self.create_train_op_low() self.create_train_op_decoder() # TF summaries self.create_summary() def create_networks(self): # Placeholders self.state = tf.placeholder(tf.float32, [None, self.l_state], 'state') self.obs = tf.placeholder(tf.float32, [None, self.l_obs], 'obs') self.z = tf.placeholder(tf.float32, [None, self.l_z], 'z') # Decoder p(z|tau) if self.obs_truncate_length: self.traj = tf.placeholder(dtype=tf.float32, shape=[None, self.traj_length_downsampled, self.obs_truncate_length]) else: self.traj = tf.placeholder(dtype=tf.float32, shape=[None, self.traj_length_downsampled, self.l_obs]) with tf.variable_scope("Decoder"): self.decoder_out, self.decoder_probs = networks.decoder(self.traj, self.traj_length_downsampled, self.nn['n_h_decoder'], self.l_z) # Low-level policy if self.low_level_alg == 'reinforce' or self.low_level_alg == 'iac': self.epsilon = tf.placeholder(tf.float32, None, 'epsilon') with tf.variable_scope("Policy_main"): probs = networks.actor(self.obs, self.z, self.nn['n_h1_low'], self.nn['n_h2_low'], self.l_action) self.probs = (1-self.epsilon) * probs + self.epsilon/float(self.l_action) self.action_samples = tf.multinomial(tf.log(self.probs), 1) if self.low_level_alg == 'iac': with tf.variable_scope("V_main"): self.V = networks.critic(self.obs, self.z, self.nn['n_h1_low'], self.nn['n_h2_low']) with tf.variable_scope("V_target"): self.V_target = networks.critic(self.obs, self.z, self.nn['n_h1_low'], self.nn['n_h2_low']) # Low-level Q-functions if self.low_level_alg == 'iql': with tf.variable_scope("Qlow_main"): self.Q_low = networks.Q_low(self.obs, self.z, self.nn['n_h1_low'], self.nn['n_h2_low'], self.l_action) with tf.variable_scope("Qlow_target"): self.Q_low_target = networks.Q_low(self.obs, self.z, self.nn['n_h1_low'], self.nn['n_h2_low'], self.l_action) self.argmax_Q_low = tf.argmax(self.Q_low, axis=1) self.actions_low_1hot = tf.placeholder(tf.float32, [None, self.l_action], 'actions_low_1hot') # High-level QMIX # Individual agent networks # output dimension is [time * n_agents, q-values] with tf.variable_scope("Agent_main"): self.agent_qs = networks.Qmix_single(self.obs, self.nn['n_h1'], self.nn['n_h2'], self.l_z) with tf.variable_scope("Agent_target"): self.agent_qs_target = networks.Qmix_single(self.obs, self.nn['n_h1'], self.nn['n_h2'], self.l_z) self.argmax_Q = tf.argmax(self.agent_qs, axis=1) self.argmax_Q_target = tf.argmax(self.agent_qs_target, axis=1) # To extract Q-value from agent_qs and agent_qs_target # [batch*n_agents, N_roles] self.actions_1hot = tf.placeholder(tf.float32, [None, self.l_z], 'actions_1hot') # [batch*n_agents, 1] self.q_selected = tf.reduce_sum(tf.multiply(self.agent_qs, self.actions_1hot), axis=1) # [batch, n_agents] self.mixer_q_input = tf.reshape( self.q_selected, [-1, self.n_agents] ) self.q_target_selected = tf.reduce_sum(tf.multiply(self.agent_qs_target, self.actions_1hot), axis=1) self.mixer_target_q_input = tf.reshape( self.q_target_selected, [-1, self.n_agents] ) # Mixing network with tf.variable_scope("Mixer_main"): self.mixer = networks.Qmix_mixer(self.mixer_q_input, self.state, self.l_state, self.n_agents, self.nn['n_h_mixer']) with tf.variable_scope("Mixer_target"): self.mixer_target = networks.Qmix_mixer(self.mixer_target_q_input, self.state, self.l_state, self.n_agents, self.nn['n_h_mixer']) def get_assign_target_ops(self): # ops for equating main and target list_initial_ops = [] # ops for slow update of target toward main list_update_ops = [] # ops for slow update of low-level target toward low-level main list_update_ops_low = [] list_Agent_main = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Agent_main') map_name_Agent_main = {v.name.split('main')[1] : v for v in list_Agent_main} list_Agent_target = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Agent_target') map_name_Agent_target = {v.name.split('target')[1] : v for v in list_Agent_target} if len(list_Agent_main) != len(list_Agent_target): raise ValueError("get_initialize_target_ops : lengths of Agent_main and Agent_target do not match") for name, var in map_name_Agent_main.items(): # create op that assigns value of main variable to # target variable of the same name list_initial_ops.append( map_name_Agent_target[name].assign(var) ) for name, var in map_name_Agent_main.items(): # incremental update of target towards main list_update_ops.append( map_name_Agent_target[name].assign( self.tau*var + (1-self.tau)*map_name_Agent_target[name] ) ) list_Mixer_main = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Mixer_main') map_name_Mixer_main = {v.name.split('main')[1] : v for v in list_Mixer_main} list_Mixer_target = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Mixer_target') map_name_Mixer_target = {v.name.split('target')[1] : v for v in list_Mixer_target} if len(list_Mixer_main) != len(list_Mixer_target): raise ValueError("get_initialize_target_ops : lengths of Mixer_main and Mixer_target do not match") # ops for equating main and target for name, var in map_name_Mixer_main.items(): # create op that assigns value of main variable to # target variable of the same name list_initial_ops.append( map_name_Mixer_target[name].assign(var) ) # ops for slow update of target toward main for name, var in map_name_Mixer_main.items(): # incremental update of target towards main list_update_ops.append( map_name_Mixer_target[name].assign( self.tau*var + (1-self.tau)*map_name_Mixer_target[name] ) ) if self.low_level_alg == 'iac': list_V_main = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'V_main') map_name_V_main = {v.name.split('main')[1] : v for v in list_V_main} list_V_target = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'V_target') map_name_V_target = {v.name.split('target')[1] : v for v in list_V_target} if len(list_V_main) != len(list_V_target): raise ValueError("get_initialize_target_ops : lengths of V_main and V_target do not match") for name, var in map_name_V_main.items(): list_initial_ops.append( map_name_V_target[name].assign(var) ) for name, var in map_name_V_main.items(): list_update_ops_low.append( map_name_V_target[name].assign( self.tau*var + (1-self.tau)*map_name_V_target[name] ) ) elif self.low_level_alg == 'iql': list_Qlow_main = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Qlow_main') map_name_Qlow_main = {v.name.split('main')[1] : v for v in list_Qlow_main} list_Qlow_target = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Qlow_target') map_name_Qlow_target = {v.name.split('target')[1] : v for v in list_Qlow_target} if len(list_Qlow_main) != len(list_Qlow_target): raise ValueError("get_initialize_target_ops : lengths of Qlow_main and Qlow_target do not match") for name, var in map_name_Qlow_main.items(): list_initial_ops.append( map_name_Qlow_target[name].assign(var) ) for name, var in map_name_Qlow_main.items(): list_update_ops_low.append( map_name_Qlow_target[name].assign( self.tau*var + (1-self.tau)*map_name_Qlow_target[name] ) ) return list_initial_ops, list_update_ops, list_update_ops_low def run_actor(self, list_obs, roles, epsilon, sess): """Get low-level actions for all agents as a batch. Args: list_obs: list of vectors, one per agent roles: np.array where each row is a 1-hot vector epsilon: exploration parameter sess: TF session Returns: np.array of action integers """ # convert to batch obs = np.array(list_obs) if self.low_level_alg == 'reinforce' or self.low_level_alg == 'iac': feed = {self.obs : obs, self.z : roles, self.epsilon : epsilon} actions = sess.run(self.action_samples, feed_dict=feed) elif self.low_level_alg == 'iql': feed = {self.obs : obs, self.z : roles} actions_argmax = sess.run(self.argmax_Q_low, feed_dict=feed) actions = np.zeros(self.n_agents, dtype=int) for idx in range(self.n_agents): if np.random.rand() < epsilon: actions[idx] = np.random.randint(0, self.l_action) else: actions[idx] = actions_argmax[idx] return actions.flatten() def assign_roles(self, list_obs, epsilon, sess, N_roles_current): """Get high-level role assignment actions for all agents. Args: list_obs: list of vectors, one per agent epsilon: exploration parameter sess: TF session N_roles_current: number of activated role dimensions Returns: np.array of role indices """ obs = np.array(list_obs) feed = {self.obs : obs} Q_values = sess.run(self.agent_qs, feed_dict=feed) # Limit the number of activated options based on curriculum roles_argmax = np.argmax(Q_values[:, 0:N_roles_current], axis=1) roles = np.zeros(self.n_agents, dtype=int) for idx in range(self.n_agents): if np.random.rand() < epsilon: roles[idx] = np.random.randint(0, N_roles_current) else: roles[idx] = roles_argmax[idx] return roles def create_train_op_high(self): """Ops for training high-level policy.""" self.td_target = tf.placeholder(tf.float32, [None], 'td_target') self.loss_Q_high = tf.reduce_mean(tf.square(self.td_target - tf.squeeze(self.mixer))) self.Q_opt = tf.train.AdamOptimizer(self.lr_Q) self.Q_op = self.Q_opt.minimize(self.loss_Q_high) def create_train_op_low(self): """Ops for training low-level policy.""" if self.low_level_alg == 'reinforce' or self.low_level_alg == 'iac': self.actions_taken = tf.placeholder(tf.float32, [None, self.l_action], 'action_taken') # self.probs shape is [batch size * traj length, l_action] # now log_probs shape is [batch size * traj length] log_probs = tf.log(tf.reduce_sum(tf.multiply(self.probs, self.actions_taken), axis=1)+1e-15) if self.low_level_alg == 'reinforce': # Rehape to [batch size, traj length] log_probs_reshaped = tf.reshape( log_probs, [-1, self.traj_length]) self.traj_reward = tf.placeholder(tf.float32, [None], 'traj_reward') # E [ \sum_t \log \pi(a_t|o_t,z) * R ] self.policy_loss = - tf.reduce_mean( tf.reduce_sum(log_probs_reshaped, axis=1) * self.traj_reward ) elif self.low_level_alg == 'iac': # Critic train op self.V_td_target = tf.placeholder(tf.float32, [None], 'V_td_target') self.loss_V = tf.reduce_mean(tf.square(self.V_td_target - tf.squeeze(self.V))) self.V_opt = tf.train.AdamOptimizer(self.lr_V) self.V_op = self.V_opt.minimize(self.loss_V) # Policy train op self.V_evaluated = tf.placeholder(tf.float32, [None], 'V_evaluated') self.V_td_error = self.V_td_target - self.V_evaluated self.policy_loss = -tf.reduce_mean( tf.multiply( log_probs, self.V_td_error ) ) self.policy_opt = tf.train.AdamOptimizer(self.lr_actor) self.policy_op = self.policy_opt.minimize(self.policy_loss) elif self.low_level_alg == 'iql': self.td_target_IQL = tf.placeholder(tf.float32, [None], 'td_target_IQL') self.td_error = self.td_target_IQL - tf.reduce_sum(tf.multiply(self.Q_low, self.actions_low_1hot), axis=1) self.loss_IQL = tf.reduce_mean(tf.square(self.td_error)) self.IQL_opt = tf.train.AdamOptimizer(self.lr_Q) self.IQL_op = self.IQL_opt.minimize(self.loss_IQL) def create_train_op_decoder(self): """Ops for training skill decoder.""" self.onehot_z = tf.placeholder(tf.float32, [None, self.l_z], 'onehot_z') self.decoder_loss = tf.losses.softmax_cross_entropy(self.onehot_z, self.decoder_out) self.decoder_opt = tf.train.AdamOptimizer(self.lr_decoder) self.decoder_op = self.decoder_opt.minimize(self.decoder_loss) def create_summary(self): summaries_Q = [tf.summary.scalar('loss_Q_high', self.loss_Q_high)] mixer_main_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Mixer_main') for v in mixer_main_variables: summaries_Q.append(tf.summary.histogram(v.op.name, v)) grads = self.Q_opt.compute_gradients(self.loss_Q_high, mixer_main_variables) for grad, var in grads: if grad is not None: summaries_Q.append( tf.summary.histogram(var.op.name+'/gradient', grad) ) agent_main_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Agent_main') for v in agent_main_variables: summaries_Q.append(tf.summary.histogram(v.op.name, v)) grads = self.Q_opt.compute_gradients(self.loss_Q_high, agent_main_variables) for grad, var in grads: if grad is not None: summaries_Q.append( tf.summary.histogram(var.op.name+'/gradient', grad) ) self.summary_op_Q = tf.summary.merge(summaries_Q) if self.low_level_alg == 'reinforce' or self.low_level_alg == 'iac': summaries_policy = [tf.summary.scalar('policy_loss', self.policy_loss)] policy_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Policy_main') for v in policy_variables: summaries_policy.append(tf.summary.histogram(v.op.name, v)) grads = self.policy_opt.compute_gradients(self.policy_loss, policy_variables) for grad, var in grads: if grad is not None: summaries_policy.append( tf.summary.histogram(var.op.name+'/gradient', grad) ) self.summary_op_policy = tf.summary.merge(summaries_policy) summaries_decoder = [tf.summary.scalar('decoder_loss', self.decoder_loss)] decoder_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Decoder') for v in decoder_variables: summaries_decoder.append(tf.summary.histogram(v.op.name, v)) grads = self.decoder_opt.compute_gradients(self.decoder_loss, decoder_variables) for grad, var in grads: if grad is not None: summaries_decoder.append( tf.summary.histogram(var.op.name+'/gradient', grad) ) self.summary_op_decoder = tf.summary.merge(summaries_decoder) if self.low_level_alg == 'iac': summaries_V = [tf.summary.scalar('V_loss', self.loss_V)] V_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'V_main') for v in V_variables: summaries_V.append(tf.summary.histogram(v.op.name, v)) grads = self.V_opt.compute_gradients(self.loss_V, V_variables) for grad, var in grads: if grad is not None: summaries_V.append( tf.summary.histogram(var.op.name+'/gradient', grad) ) self.summary_op_V = tf.summary.merge(summaries_V) if self.low_level_alg == 'iql': summaries_Qlow = [tf.summary.scalar('loss_IQL', self.loss_IQL)] Qlow_main_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Qlow_main') for v in Qlow_main_variables: summaries_Qlow.append(tf.summary.histogram(v.op.name, v)) grads = self.IQL_opt.compute_gradients(self.loss_IQL, Qlow_main_variables) for grad, var in grads: if grad is not None: summaries_Qlow.append( tf.summary.histogram(var.op.name+'/gradient', grad) ) self.summary_op_Qlow = tf.summary.merge(summaries_Qlow) def process_actions(self, n_steps, actions, n_actions): """ Args: n_steps: number of steps in trajectory actions: must have shape [time, n_agents], and values are action indices n_actions: dimension of action space Returns: 1-hot representation of actions """ # Each row of actions is one time step, # row contains action indices for all agents # Convert to [time, agents, N_roles] # so each agent gets its own 1-hot row vector actions_1hot = np.zeros([n_steps, self.n_agents, n_actions], dtype=int) grid = np.indices((n_steps, self.n_agents)) actions_1hot[grid[0], grid[1], actions] = 1 # In-place reshape of actions to [time*n_agents, N_roles] actions_1hot.shape = (n_steps*self.n_agents, n_actions) return actions_1hot def process_batch(self, batch): """Used for high-level buffer. Extract quantities of the same type from batch. Format batch so that each agent at each time step is one batch entry. """ # shapes are [time, ...original dims...] state = np.stack(batch[:,0]) # [time, l_state] obs = np.stack(batch[:,1]) # [time, agents, l_obs] actions = np.stack(batch[:,2]) # [time, agents] reward = np.stack(batch[:,3]) # [time] state_next = np.stack(batch[:,4]) # [time, l_state] obs_next = np.stack(batch[:,5]) # [time, agents, l_obs] done = np.stack(batch[:,6]) # [time] # Try to free memory batch = None n_steps = state.shape[0] # In-place reshape for obs, so that one time step # for one agent is considered one batch entry obs.shape = (n_steps * self.n_agents, self.l_obs) obs_next.shape = (n_steps * self.n_agents, self.l_obs) actions_1hot = self.process_actions(n_steps, actions, self.l_z) return n_steps, state, obs, actions_1hot, reward, state_next, obs_next, done def train_policy_high(self, sess, batch, step_train, summarize=False, writer=None): """Training step for high-level policy.""" # Each agent for each time step is now a batch entry n_steps, state, obs, actions_1hot, reward, state_next, obs_next, done = self.process_batch(batch) # Get argmax actions from target networks feed = {self.obs : obs_next} argmax_actions = sess.run(self.argmax_Q_target, feed_dict=feed) # [batch*n_agents] # Convert to 1-hot actions_target_1hot = np.zeros([n_steps * self.n_agents, self.l_z], dtype=int) actions_target_1hot[np.arange(n_steps*self.n_agents), argmax_actions] = 1 # Get Q_tot target value feed = {self.state : state_next, self.actions_1hot : actions_target_1hot, self.obs : obs_next} Q_tot_target = sess.run(self.mixer_target, feed_dict=feed) done_multiplier = -(done - 1) target = reward + self.gamma * np.squeeze(Q_tot_target) * done_multiplier feed = {self.state : state, self.td_target : target} feed[self.obs] = obs feed[self.actions_1hot] = actions_1hot if summarize: summary, _ = sess.run([self.summary_op_Q, self.Q_op], feed_dict=feed) writer.add_summary(summary, step_train) else: _ = sess.run(self.Q_op, feed_dict=feed) sess.run(self.list_update_target_ops) def process_batch_low(self, batch): """ Extract quantities of the same type from batch. Format batch so that each agent at each time step is one batch entry. """ # shapes are [time, ...original dims...] obs = np.stack(batch[:,0]) # [time, agents, l_obs] actions = np.stack(batch[:,1]) # [time, agents] rewards = np.stack(batch[:,2]) # [time, agents] obs_next = np.stack(batch[:,3]) # [time, agents, l_obs] roles = np.stack(batch[:,4]) # [time, agents, N_roles] done = np.stack(batch[:,5]) # [time] batch = None # Try to free memory n_steps = obs.shape[0] # In-place reshape for obs, so that one time step # for one agent is considered one batch entry obs.shape = (n_steps * self.n_agents, self.l_obs) obs_next.shape = (n_steps * self.n_agents, self.l_obs) rewards.shape = (n_steps * self.n_agents) roles.shape = (n_steps * self.n_agents, self.l_z) done = np.repeat(done, self.n_agents, axis=0) actions_1hot = self.process_actions(n_steps, actions, self.l_action) return n_steps, obs, actions_1hot, rewards, obs_next, roles, done def train_policy_low(self, sess, batch, step_train=0, summarize=False, writer=None): """Training step for low-level action policy. Runs independent Q-learning on each agent's experiences using local rewards """ n_steps, obs, actions_1hot, rewards, obs_next, roles, done = self.process_batch_low(batch) # Get target values feed = {self.obs : obs_next, self.z : roles} Q_target = sess.run(self.Q_low_target, feed_dict=feed) done_multiplier = - (done - 1) target = rewards + self.gamma * np.max(Q_target, axis=1) * done_multiplier feed = {self.obs : obs, self.actions_low_1hot : actions_1hot, self.z : roles, self.td_target_IQL : target} if summarize: summary, _ = sess.run([self.summary_op_Qlow, self.IQL_op], feed_dict=feed) writer.add_summary(summary, step_train) else: _ = sess.run(self.IQL_op, feed_dict=feed) sess.run(self.list_update_target_ops_low) def train_decoder(self, sess, dataset, step_train, summarize=False, writer=None): """Training step for skill decoder. Args: sess: TF session dataset: list of np.array objects step_train: int """ dataset = np.array(dataset) obs = np.stack(dataset[:,0]) z = np.stack(dataset[:,1]) # Downsample obs along the traj dimension # obs has shape [batch, traj, l_obs] obs_downsampled = obs[ :, ::self.traj_skip, : ] if self.obs_truncate_length: obs_downsampled = obs_downsampled[ : , : , :self.obs_truncate_length] if self.use_state_difference: # use the difference between consecutive states in a trajectory, rather than the state obs_downsampled = obs_downsampled[ : , 1: , : ] - obs_downsampled[ : , :-1 , : ] assert( obs_downsampled.shape[1] == self.traj_length_downsampled ) # Train decoder feed = {self.onehot_z : z, self.traj : obs_downsampled} if summarize: summary, _, decoder_probs = sess.run([self.summary_op_decoder, self.decoder_op, self.decoder_probs], feed_dict=feed) writer.add_summary(summary, step_train) else: _, decoder_probs = sess.run([self.decoder_op, self.decoder_probs], feed_dict=feed) # decoder_probs has shape [batch, N_roles] prob = np.sum(np.multiply( decoder_probs, z ), axis=1) expected_prob = np.mean( prob ) return expected_prob def process_dataset(self, dataset): """ Extract batches of obs, action, reward and z for training low-level policy and decoder Each batch entry corresponds to a trajectory segment dataset: np.array """ # shapes are [batch, ...original dims...] obs = np.stack(dataset[:,0]) # [batch, traj, l_obs] action = np.stack(dataset[:,1]) # [batch, traj, l_action] reward = np.stack(dataset[:,2]) # [batch, traj] obs_next = np.stack(dataset[:,3]) # [batch, traj, l_obs] done = np.stack(dataset[:,4]) # [batch, traj] z = np.stack(dataset[:,5]) # [batch, N_roles] return obs, action, reward, obs_next, done, z def compute_reward(self, sess, agents_traj_obs, z): """Computes P(z|traj) as the reward for low-level policy. Args: sess: TF session agents_traj_obs: np.array shape [n_agents, traj length, l_obs] z: np.array shape [n_agents, N_roles] """ # Downsample along traj dimension obs_downsampled = agents_traj_obs[ : , ::self.traj_skip , : ] if self.obs_truncate_length: obs_downsampled = obs_downsampled[ : , : , :self.obs_truncate_length] if self.use_state_difference: # use the difference between consecutive states in a trajectory, rather than the state obs_downsampled = obs_downsampled[ : , 1: , : ] - obs_downsampled[ : , :-1 , : ] assert( obs_downsampled.shape[1] == self.traj_length_downsampled ) decoder_probs = sess.run(self.decoder_probs, feed_dict={self.traj : obs_downsampled}) prob = np.sum(np.multiply( decoder_probs, z ), axis=1) return prob def train_policy_and_decoder(self, sess, dataset, alpha, epsilon, step_train, summarize=False, writer=None): """DEPRECATED. dataset: list of np.array objects alpha: scalar coefficient for computing extrinsic versus intrinsic reward epsilon: scalar exploration parameter Return E[ log p(z|traj) ] of the batch """ obs, action, reward_e, obs_next, done, z = self.process_dataset(np.array(dataset)) # Downsample obs along the traj dimension # obs has shape [batch, traj, l_obs] obs_downsampled = obs[ :, ::self.traj_skip, : ] if self.obs_truncate_length: obs_downsampled = obs_downsampled[ : , : , :self.obs_truncate_length] if self.use_state_difference: # use the difference between consecutive states in a trajectory, rather than the state obs_downsampled = obs_downsampled[ : , 1: , : ] - obs_downsampled[ : , :-1 , : ] assert( obs_downsampled.shape[1] == self.traj_length_downsampled ) # Train decoder feed = {self.onehot_z : z, self.traj : obs_downsampled} if summarize: summary, _, decoder_probs = sess.run([self.summary_op_decoder, self.decoder_op, self.decoder_probs], feed_dict=feed) writer.add_summary(summary, step_train) else: _, decoder_probs = sess.run([self.decoder_op, self.decoder_probs], feed_dict=feed) # Compute mean and std of batch of P(z|traj) prob = np.sum(np.multiply( decoder_probs, z ), axis=1) log_probs = np.log( prob + 1e-15 ) log_probs_mean = np.mean( log_probs ) log_probs_std = np.std( log_probs ) # decoder_probs has shape [batch, N_roles] expected_prob = np.mean( prob ) # Reshape quantities for low-level policy training N_batch = obs.shape[0] N_traj = obs.shape[1] obs_reshaped = np.reshape(obs, [N_batch * N_traj, self.l_obs]) action_reshaped = np.reshape(action, [N_batch * N_traj, self.l_action]) reward_reshaped = np.reshape(reward_e, [N_batch * N_traj]) obs_next_reshaped = np.reshape(obs_next, [N_batch * N_traj, self.l_obs]) done_reshaped = np.reshape(done, [N_batch * N_traj]) # duplicate s.t. each time step in trajectory gets the same z z_repeated = np.repeat(z, N_traj, axis=0) if self.low_level_alg == 'reinforce': # Compute intrinsic reward for each batch entry reward_i = (log_probs - log_probs_mean) / log_probs_std # Environment reward, sum along trajectory reward_e = np.sum(reward_e, axis=1) reward = alpha * reward_e + (1 - alpha) * reward_i # Train low-level policy feed = {self.epsilon : epsilon, self.obs : obs_reshaped, self.z : z_repeated, self.actions_taken : action_reshaped, self.traj_reward : reward} if summarize: summary, _ = sess.run([self.summary_op_policy, self.policy_op], feed_dict=feed) writer.add_summary(summary, step_train) else: _ = sess.run(self.policy_op, feed_dict=feed) elif self.low_level_alg == 'iac': # NOTE: intrinsic reward not implemented yet # Train critic feed = {self.obs : obs_next_reshaped, self.z : z_repeated} V_target_res, V_next_res = sess.run([self.V_target, self.V], feed_dict=feed) V_target_res = np.squeeze(V_target_res) V_next_res = np.squeeze(V_next_res) # if true, then 0, else 1 done_multiplier = -(done_reshaped - 1) V_td_target = reward_reshaped + self.gamma * V_target_res * done_multiplier feed = {self.V_td_target : V_td_target, self.obs : obs_reshaped, self.z : z_repeated} if summarize: summary, _, V_res = sess.run([self.summary_op_V, self.V_op, self.V], feed_dict=feed) writer.add_summary(summary, step_train) else: _, V_res = sess.run([self.V_op, self.V], feed_dict=feed) # Train policy V_res = np.squeeze(V_res) V_td_target = reward_reshaped + self.gamma * V_next_res * done_multiplier feed = {self.epsilon : epsilon, self.obs : obs_reshaped, self.z : z_repeated, self.actions_taken : action_reshaped, self.V_td_target : V_td_target, self.V_evaluated : V_res} if summarize: summary, _ = sess.run([self.summary_op_policy, self.policy_op], feed_dict=feed) writer.add_summary(summary, step_train) else: _ = sess.run(self.policy_op, feed_dict=feed) sess.run(self.list_update_target_ops_low) else: raise ValueError("alg_hsd.py : self.low_level_alg invalid") return expected_prob
StarcoderdataPython
3325373
<reponame>SMattfeldt/probeye<filename>tests/unit_tests/definition/test_prior.py # standard library imports import unittest # local imports from probeye.definition.prior import PriorBase class TestProblem(unittest.TestCase): def test_prior_template(self): prior_template = PriorBase( "a", ["loc_a", "scale_a"], "a_normal", "normal distribution" ) # check that the attributes are wired correctly self.assertEqual(prior_template.ref_prm, "a") self.assertEqual(prior_template.name, "a_normal") self.assertEqual(prior_template.prior_type, "normal distribution") self.assertEqual( prior_template.prms_def, {"a": "a", "loc_a": "loc_a", "scale_a": "scale_a"} ) self.assertEqual( prior_template.hyperparameters, {"loc_a": "loc_a", "scale_a": "scale_a"} ) # check that the __str__-method works self.assertTrue(len(prior_template.__str__()) > 0) if __name__ == "__main__": unittest.main()
StarcoderdataPython
3323423
import os from testcontainers.postgres import PostgresContainer import psycopg2 from contextlib import contextmanager def get_migration_files(): path = os.path.join(os.path.dirname(__file__), os.pardir, "migration") files = os.listdir(path) files.sort() for f in files: yield os.path.join(path, f) def migrate(conn): cur = conn.cursor() for f in get_migration_files(): with open(f) as fp: stmt = " ".join(fp.readlines()) cur.execute(stmt) conn.commit() @contextmanager def migrated_testcontainer(): with PostgresContainer("postgres:13.0") as postgres: os.environ["DATABASE"] = 'test' os.environ["HOST"] = postgres.get_container_host_ip() os.environ["PORT"] = postgres.get_exposed_port(5432) os.environ["USERNAME"] = postgres.POSTGRES_USER os.environ["PASSWORD"] = <PASSWORD> dsn = f"dbname='test' host='{postgres.get_container_host_ip()}' port='{postgres.get_exposed_port(5432)}' user='{postgres.POSTGRES_USER}' password='{<PASSWORD>}'" conn = psycopg2.connect(dsn) migrate(conn) yield dsn
StarcoderdataPython
107530
# Copyright (c) 2012-2016 <NAME> # Copyright (c) 2012-2018 The Bitmessage developers """ This is not what you run to run the Bitmessage API. Instead, enable the API ( https://bitmessage.org/wiki/API ) and optionally enable daemon mode ( https://bitmessage.org/wiki/Daemon ) then run bitmessagemain.py. """ import base64 import hashlib import json import time from binascii import hexlify, unhexlify from struct import pack import shared from addresses import ( decodeAddress, addBMIfNotPresent, decodeVarint, calculateInventoryHash, varintDecodeError) import defaults import helper_inbox import helper_sent import state import queues import shutdown import network.stats # Classes from helper_sql import sqlQuery, sqlExecute, SqlBulkExecute, sqlStoredProcedure from helper_ackPayload import genAckPayload from inventory import Inventory from version import softwareVersion # Helper Functions import proofofwork __all__ = [ 'BMConfigParser', 'state', 'APIError', 'varintDecodeError', 'Services', 'logger', ] from bmconfigparser import BMConfigParser import state import logging logger = logging.getLogger('default') # logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) # logger.getEffectiveLevel() # logger.setLevel(loggin.INFO) str_chan = '[chan]' # varintDecodeError = addresses.varintDecodeError class APIError(Exception): def __init__(self, error_number, error_message): super(APIError, self).__init__() self.error_number = error_number self.error_message = error_message def __str__(self): return "API Error %04i: %s" % (self.error_number, self.error_message) class Services(object): def _decode(self, text, decode_type): try: if decode_type == 'hex': return unhexlify(text) elif decode_type == 'base64': return base64.b64decode(text) except Exception as e: raise APIError( 22, "Decode error - %s. Had trouble while decoding string: %r" % (e, text) ) def _verifyAddress(self, address): status, addressVersionNumber, streamNumber, ripe = \ decodeAddress(address) if status != 'success': logger.warning( 'API Error 0007: Could not decode address %s. Status: %s.', address, status ) if status == 'checksumfailed': raise APIError(8, 'Checksum failed for address: ' + address) if status == 'invalidcharacters': raise APIError(9, 'Invalid characters in address: ' + address) if status == 'versiontoohigh': raise APIError( 10, 'Address version number too high (or zero) in address: ' + address ) if status == 'varintmalformed': raise APIError(26, 'Malformed varint in address: ' + address) raise APIError( 7, 'Could not decode address: %s : %s' % (address, status)) if addressVersionNumber < 2 or addressVersionNumber > 4: raise APIError( 11, 'The address version number currently must be 2, 3 or 4.' ' Others aren\'t supported. Check the address.' ) if streamNumber != 1: raise APIError( 12, 'The stream number must be 1. Others aren\'t supported.' ' Check the address.' ) return (status, addressVersionNumber, streamNumber, ripe) # Request Handlers def HandleListAddresses(self, method): data = '{"addresses":[' for addressInKeysFile in BMConfigParser().addresses(): status, addressVersionNumber, streamNumber, hash01 = decodeAddress( addressInKeysFile) if len(data) > 20: data += ',' if BMConfigParser().has_option(addressInKeysFile, 'chan'): chan = BMConfigParser().getboolean(addressInKeysFile, 'chan') else: chan = False label = BMConfigParser().get(addressInKeysFile, 'label') if method == 'listAddresses2': label = base64.b64encode(label) data += json.dumps({ 'label': label, 'address': addressInKeysFile, 'stream': streamNumber, 'enabled': BMConfigParser().getboolean(addressInKeysFile, 'enabled'), 'chan': chan }, indent=4, separators=(',', ': ')) data += ']}' return data def HandleListAddressBookEntries(self, params): if len(params) == 1: label, = params label = self._decode(label, "base64") queryreturn = sqlQuery( "SELECT label, address from addressbook WHERE label = ?", label) elif len(params) > 1: raise APIError(0, "Too many paremeters, max 1") else: queryreturn = sqlQuery("SELECT label, address from addressbook") data = '{"addresses":[' for row in queryreturn: label, address = row label = shared.fixPotentiallyInvalidUTF8Data(label) if len(data) > 20: data += ',' data += json.dumps({ 'label': base64.b64encode(label), 'address': address}, indent=4, separators=(',', ': ')) data += ']}' return data def HandleAddAddressBookEntry(self, params): if len(params) != 2: raise APIError(0, "I need label and address") address, label = params label = self._decode(label, "base64") address = addBMIfNotPresent(address) self._verifyAddress(address) queryreturn = sqlQuery( "SELECT address FROM addressbook WHERE address=?", address) if queryreturn != []: raise APIError( 16, 'You already have this address in your address book.') sqlExecute("INSERT INTO addressbook VALUES(?,?)", label, address) queues.UISignalQueue.put(('rerenderMessagelistFromLabels', '')) queues.UISignalQueue.put(('rerenderMessagelistToLabels', '')) queues.UISignalQueue.put(('rerenderAddressBook', '')) return "Added address %s to address book" % address def HandleDeleteAddressBookEntry(self, params): if len(params) != 1: raise APIError(0, "I need an address") address, = params address = addBMIfNotPresent(address) self._verifyAddress(address) sqlExecute('DELETE FROM addressbook WHERE address=?', address) queues.UISignalQueue.put(('rerenderMessagelistFromLabels', '')) queues.UISignalQueue.put(('rerenderMessagelistToLabels', '')) queues.UISignalQueue.put(('rerenderAddressBook', '')) return "Deleted address book entry for %s if it existed" % address def HandleCreateRandomAddress(self, params): if len(params) == 0: raise APIError(0, 'I need parameters!') elif len(params) == 1: label, = params eighteenByteRipe = False nonceTrialsPerByte = BMConfigParser().get( 'bitmessagesettings', 'defaultnoncetrialsperbyte') payloadLengthExtraBytes = BMConfigParser().get( 'bitmessagesettings', 'defaultpayloadlengthextrabytes') elif len(params) == 2: label, eighteenByteRipe = params nonceTrialsPerByte = BMConfigParser().get( 'bitmessagesettings', 'defaultnoncetrialsperbyte') payloadLengthExtraBytes = BMConfigParser().get( 'bitmessagesettings', 'defaultpayloadlengthextrabytes') elif len(params) == 3: label, eighteenByteRipe, totalDifficulty = params nonceTrialsPerByte = int( defaults.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty) payloadLengthExtraBytes = BMConfigParser().get( 'bitmessagesettings', 'defaultpayloadlengthextrabytes') elif len(params) == 4: label, eighteenByteRipe, totalDifficulty, \ smallMessageDifficulty = params nonceTrialsPerByte = int( defaults.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty) payloadLengthExtraBytes = int( defaults.networkDefaultPayloadLengthExtraBytes * smallMessageDifficulty) else: raise APIError(0, 'Too many parameters!') label = self._decode(label, "base64") try: unicode(label, 'utf-8') except: raise APIError(17, 'Label is not valid UTF-8 data.') queues.apiAddressGeneratorReturnQueue.queue.clear() streamNumberForAddress = 1 queues.addressGeneratorQueue.put(( 'createRandomAddress', 4, streamNumberForAddress, label, 1, "", eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes )) return queues.apiAddressGeneratorReturnQueue.get() def HandleCreateDeterministicAddresses(self, params): if len(params) == 0: raise APIError(0, 'I need parameters!') elif len(params) == 1: passphrase, = params numberOfAddresses = 1 addressVersionNumber = 0 streamNumber = 0 eighteenByteRipe = False nonceTrialsPerByte = BMConfigParser().get( 'bitmessagesettings', 'defaultnoncetrialsperbyte') payloadLengthExtraBytes = BMConfigParser().get( 'bitmessagesettings', 'defaultpayloadlengthextrabytes') elif len(params) == 2: passphrase, numberOfAddresses = params addressVersionNumber = 0 streamNumber = 0 eighteenByteRipe = False nonceTrialsPerByte = BMConfigParser().get( 'bitmessagesettings', 'defaultnoncetrialsperbyte') payloadLengthExtraBytes = BMConfigParser().get( 'bitmessagesettings', 'defaultpayloadlengthextrabytes') elif len(params) == 3: passphrase, numberOfAddresses, addressVersionNumber = params streamNumber = 0 eighteenByteRipe = False nonceTrialsPerByte = BMConfigParser().get( 'bitmessagesettings', 'defaultnoncetrialsperbyte') payloadLengthExtraBytes = BMConfigParser().get( 'bitmessagesettings', 'defaultpayloadlengthextrabytes') elif len(params) == 4: passphrase, numberOfAddresses, addressVersionNumber, \ streamNumber = params eighteenByteRipe = False nonceTrialsPerByte = BMConfigParser().get( 'bitmessagesettings', 'defaultnoncetrialsperbyte') payloadLengthExtraBytes = BMConfigParser().get( 'bitmessagesettings', 'defaultpayloadlengthextrabytes') elif len(params) == 5: passphrase, numberOfAddresses, addressVersionNumber, \ streamNumber, eighteenByteRipe = params nonceTrialsPerByte = BMConfigParser().get( 'bitmessagesettings', 'defaultnoncetrialsperbyte') payloadLengthExtraBytes = BMConfigParser().get( 'bitmessagesettings', 'defaultpayloadlengthextrabytes') elif len(params) == 6: passphrase, numberOfAddresses, addressVersionNumber, \ streamNumber, eighteenByteRipe, totalDifficulty = params nonceTrialsPerByte = int( defaults.networkDefaultPayloadLengthExtraBytes * totalDifficulty) payloadLengthExtraBytes = BMConfigParser().get( 'bitmessagesettings', 'defaultpayloadlengthextrabytes') elif len(params) == 7: passphrase, numberOfAddresses, addressVersionNumber, \ streamNumber, eighteenByteRipe, totalDifficulty, \ smallMessageDifficulty = params nonceTrialsPerByte = int( defaults.networkDefaultPayloadLengthExtraBytes * totalDifficulty) payloadLengthExtraBytes = int( defaults.networkDefaultPayloadLengthExtraBytes * smallMessageDifficulty) else: raise APIError(0, 'Too many parameters!') if len(passphrase) == 0: raise APIError(1, 'The specified passphrase is blank.') if not isinstance(eighteenByteRipe, bool): raise APIError( 23, 'Bool expected in eighteenByteRipe, saw %s instead' % type(eighteenByteRipe)) passphrase = self._decode(passphrase, "base64") # 0 means "just use the proper addressVersionNumber" if addressVersionNumber == 0: addressVersionNumber = 4 if addressVersionNumber != 3 and addressVersionNumber != 4: raise APIError( 2, 'The address version number currently must be 3, 4, or 0' ' (which means auto-select). %i isn\'t supported.' % addressVersionNumber) if streamNumber == 0: # 0 means "just use the most available stream" streamNumber = 1 if streamNumber != 1: raise APIError( 3, 'The stream number must be 1 (or 0 which means' ' auto-select). Others aren\'t supported.') if numberOfAddresses == 0: raise APIError( 4, 'Why would you ask me to generate 0 addresses for you?') if numberOfAddresses > 999: raise APIError( 5, 'You have (accidentally?) specified too many addresses to' ' make. Maximum 999. This check only exists to prevent' ' mischief; if you really want to create more addresses than' ' this, contact the Bitmessage developers and we can modify' ' the check or you can do it yourself by searching the source' ' code for this message.') queues.apiAddressGeneratorReturnQueue.queue.clear() logger.debug( 'Requesting that the addressGenerator create %s addresses.', numberOfAddresses) queues.addressGeneratorQueue.put(( 'createDeterministicAddresses', addressVersionNumber, streamNumber, 'unused API address', numberOfAddresses, passphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes )) data = '{"addresses":[' queueReturn = queues.apiAddressGeneratorReturnQueue.get() for item in queueReturn: if len(data) > 20: data += ',' data += "\"" + item + "\"" data += ']}' return data def HandleGetDeterministicAddress(self, params): if len(params) != 3: raise APIError(0, 'I need exactly 3 parameters.') passphrase, addressVersionNumber, streamNumber = params numberOfAddresses = 1 eighteenByteRipe = False if len(passphrase) == 0: raise APIError(1, 'The specified passphrase is blank.') passphrase = self._decode(passphrase, "base64") if addressVersionNumber != 3 and addressVersionNumber != 4: raise APIError( 2, 'The address version number currently must be 3 or 4. %i' ' isn\'t supported.' % addressVersionNumber) if streamNumber != 1: raise APIError( 3, ' The stream number must be 1. Others aren\'t supported.') queues.apiAddressGeneratorReturnQueue.queue.clear() logger.debug( 'Requesting that the addressGenerator create %s addresses.', numberOfAddresses) queues.addressGeneratorQueue.put(( 'getDeterministicAddress', addressVersionNumber, streamNumber, 'unused API address', numberOfAddresses, passphrase, eighteenByteRipe )) return queues.apiAddressGeneratorReturnQueue.get() def HandleCreateChan(self, params): if len(params) == 0: raise APIError(0, 'I need parameters.') elif len(params) == 1: passphrase, = params passphrase = self._decode(passphrase, "base64") if len(passphrase) == 0: raise APIError(1, 'The specified passphrase is blank.') # It would be nice to make the label the passphrase but it is # possible that the passphrase contains non-utf-8 characters. try: unicode(passphrase, 'utf-8') label = str_chan + ' ' + passphrase except: label = str_chan + ' ' + repr(passphrase) addressVersionNumber = 4 streamNumber = 1 queues.apiAddressGeneratorReturnQueue.queue.clear() logger.debug( 'Requesting that the addressGenerator create chan %s.', passphrase) queues.addressGeneratorQueue.put(( 'createChan', addressVersionNumber, streamNumber, label, passphrase, True )) queueReturn = queues.apiAddressGeneratorReturnQueue.get() if len(queueReturn) == 0: raise APIError(24, 'Chan address is already present.') address = queueReturn[0] return address def HandleJoinChan(self, params): if len(params) < 2: raise APIError(0, 'I need two parameters.') elif len(params) == 2: passphrase, suppliedAddress = params passphrase = self._decode(passphrase, "base64") if len(passphrase) == 0: raise APIError(1, 'The specified passphrase is blank.') # It would be nice to make the label the passphrase but it is # possible that the passphrase contains non-utf-8 characters. try: unicode(passphrase, 'utf-8') label = str_chan + ' ' + passphrase except: label = str_chan + ' ' + repr(passphrase) status, addressVersionNumber, streamNumber, toRipe = \ self._verifyAddress(suppliedAddress) suppliedAddress = addBMIfNotPresent(suppliedAddress) queues.apiAddressGeneratorReturnQueue.queue.clear() queues.addressGeneratorQueue.put(( 'joinChan', suppliedAddress, label, passphrase, True )) addressGeneratorReturnValue = \ queues.apiAddressGeneratorReturnQueue.get() if addressGeneratorReturnValue[0] == \ 'chan name does not match address': raise APIError(18, 'Chan name does not match address.') if len(addressGeneratorReturnValue) == 0: raise APIError(24, 'Chan address is already present.') # TODO: this variable is not used to anything # in case we ever want it for anything. # createdAddress = addressGeneratorReturnValue[0] return "success" def HandleLeaveChan(self, params): if len(params) == 0: raise APIError(0, 'I need parameters.') elif len(params) == 1: address, = params status, addressVersionNumber, streamNumber, toRipe = \ self._verifyAddress(address) address = addBMIfNotPresent(address) if not BMConfigParser().has_section(address): raise APIError( 13, 'Could not find this address in your keys.dat file.') if not BMConfigParser().safeGetBoolean(address, 'chan'): raise APIError( 25, 'Specified address is not a chan address.' ' Use deleteAddress API call instead.') BMConfigParser().remove_section(address) with open(state.appdata + 'keys.dat', 'wb') as configfile: BMConfigParser().write(configfile) return 'success' def HandleDeleteAddress(self, params): if len(params) == 0: raise APIError(0, 'I need parameters.') elif len(params) == 1: address, = params status, addressVersionNumber, streamNumber, toRipe = \ self._verifyAddress(address) address = addBMIfNotPresent(address) if not BMConfigParser().has_section(address): raise APIError( 13, 'Could not find this address in your keys.dat file.') BMConfigParser().remove_section(address) with open(state.appdata + 'keys.dat', 'wb') as configfile: BMConfigParser().write(configfile) queues.UISignalQueue.put(('rerenderMessagelistFromLabels', '')) queues.UISignalQueue.put(('rerenderMessagelistToLabels', '')) shared.reloadMyAddressHashes() return 'success' def HandleGetAllInboxMessages(self, params): queryreturn = sqlQuery( "SELECT msgid, toaddress, fromaddress, subject, received, message," " encodingtype, read FROM inbox where folder='inbox'" " ORDER BY received" ) data = '{"inboxMessages":[' for row in queryreturn: msgid, toAddress, fromAddress, subject, received, message, \ encodingtype, read = row subject = shared.fixPotentiallyInvalidUTF8Data(subject) message = shared.fixPotentiallyInvalidUTF8Data(message) if len(data) > 25: data += ',' data += json.dumps({ 'msgid': hexlify(msgid), 'toAddress': toAddress, 'fromAddress': fromAddress, 'subject': base64.b64encode(subject), 'message': base64.b64encode(message), 'encodingType': encodingtype, 'receivedTime': received, 'read': read}, indent=4, separators=(',', ': ')) data += ']}' return data def HandleGetAllInboxMessageIds(self, params): queryreturn = sqlQuery( "SELECT msgid FROM inbox where folder='inbox' ORDER BY received") data = '{"inboxMessageIds":[' for row in queryreturn: msgid = row[0] if len(data) > 25: data += ',' data += json.dumps( {'msgid': hexlify(msgid)}, indent=4, separators=(',', ': ')) data += ']}' return data def HandleGetInboxMessageById(self, params): if len(params) == 0: raise APIError(0, 'I need parameters!') elif len(params) == 1: msgid = self._decode(params[0], "hex") elif len(params) >= 2: msgid = self._decode(params[0], "hex") readStatus = params[1] if not isinstance(readStatus, bool): raise APIError( 23, 'Bool expected in readStatus, saw %s instead.' % type(readStatus)) queryreturn = sqlQuery( "SELECT read FROM inbox WHERE msgid=?", msgid) # UPDATE is slow, only update if status is different if queryreturn != [] and (queryreturn[0][0] == 1) != readStatus: sqlExecute( "UPDATE inbox set read = ? WHERE msgid=?", readStatus, msgid) queues.UISignalQueue.put(('changedInboxUnread', None)) queryreturn = sqlQuery( "SELECT msgid, toaddress, fromaddress, subject, received, message," " encodingtype, read FROM inbox WHERE msgid=?", msgid ) data = '{"inboxMessage":[' for row in queryreturn: msgid, toAddress, fromAddress, subject, received, message, \ encodingtype, read = row subject = shared.fixPotentiallyInvalidUTF8Data(subject) message = shared.fixPotentiallyInvalidUTF8Data(message) data += json.dumps({ 'msgid': hexlify(msgid), 'toAddress': toAddress, 'fromAddress': fromAddress, 'subject': base64.b64encode(subject), 'message': base64.b64encode(message), 'encodingType': encodingtype, 'receivedTime': received, 'read': read}, indent=4, separators=(',', ': ')) data += ']}' return data def HandleGetAllSentMessages(self, params): queryreturn = sqlQuery( "SELECT msgid, toaddress, fromaddress, subject, lastactiontime," " message, encodingtype, status, ackdata FROM sent" " WHERE folder='sent' ORDER BY lastactiontime" ) data = '{"sentMessages":[' for row in queryreturn: msgid, toAddress, fromAddress, subject, lastactiontime, message, \ encodingtype, status, ackdata = row subject = shared.fixPotentiallyInvalidUTF8Data(subject) message = shared.fixPotentiallyInvalidUTF8Data(message) if len(data) > 25: data += ',' data += json.dumps({ 'msgid': hexlify(msgid), 'toAddress': toAddress, 'fromAddress': fromAddress, 'subject': base64.b64encode(subject), 'message': base64.b64encode(message), 'encodingType': encodingtype, 'lastActionTime': lastactiontime, 'status': status, 'ackData': hexlify(ackdata)}, indent=4, separators=(',', ': ')) data += ']}' return data def HandleGetAllSentMessageIds(self, params): queryreturn = sqlQuery( "SELECT msgid FROM sent where folder='sent'" " ORDER BY lastactiontime" ) data = '{"sentMessageIds":[' for row in queryreturn: msgid = row[0] if len(data) > 25: data += ',' data += json.dumps( {'msgid': hexlify(msgid)}, indent=4, separators=(',', ': ')) data += ']}' return data def HandleInboxMessagesByReceiver(self, params): if len(params) == 0: raise APIError(0, 'I need parameters!') toAddress = params[0] queryreturn = sqlQuery( "SELECT msgid, toaddress, fromaddress, subject, received, message," " encodingtype FROM inbox WHERE folder='inbox' AND toAddress=?", toAddress) data = '{"inboxMessages":[' for row in queryreturn: msgid, toAddress, fromAddress, subject, received, message, \ encodingtype = row subject = shared.fixPotentiallyInvalidUTF8Data(subject) message = shared.fixPotentiallyInvalidUTF8Data(message) if len(data) > 25: data += ',' data += json.dumps({ 'msgid': hexlify(msgid), 'toAddress': toAddress, 'fromAddress': fromAddress, 'subject': base64.b64encode(subject), 'message': base64.b64encode(message), 'encodingType': encodingtype, 'receivedTime': received}, indent=4, separators=(',', ': ')) data += ']}' return data def HandleGetSentMessageById(self, params): if len(params) == 0: raise APIError(0, 'I need parameters!') msgid = self._decode(params[0], "hex") queryreturn = sqlQuery( "SELECT msgid, toaddress, fromaddress, subject, lastactiontime," " message, encodingtype, status, ackdata FROM sent WHERE msgid=?", msgid ) data = '{"sentMessage":[' for row in queryreturn: msgid, toAddress, fromAddress, subject, lastactiontime, message, \ encodingtype, status, ackdata = row subject = shared.fixPotentiallyInvalidUTF8Data(subject) message = shared.fixPotentiallyInvalidUTF8Data(message) data += json.dumps({ 'msgid': hexlify(msgid), 'toAddress': toAddress, 'fromAddress': fromAddress, 'subject': base64.b64encode(subject), 'message': base64.b64encode(message), 'encodingType': encodingtype, 'lastActionTime': lastactiontime, 'status': status, 'ackData': hexlify(ackdata)}, indent=4, separators=(',', ': ')) data += ']}' return data def HandleGetSentMessagesBySender(self, params): # HandleGetSentMessagesByAddress if len(params) == 0: raise APIError(0, 'I need parameters!') fromAddress = params[0] queryreturn = sqlQuery( "SELECT msgid, toaddress, fromaddress, subject, lastactiontime," " message, encodingtype, status, ackdata FROM sent" " WHERE folder='sent' AND fromAddress=? ORDER BY lastactiontime", fromAddress ) data = '{"sentMessages":[' for row in queryreturn: msgid, toAddress, fromAddress, subject, lastactiontime, message, \ encodingtype, status, ackdata = row subject = shared.fixPotentiallyInvalidUTF8Data(subject) message = shared.fixPotentiallyInvalidUTF8Data(message) if len(data) > 25: data += ',' data += json.dumps({ 'msgid': hexlify(msgid), 'toAddress': toAddress, 'fromAddress': fromAddress, 'subject': base64.b64encode(subject), 'message': base64.b64encode(message), 'encodingType': encodingtype, 'lastActionTime': lastactiontime, 'status': status, 'ackData': hexlify(ackdata)}, indent=4, separators=(',', ': ')) data += ']}' return data def HandleGetSentMessagesByAckData(self, params): if len(params) == 0: raise APIError(0, 'I need parameters!') ackData = self._decode(params[0], "hex") queryreturn = sqlQuery( "SELECT msgid, toaddress, fromaddress, subject, lastactiontime," " message, encodingtype, status, ackdata FROM sent" " WHERE ackdata=?", ackData ) data = '{"sentMessage":[' for row in queryreturn: msgid, toAddress, fromAddress, subject, lastactiontime, message, \ encodingtype, status, ackdata = row subject = shared.fixPotentiallyInvalidUTF8Data(subject) message = shared.fixPotentiallyInvalidUTF8Data(message) data += json.dumps({ 'msgid': hexlify(msgid), 'toAddress': toAddress, 'fromAddress': fromAddress, 'subject': base64.b64encode(subject), 'message': base64.b64encode(message), 'encodingType': encodingtype, 'lastActionTime': lastactiontime, 'status': status, 'ackData': hexlify(ackdata)}, indent=4, separators=(',', ': ')) data += ']}' return data def HandleTrashMessage(self, params): if len(params) == 0: raise APIError(0, 'I need parameters!') msgid = self._decode(params[0], "hex") # Trash if in inbox table helper_inbox.trash(msgid) # Trash if in sent table sqlExecute('''UPDATE sent SET folder='trash' WHERE msgid=?''', msgid) return 'Trashed message (assuming message existed).' def HandleTrashInboxMessage(self, params): if len(params) == 0: raise APIError(0, 'I need parameters!') msgid = self._decode(params[0], "hex") helper_inbox.trash(msgid) return 'Trashed inbox message (assuming message existed).' def HandleTrashSentMessage(self, params): if len(params) == 0: raise APIError(0, 'I need parameters!') msgid = self._decode(params[0], "hex") sqlExecute('''UPDATE sent SET folder='trash' WHERE msgid=?''', msgid) return 'Trashed sent message (assuming message existed).' def HandleSendMessage(self, params): if len(params) == 0: raise APIError(0, 'I need parameters!') elif len(params) == 4: toAddress, fromAddress, subject, message = params encodingType = 2 TTL = 4 * 24 * 60 * 60 elif len(params) == 5: toAddress, fromAddress, subject, message, encodingType = params TTL = 4 * 24 * 60 * 60 elif len(params) == 6: toAddress, fromAddress, subject, message, encodingType, TTL = \ params if encodingType not in [2, 3]: raise APIError(6, 'The encoding type must be 2 or 3.') subject = self._decode(subject, "base64") message = self._decode(message, "base64") if len(subject + message) > (2 ** 18 - 500): raise APIError(27, 'Message is too long.') if TTL < 60 * 60: TTL = 60 * 60 if TTL > 28 * 24 * 60 * 60: TTL = 28 * 24 * 60 * 60 toAddress = addBMIfNotPresent(toAddress) fromAddress = addBMIfNotPresent(fromAddress) status, addressVersionNumber, streamNumber, toRipe = \ self._verifyAddress(toAddress) self._verifyAddress(fromAddress) try: fromAddressEnabled = BMConfigParser().getboolean( fromAddress, 'enabled') except: raise APIError( 13, 'Could not find your fromAddress in the keys.dat file.') if not fromAddressEnabled: raise APIError(14, 'Your fromAddress is disabled. Cannot send.') stealthLevel = BMConfigParser().safeGetInt( 'bitmessagesettings', 'ackstealthlevel') ackdata = genAckPayload(streamNumber, stealthLevel) t = ('', toAddress, toRipe, fromAddress, subject, message, ackdata, int(time.time()), # sentTime (this won't change) int(time.time()), # lastActionTime 0, 'msgqueued', 0, 'sent', 2, TTL) helper_sent.insert(t) toLabel = '' queryreturn = sqlQuery( "SELECT label FROM addressbook WHERE address=?", toAddress) if queryreturn != []: for row in queryreturn: toLabel, = row # apiSignalQueue.put(('displayNewSentMessage',(toAddress,toLabel,fromAddress,subject,message,ackdata))) queues.UISignalQueue.put(('displayNewSentMessage', ( toAddress, toLabel, fromAddress, subject, message, ackdata))) queues.workerQueue.put(('sendmessage', toAddress)) return hexlify(ackdata) def HandleSendBroadcast(self, params): if len(params) == 0: raise APIError(0, 'I need parameters!') if len(params) == 3: fromAddress, subject, message = params encodingType = 2 TTL = 4 * 24 * 60 * 60 elif len(params) == 4: fromAddress, subject, message, encodingType = params TTL = 4 * 24 * 60 * 60 elif len(params) == 5: fromAddress, subject, message, encodingType, TTL = params if encodingType not in [2, 3]: raise APIError(6, 'The encoding type must be 2 or 3.') subject = self._decode(subject, "base64") message = self._decode(message, "base64") if len(subject + message) > (2 ** 18 - 500): raise APIError(27, 'Message is too long.') if TTL < 60 * 60: TTL = 60 * 60 if TTL > 28 * 24 * 60 * 60: TTL = 28 * 24 * 60 * 60 fromAddress = addBMIfNotPresent(fromAddress) self._verifyAddress(fromAddress) try: BMConfigParser().getboolean(fromAddress, 'enabled') except: raise APIError( 13, 'could not find your fromAddress in the keys.dat file.') streamNumber = decodeAddress(fromAddress)[2] ackdata = genAckPayload(streamNumber, 0) toAddress = '[Broadcast subscribers]' ripe = '' t = ('', toAddress, ripe, fromAddress, subject, message, ackdata, int(time.time()), # sentTime (this doesn't change) int(time.time()), # lastActionTime 0, 'broadcastqueued', 0, 'sent', 2, TTL) helper_sent.insert(t) toLabel = '[Broadcast subscribers]' queues.UISignalQueue.put(('displayNewSentMessage', ( toAddress, toLabel, fromAddress, subject, message, ackdata))) queues.workerQueue.put(('sendbroadcast', '')) return hexlify(ackdata) def HandleGetStatus(self, params): if len(params) != 1: raise APIError(0, 'I need one parameter!') ackdata, = params if len(ackdata) < 76: # The length of ackData should be at least 38 bytes (76 hex digits) raise APIError(15, 'Invalid ackData object size.') ackdata = self._decode(ackdata, "hex") queryreturn = sqlQuery( "SELECT status FROM sent where ackdata=?", ackdata) if queryreturn == []: return 'notfound' for row in queryreturn: status, = row return status def HandleAddSubscription(self, params): if len(params) == 0: raise APIError(0, 'I need parameters!') if len(params) == 1: address, = params label = '' if len(params) == 2: address, label = params label = self._decode(label, "base64") try: unicode(label, 'utf-8') except: raise APIError(17, 'Label is not valid UTF-8 data.') if len(params) > 2: raise APIError(0, 'I need either 1 or 2 parameters!') address = addBMIfNotPresent(address) self._verifyAddress(address) # First we must check to see if the address is already in the # subscriptions list. queryreturn = sqlQuery( "SELECT * FROM subscriptions WHERE address=?", address) if queryreturn != []: raise APIError(16, 'You are already subscribed to that address.') sqlExecute( "INSERT INTO subscriptions VALUES (?,?,?)", label, address, True) shared.reloadBroadcastSendersForWhichImWatching() queues.UISignalQueue.put(('rerenderMessagelistFromLabels', '')) queues.UISignalQueue.put(('rerenderSubscriptions', '')) return 'Added subscription.' def HandleDeleteSubscription(self, params): if len(params) != 1: raise APIError(0, 'I need 1 parameter!') address, = params address = addBMIfNotPresent(address) sqlExecute('''DELETE FROM subscriptions WHERE address=?''', address) shared.reloadBroadcastSendersForWhichImWatching() queues.UISignalQueue.put(('rerenderMessagelistFromLabels', '')) queues.UISignalQueue.put(('rerenderSubscriptions', '')) return 'Deleted subscription if it existed.' def HandleListSubscriptions(self, params): # ListSubscriptions queryreturn = sqlQuery( "SELECT label, address, enabled FROM subscriptions") data = {'subscriptions': []} for row in queryreturn: label, address, enabled = row label = shared.fixPotentiallyInvalidUTF8Data(label) data['subscriptions'].append({ 'label': base64.b64encode(label), 'address': address, 'enabled': enabled == 1 }) return json.dumps(data, indent=4, separators=(',', ': ')) def HandleDisseminatePreEncryptedMsg(self, params): # The device issuing this command to PyBitmessage supplies a msg # object that has already been encrypted but which still needs the POW # to be done. PyBitmessage accepts this msg object and sends it out # to the rest of the Bitmessage network as if it had generated # the message itself. Please do not yet add this to the api doc. if len(params) != 3: raise APIError(0, 'I need 3 parameter!') encryptedPayload, requiredAverageProofOfWorkNonceTrialsPerByte, \ requiredPayloadLengthExtraBytes = params encryptedPayload = self._decode(encryptedPayload, "hex") # Let us do the POW and attach it to the front target = 2**64 / ( (len(encryptedPayload) + requiredPayloadLengthExtraBytes + 8) * requiredAverageProofOfWorkNonceTrialsPerByte) with shared.printLock: print('(For msg message via API) Doing proof of work. Total required difficulty:', float(requiredAverageProofOfWorkNonceTrialsPerByte) / defaults.networkDefaultPayloadLengthExtraBytes, 'Required small message difficulty:', float(requiredPayloadLengthExtraBytes) / defaults.networkDefaultPayloadLengthExtraBytes) powStartTime = time.time() initialHash = hashlib.sha512(encryptedPayload).digest() trialValue, nonce = proofofwork.run(target, initialHash) with shared.printLock: print('(For msg message via API) Found proof of work', trialValue, 'Nonce:', nonce) try: print('POW took %d seconds. %d nonce trials per second.' % (int(time.time() - powStartTime), nonce / (time.time() - powStartTime))) except: pass encryptedPayload = pack('>Q', nonce) + encryptedPayload toStreamNumber = decodeVarint(encryptedPayload[16:26])[0] inventoryHash = calculateInventoryHash(encryptedPayload) objectType = 2 TTL = 2.5 * 24 * 60 * 60 Inventory()[inventoryHash] = ( objectType, toStreamNumber, encryptedPayload, int(time.time()) + TTL, '' ) with shared.printLock: print('Broadcasting inv for msg(API disseminatePreEncryptedMsg command):', hexlify(inventoryHash)) queues.invQueue.put((toStreamNumber, inventoryHash)) def HandleTrashSentMessageByAckDAta(self, params): # This API method should only be used when msgid is not available if len(params) == 0: raise APIError(0, 'I need parameters!') ackdata = self._decode(params[0], "hex") sqlExecute("UPDATE sent SET folder='trash' WHERE ackdata=?", ackdata) return 'Trashed sent message (assuming message existed).' def HandleDissimatePubKey(self, params): # The device issuing this command to PyBitmessage supplies a pubkey # object to be disseminated to the rest of the Bitmessage network. # PyBitmessage accepts this pubkey object and sends it out to the rest # of the Bitmessage network as if it had generated the pubkey object # itself. Please do not yet add this to the api doc. if len(params) != 1: raise APIError(0, 'I need 1 parameter!') payload, = params payload = self._decode(payload, "hex") # Let us do the POW target = 2 ** 64 / ( (len(payload) + defaults.networkDefaultPayloadLengthExtraBytes + 8) * defaults.networkDefaultPayloadLengthExtraBytes) print('(For pubkey message via API) Doing proof of work...') initialHash = hashlib.sha512(payload).digest() trialValue, nonce = proofofwork.run(target, initialHash) print('(For pubkey message via API) Found proof of work', trialValue, 'Nonce:', nonce) payload = pack('>Q', nonce) + payload pubkeyReadPosition = 8 # bypass the nonce if payload[pubkeyReadPosition:pubkeyReadPosition+4] == \ '\x00\x00\x00\x00': # if this pubkey uses 8 byte time pubkeyReadPosition += 8 else: pubkeyReadPosition += 4 addressVersion, addressVersionLength = decodeVarint( payload[pubkeyReadPosition:pubkeyReadPosition+10]) pubkeyReadPosition += addressVersionLength pubkeyStreamNumber = decodeVarint( payload[pubkeyReadPosition:pubkeyReadPosition+10])[0] inventoryHash = calculateInventoryHash(payload) objectType = 1 # TODO: support v4 pubkeys TTL = 28 * 24 * 60 * 60 Inventory()[inventoryHash] = ( objectType, pubkeyStreamNumber, payload, int(time.time()) + TTL, '' ) with shared.printLock: print('broadcasting inv within API command disseminatePubkey with hash:', hexlify(inventoryHash)) queues.invQueue.put((pubkeyStreamNumber, inventoryHash)) def HandleGetMessageDataByDestinationHash(self, params): # Method will eventually be used by a particular Android app to # select relevant messages. Do not yet add this to the api # doc. if len(params) != 1: raise APIError(0, 'I need 1 parameter!') requestedHash, = params if len(requestedHash) != 32: raise APIError( 19, 'The length of hash should be 32 bytes (encoded in hex' ' thus 64 characters).') requestedHash = self._decode(requestedHash, "hex") # This is not a particularly commonly used API function. Before we # use it we'll need to fill out a field in our inventory database # which is blank by default (first20bytesofencryptedmessage). queryreturn = sqlQuery( "SELECT hash, payload FROM inventory WHERE tag = ''" " and objecttype = 2") with SqlBulkExecute() as sql: for row in queryreturn: hash01, payload = row readPosition = 16 # Nonce length + time length # Stream Number length readPosition += decodeVarint( payload[readPosition:readPosition+10])[1] t = (payload[readPosition:readPosition+32], hash01) sql.execute("UPDATE inventory SET tag=? WHERE hash=?", *t) queryreturn = sqlQuery( "SELECT payload FROM inventory WHERE tag = ?", requestedHash) data = '{"receivedMessageDatas":[' for row in queryreturn: payload, = row if len(data) > 25: data += ',' data += json.dumps( {'data': hexlify(payload)}, indent=4, separators=(',', ': ')) data += ']}' return data def HandleClientStatus(self, params): if len(network.stats.connectedHostsList()) == 0: networkStatus = 'notConnected' elif len(network.stats.connectedHostsList()) > 0 \ and not shared.clientHasReceivedIncomingConnections: networkStatus = 'connectedButHaveNotReceivedIncomingConnections' else: networkStatus = 'connectedAndReceivingIncomingConnections' return json.dumps({ 'networkConnections': len(network.stats.connectedHostsList()), 'shared.numberOfMessagesProcessed': shared.numberOfMessagesProcessed, 'shared.numberOfBroadcastsProcessed': shared.numberOfBroadcastsProcessed, 'shared.numberOfPubkeysProcessed': shared.numberOfPubkeysProcessed, 'networkStatus': networkStatus, 'softwareName': 'PyBitmessage', 'softwareVersion': softwareVersion }, indent=4, separators=(',', ': ')) def HandleDecodeAddress(self, params): # Return a meaningful decoding of an address. if len(params) != 1: raise APIError(0, 'I need 1 parameter!') address, = params status, addressVersion, streamNumber, ripe = decodeAddress(address) return json.dumps({ 'status': status, 'addressVersion': addressVersion, 'streamNumber': streamNumber, 'ripe': base64.b64encode(ripe) }, indent=4, separators=(',', ': ')) def HandleHelloWorld(self, params): a, b = params return a + '-' + b def HandleAdd(self, params): a, b = params return a + b def HandleStatusBar(self, params): message, = params queues.UISignalQueue.put(('updateStatusBar', message)) def HandleDeleteAndVacuum(self, params): if not params: sqlStoredProcedure('deleteandvacuume') return 'done' def HandleShutdown(self, params): if not params: shutdown.doCleanShutdown() return 'done'
StarcoderdataPython
4803634
from . import xmltodict from pymatgen import Structure
StarcoderdataPython
143894
<reponame>CodePsy-2001/hanshift JONG_COMP = { 'ㄱ': { 'ㄱ': 'ㄲ', 'ㅅ': 'ㄳ', }, 'ㄴ': { 'ㅈ': 'ㄵ', 'ㅎ': 'ㄶ', }, 'ㄹ': { 'ㄱ': 'ㄺ', 'ㅁ': 'ㄻ', 'ㅂ': 'ㄼ', 'ㅅ': 'ㄽ', 'ㅌ': 'ㄾ', 'ㅍ': 'ㄿ', 'ㅎ': 'ㅀ', } } DEFAULT_COMPOSE_SEPARATOR = u'ᴥ' ################################################################################ # Hangul Automata functions by <EMAIL> ################################################################################ def decompose(text, latin_filter=True, separator=DEFAULT_COMPOSE_SEPARATOR): from . import letter result = "" for c in list(text): if letter.is_hangul(c): result += "".join(letter.decompose(c)) + separator else: result = result + c return result STATUS_CHO = 0 STATUS_JOONG = 1 STATUS_JONG1 = 2 STATUS_JONG2 = 3 def compose(text, compose_code=DEFAULT_COMPOSE_SEPARATOR): from .const import ONSET, NUCLEUS, CODA from . import letter res_text = "" status = STATUS_CHO for c in text: if status == STATUS_CHO: if c in ONSET: chosung = c status = STATUS_JOONG else: if c != compose_code: res_text = res_text + c elif status == STATUS_JOONG: if c != compose_code and c in NUCLEUS: joongsung = c status = STATUS_JONG1 else: res_text = res_text + chosung if c in ONSET: chosung = c status = STATUS_JOONG else: if c != compose_code: res_text = res_text + c status = STATUS_CHO elif status == STATUS_JONG1: if c != compose_code and c in CODA: jongsung = c if c in JONG_COMP: status = STATUS_JONG2 else: res_text = res_text + letter.compose(chosung, joongsung, jongsung) status = STATUS_CHO else: res_text = res_text + letter.compose(chosung, joongsung) if c in ONSET: chosung = c status = STATUS_JOONG else: if c != compose_code: res_text = res_text + c status = STATUS_CHO elif status == STATUS_JONG2: if c != compose_code and c in JONG_COMP[jongsung]: jongsung = JONG_COMP[jongsung][c] c = compose_code # 종성째 출력 방지 res_text = res_text + letter.compose(chosung, joongsung, jongsung) if c != compose_code: res_text = res_text + c status = STATUS_CHO return res_text
StarcoderdataPython
3294436
import gitlab import dateutil.parser import reader.cache import hashlib import logging from pandas import DataFrame, NaT from datetime import datetime class Gitlab: def __init__(self, gitlab_config: dict, workflow: dict): self.gitlab_config = gitlab_config self.workflow = workflow def cache_name(self): token = self.gitlab_config["token"] workflow = str(self.workflow) url = self.gitlab_config["url"] project_id = ( self.gitlab_config.get("project_id") if self.gitlab_config.get("project_id") else self.gitlab_config.get("group_id") ) name_hashed = hashlib.md5( (token + url + workflow + str(project_id)).encode("utf-8") ) return name_hashed.hexdigest() self.cache = reader.cache.Cache(cache_name(self)) def get_gitlab_instance(self): gl = gitlab.Gitlab( self.gitlab_config["url"], private_token=self.gitlab_config["token"] ) gl.auth() return gl def get_issue_data(self, issue): issue_data = { "Key": issue.id, "Type": "issue", "Creator": issue.author["name"], "Created": dateutil.parser.parse(issue.created_at).replace(tzinfo=None), "Done": ( dateutil.parser.parse(issue.created_at).replace(tzinfo=None) if issue.created_at else NaT ), } return issue_data def get_issues(self): gl = self.get_gitlab_instance() if self.gitlab_config.get("project_id"): project = gl.projects.get(self.gitlab_config["project_id"]) issues = project.issues.list() elif self.gitlab_config.get("group_id"): group = gl.groups.get(self.gitlab_config["group_id"]) issues = group.issues.list() else: raise Exception("No valid project_id or group_id found!") return issues def get_data(self) -> DataFrame: if self.gitlab_config["cache"] and self.cache.is_valid(): logging.debug("Getting gitlab data from cache") df_issue_data = self.cache.read() return df_issue_data issues = self.get_issues() # issue_data = {"Key": [], "Type": [], "Creator": [], "Created": [], "Done": []} issues_data = [self.get_issue_data(issue) for issue in issues] df_issues_data = DataFrame(issues_data) if self.gitlab_config["cache"]: logging.debug("Storing gitlab issue data in cache") self.cache.write(df_issues_data) return df_issues_data def refresh_data(self, date: datetime) -> DataFrame: if self.gitlab_config["cache"] and self.cache.is_valid(): self.cache.clean() return self.get_data()
StarcoderdataPython
1745356
import logging from unittest import TestCase from parameterized import parameterized, param from hvac import exceptions from tests import utils from tests.utils.hvac_integration_test_case import HvacIntegrationTestCase from tests.utils.mock_ldap_server import MockLdapServer class TestLdap(HvacIntegrationTestCase, TestCase): TEST_LDAP_PATH = 'test-ldap' ldap_server = None @classmethod def setUpClass(cls): super(TestLdap, cls).setUpClass() logging.getLogger('ldap_test').setLevel(logging.ERROR) cls.mock_server_port = utils.get_free_port() cls.ldap_server = MockLdapServer() cls.ldap_server.start() @classmethod def tearDownClass(cls): super(TestLdap, cls).tearDownClass() cls.ldap_server.stop() def setUp(self): super(TestLdap, self).setUp() if 'ldap/' not in self.client.list_auth_backends(): self.client.sys.enable_auth_method( method_type='ldap', path=self.TEST_LDAP_PATH ) def tearDown(self): super(TestLdap, self).tearDown() self.client.disable_auth_backend( mount_point=self.TEST_LDAP_PATH, ) @parameterized.expand([ ('update url', dict(url=MockLdapServer.ldap_url)), ('update binddn', dict(url=MockLdapServer.ldap_url, bind_dn='cn=vault,ou=Users,dc=hvac,dc=network')), ('update upn_domain', dict(url=MockLdapServer.ldap_url, upn_domain='python-hvac.org')), ('update certificate', dict(url=MockLdapServer.ldap_url, certificate=utils.load_config_file('server-cert.pem'))), ('incorrect tls version', dict(url=MockLdapServer.ldap_url, tls_min_version='cats'), exceptions.InvalidRequest, "invalid 'tls_min_version'"), ]) def test_configure(self, test_label, parameters, raises=None, exception_message=''): parameters.update({ 'user_dn': MockLdapServer.ldap_users_dn, 'group_dn': MockLdapServer.ldap_groups_dn, 'mount_point': self.TEST_LDAP_PATH, }) if raises: with self.assertRaises(raises) as cm: self.client.auth.ldap.configure(**parameters) self.assertIn( member=exception_message, container=str(cm.exception), ) else: expected_status_code = 204 configure_response = self.client.auth.ldap.configure(**parameters) self.assertEqual( first=expected_status_code, second=configure_response.status_code ) read_config_response = self.client.auth.ldap.read_configuration( mount_point=self.TEST_LDAP_PATH, ) for parameter, argument in parameters.items(): if parameter == 'mount_point': continue self.assertIn( member=argument, container=read_config_response['data'].values(), ) def test_read_configuration(self): response = self.client.auth.ldap.read_configuration( mount_point=self.TEST_LDAP_PATH, ) self.assertIn( member='data', container=response, ) @parameterized.expand([ ('no policies', 'cats'), ('policies as list', 'cats', ['purr-policy']), ('policies as invalid type', 'cats', 'purr-policy', exceptions.ParamValidationError, '"policies" argument must be an instance of list'), ]) def test_create_or_update_group(self, test_label, name, policies=None, raises=None, exception_message=''): expected_status_code = 204 if raises: with self.assertRaises(raises) as cm: create_response = self.client.auth.ldap.create_or_update_group( name=name, policies=policies, mount_point=self.TEST_LDAP_PATH, ) if exception_message is not None: self.assertIn( member=exception_message, container=str(cm.exception), ) else: create_response = self.client.auth.ldap.create_or_update_group( name=name, policies=policies, mount_point=self.TEST_LDAP_PATH, ) self.assertEqual( first=expected_status_code, second=create_response.status_code ) @parameterized.expand([ ('read configured groups', 'cats'), ('non-existent groups', 'cats', False, exceptions.InvalidPath), ]) def test_list_groups(self, test_label, name, configure_first=True, raises=None, exception_message=None): if configure_first: self.client.auth.ldap.create_or_update_group( name=name, mount_point=self.TEST_LDAP_PATH, ) if raises: with self.assertRaises(raises) as cm: self.client.auth.ldap.list_groups( mount_point=self.TEST_LDAP_PATH, ) if exception_message is not None: self.assertIn( member=exception_message, container=str(cm.exception), ) else: list_groups_response = self.client.auth.ldap.list_groups( mount_point=self.TEST_LDAP_PATH, ) # raise Exception(list_groups_response) self.assertDictEqual( d1=dict(keys=[name]), d2=list_groups_response['data'], ) @parameterized.expand([ ('read configured group', 'cats'), ('non-existent group', 'cats', False, exceptions.InvalidPath), ]) def test_read_group(self, test_label, name, configure_first=True, raises=None, exception_message=None): if configure_first: self.client.auth.ldap.create_or_update_group( name=name, mount_point=self.TEST_LDAP_PATH, ) if raises: with self.assertRaises(raises) as cm: self.client.auth.ldap.read_group( name=name, mount_point=self.TEST_LDAP_PATH, ) if exception_message is not None: self.assertIn( member=exception_message, container=str(cm.exception), ) else: read_group_response = self.client.auth.ldap.read_group( name=name, mount_point=self.TEST_LDAP_PATH, ) self.assertIn( member='policies', container=read_group_response['data'], ) @parameterized.expand([ ('no policies or groups', 'cats'), ('policies as list', 'cats', ['purr-policy']), ('policies as invalid type', 'cats', 'purr-policy', None, exceptions.ParamValidationError, '"policies" argument must be an instance of list'), ('no groups', 'cats', ['purr-policy']), ('groups as list', 'cats', None, ['meow-group']), ('groups as invalid type', 'cats', None, 'meow-group', exceptions.ParamValidationError, '"groups" argument must be an instance of list'), ]) def test_create_or_update_user(self, test_label, username, policies=None, groups=None, raises=None, exception_message=''): expected_status_code = 204 if raises: with self.assertRaises(raises) as cm: self.client.auth.ldap.create_or_update_user( username=username, policies=policies, groups=groups, mount_point=self.TEST_LDAP_PATH, ) if exception_message is not None: self.assertIn( member=exception_message, container=str(cm.exception), ) else: create_response = self.client.auth.ldap.create_or_update_user( username=username, policies=policies, groups=groups, mount_point=self.TEST_LDAP_PATH, ) self.assertEqual( first=expected_status_code, second=create_response.status_code ) @parameterized.expand([ ('read configured group', 'cats'), ('non-existent group', 'cats', False, exceptions.InvalidPath), ]) def test_delete_group(self, test_label, name, configure_first=True, raises=None, exception_message=None): if configure_first: self.client.auth.ldap.create_or_update_group( name=name, mount_point=self.TEST_LDAP_PATH, ) expected_status_code = 204 delete_group_response = self.client.auth.ldap.delete_group( name=name, mount_point=self.TEST_LDAP_PATH, ) self.assertEqual( first=expected_status_code, second=delete_group_response.status_code ) @parameterized.expand([ ('read configured user', 'cats'), ('non-existent user', 'cats', False, exceptions.InvalidPath), ]) def test_list_users(self, test_label, username, configure_first=True, raises=None, exception_message=None): if configure_first: self.client.auth.ldap.create_or_update_user( username=username, mount_point=self.TEST_LDAP_PATH, ) if raises: with self.assertRaises(raises) as cm: self.client.auth.ldap.list_users( mount_point=self.TEST_LDAP_PATH, ) if exception_message is not None: self.assertIn( member=exception_message, container=str(cm.exception), ) else: list_users_response = self.client.auth.ldap.list_users( mount_point=self.TEST_LDAP_PATH, ) self.assertDictEqual( d1=dict(keys=[username]), d2=list_users_response['data'], ) @parameterized.expand([ ('read configured user', 'cats'), ('non-existent user', 'cats', False, exceptions.InvalidPath), ]) def test_read_user(self, test_label, username, configure_first=True, raises=None, exception_message=None): if configure_first: self.client.auth.ldap.create_or_update_user( username=username, mount_point=self.TEST_LDAP_PATH, ) if raises: with self.assertRaises(raises) as cm: self.client.auth.ldap.read_user( username=username, mount_point=self.TEST_LDAP_PATH, ) if exception_message is not None: self.assertIn( member=exception_message, container=str(cm.exception), ) else: read_user_response = self.client.auth.ldap.read_user( username=username, mount_point=self.TEST_LDAP_PATH, ) self.assertIn( member='policies', container=read_user_response['data'], ) @parameterized.expand([ ('read configured user', 'cats'), ('non-existent user', 'cats', False, exceptions.InvalidPath), ]) def test_delete_user(self, test_label, username, configure_first=True, raises=None, exception_message=None): if configure_first: self.client.auth.ldap.create_or_update_user( username=username, mount_point=self.TEST_LDAP_PATH, ) expected_status_code = 204 delete_user_response = self.client.auth.ldap.delete_user( username=username, mount_point=self.TEST_LDAP_PATH, ) self.assertEqual( first=expected_status_code, second=delete_user_response.status_code ) @parameterized.expand([ param( label='working creds with policy' ), param( label='invalid creds', username='not_your_dude_pal', password='<PASSWORD>', attach_policy=False, raises=exceptions.InvalidRequest, ), # The following two test cases cover either side of the associated changelog entry for LDAP auth here: # https://github.com/hashicorp/vault/blob/master/CHANGELOG.md#0103-june-20th-2018 param( label='working creds no membership with Vault version >= 0.10.3', attach_policy=False, skip_due_to_vault_version=utils.vault_version_lt('0.10.3'), ), param( label='working creds no membership with Vault version < 0.10.3', attach_policy=False, raises=exceptions.InvalidRequest, exception_message='user is not a member of any authorized group', skip_due_to_vault_version=utils.vault_version_ge('0.10.3'), ), ]) def test_login(self, label, username=None, password=<PASSWORD>, attach_policy=True, raises=None, exception_message='', skip_due_to_vault_version=False): if skip_due_to_vault_version: self.skipTest(reason='test case does not apply to Vault version under test') if username is None: username = self.ldap_server.ldap_user_name if password is None: password = self.ldap_server.ldap_user_password test_policy_name = 'test-ldap-policy' self.client.auth.ldap.configure( url=self.ldap_server.url, bind_dn=self.ldap_server.ldap_bind_dn, bind_pass=<PASSWORD>, user_dn=self.ldap_server.ldap_users_dn, user_attr='uid', group_dn=self.ldap_server.ldap_groups_dn, group_attr='cn', insecure_tls=True, mount_point=self.TEST_LDAP_PATH, ) if attach_policy: self.prep_policy(test_policy_name) self.client.auth.ldap.create_or_update_group( name=self.ldap_server.ldap_group_name, policies=[test_policy_name], mount_point=self.TEST_LDAP_PATH, ) if raises: with self.assertRaises(raises) as cm: self.client.auth.ldap.login( username=username, password=password, mount_point=self.TEST_LDAP_PATH, ) if exception_message is not None: self.assertIn( member=exception_message, container=str(cm.exception), ) else: login_response = self.client.auth.ldap.login( username=username, password=password, mount_point=self.TEST_LDAP_PATH, ) self.assertDictEqual( d1=dict(username=username), d2=login_response['auth']['metadata'], ) self.assertEqual( first=login_response['auth']['client_token'], second=self.client.token, ) if attach_policy: expected_policies = ['default', test_policy_name] else: expected_policies = ['default'] self.assertEqual( first=expected_policies, second=login_response['auth']['policies'] )
StarcoderdataPython
91623
<reponame>yishantao/DailyPractice<gh_stars>0 # -*- coding:utf-8 -*- """This module is used for cross validation""" from xgboost import XGBClassifier # 加载LibSVM格式数据模块 from sklearn.datasets import load_svmlight_file # from sklearn.model_selection import KFold from sklearn.model_selection import StratifiedKFold # 对给定参数的单个模型评估 from sklearn.model_selection import cross_val_score # read in data my_workpath = './data/' x_train, y_train = load_svmlight_file(my_workpath + 'agaricus.txt.train') x_test, y_test = load_svmlight_file(my_workpath + 'agaricus.txt.test') # print(x_train.shape) # 设置boosting迭代计算次数 num_round = 2 bst = XGBClassifier(max_depth=2, learning_rate=0.1, n_estimators=num_round, silent=True, objective='binary:logistic') # 交叉验证,速度比较慢 # stratified k-fold cross validation evaluation of xgboost model # kfold = KFold(n_splits=10, random_state=7) kfold = StratifiedKFold(n_splits=10, random_state=7) results = cross_val_score(bst, x_train, y_train, cv=kfold) print(results) print('CV Accuracy: %.2f%% (%.2f%%)' % (results.mean() * 100, results.std() * 100))
StarcoderdataPython
36393
<gh_stars>0 def none_check(value): if value is None: return False else: return True def is_empty(any_type_value): if any_type_value: return False else: return True
StarcoderdataPython
170468
<gh_stars>0 from django.test import TestCase from .models import Bucketlist from rest_framework.test import APIClient from rest_framework import status from django.core.urlresolvers import reverse class ModelTestCase(TestCase): """This class defines the test suite for the bucketlist model.""" def setUp(self): """Define the test client and other test variables.""" self.bucketlist_name = "Write world class code" self.bucketlist = Bucketlist(name=self.bucketlist_name) def test_model_can_create_a_bucketlist(self): """Test the bucketlist model can create a bucketlist.""" old_count = Bucketlist.objects.count() self.bucketlist.save() new_count = Bucketlist.objects.count() self.assertNotEqual(old_count, new_count) class ViewTestCase(TestCase): """Test suite for the api views""" def setUp(self): """Define the test client and other test variables.""" self.client = APIClient() self.bucketlist_data = {'name': 'Go to Ibiza'} self.response = self.client.post( reverse('create'), self.bucketlist_data, format='json') def test_api_can_create_a_bucketlist(self): """Test the api has bucket creation capability.""" self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)
StarcoderdataPython
1673231
<gh_stars>0 import math import tor4 from ...tensor import Tensor from .. import functional as F from .. import init from ..parameter import Parameter from .module import Module class Linear(Module): def __init__(self, in_features: int, out_features: int, bias: bool = True) -> None: self.in_features = in_features super().__init__() self.out_features = out_features self.weight = Parameter(tor4.empty(out_features, in_features)) if bias: self.bias = Parameter(tor4.zeros(out_features)) self.reset_parameters() def reset_parameters(self) -> None: init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if hasattr(self, "bias"): fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) init.uniform_(self.bias, -bound, bound) def extra_repr(self) -> str: return f'in_features={self.in_features}, out_features={self.out_features}, bias={hasattr(self, "bias")}' def forward(self, x: Tensor) -> Tensor: return F.linear(x, self.weight, self.bias if hasattr(self, "bias") else None)
StarcoderdataPython
101488
<reponame>pytexas/PyTexas import csv import random from django.conf import settings from django.core.management.base import BaseCommand, CommandError from conference.event.models import Conference, PrizeWinner import requests class Command(BaseCommand): help = 'Pick A Random Prize Winner' def add_arguments(self, parser): # parser.add_argument('acct_slug', type=str) # parser.add_argument('event_slug', type=str) parser.add_argument('conf_slug', type=str) # parser.add_argument('csv', type=str) parser.add_argument( '--clear', action='store_true', dest='clear', help='clear winners', ) def get_tickets_api(self, options): tickets = [] emails = {} params = {} while 1: print('Getting page', params.get('page', 1)) response = requests.get( 'https://api.tito.io/v3/pytexas/pytexas-2019/tickets', params=params, headers={ 'Authorization': 'Token token={}'.format(settings.TITO_TOKEN), 'Accept': 'application/json', }) data = response.json() for t in data['tickets']: if t['name'] and t['email'] and t['email'] not in emails: tickets.append(t) emails[t['email']] = True if data['meta']['next_page'] and data['meta']['next_page'] != data[ 'meta']['current_page']: params = {'page': data['meta']['next_page']} else: break return tickets def get_tickets(self, options): tickets = [] emails = {} with open(options['csv'], 'r') as csvfile: reader = csv.DictReader(csvfile) for row in reader: if row['Ticket Email'] not in emails: tickets.append(row) emails[row['Ticket Email']] = True return tickets def handle(self, *args, **options): conf = Conference.objects.get(slug=options['conf_slug']) if options['clear']: PrizeWinner.objects.filter(conference=conf).delete() print('Cleared winners for {}'.format(conf)) return tickets = self.get_tickets_api(options) random.shuffle(tickets) print('Total Tickets:', len(tickets)) i = 0 print('Ready') while 1: ans = input('\n>>> ') if 'q' in ans.lower(): break while 1: picked = tickets[i] i += 1 if not picked['email']: continue qs = PrizeWinner.objects.filter( conference=conf, ticket_id=picked['slug']) if qs.count() == 0: pw = PrizeWinner( name=picked['name'], email=picked['email'], ticket_id=picked['slug'], conference=conf) pw.save() print('Winner 🎉🐍 {} 🐍🎉'.format(picked['name'])) break
StarcoderdataPython
28037
""" Spacer components to add horizontal or vertical space to a layout. """ import param from bokeh.models import Div as BkDiv, Spacer as BkSpacer from ..reactive import Reactive class Spacer(Reactive): """ The `Spacer` layout is a very versatile component which makes it easy to put fixed or responsive spacing between objects. Like all other components spacers support both absolute and responsive sizing modes. Reference: https://panel.holoviz.org/user_guide/Customization.html#spacers :Example: >>> pn.Row( ... 1, pn.Spacer(width=200), ... 2, pn.Spacer(width=100), ... 3 ... ) """ _bokeh_model = BkSpacer def _get_model(self, doc, root=None, parent=None, comm=None): properties = self._process_param_change(self._init_params()) model = self._bokeh_model(**properties) if root is None: root = model self._models[root.ref['id']] = (model, parent) return model class VSpacer(Spacer): """ The `VSpacer` layout provides responsive vertical spacing. Using this component we can space objects equidistantly in a layout and allow the empty space to shrink when the browser is resized. Reference: https://panel.holoviz.org/user_guide/Customization.html#spacers :Example: >>> pn.Column( ... pn.layout.VSpacer(), 'Item 1', ... pn.layout.VSpacer(), 'Item 2', ... pn.layout.VSpacer() ... ) """ sizing_mode = param.Parameter(default='stretch_height', readonly=True) class HSpacer(Spacer): """ The `HSpacer` layout provides responsive vertical spacing. Using this component we can space objects equidistantly in a layout and allow the empty space to shrink when the browser is resized. Reference: https://panel.holoviz.org/user_guide/Customization.html#spacers :Example: >>> pn.Row( ... pn.layout.HSpacer(), 'Item 1', ... pn.layout.HSpacer(), 'Item 2', ... pn.layout.HSpacer() ... ) """ sizing_mode = param.Parameter(default='stretch_width', readonly=True) class Divider(Reactive): """ A `Divider` draws a horizontal rule (a `<hr>` tag in HTML) to separate multiple components in a layout. It automatically spans the full width of the container. Reference: https://panel.holoviz.org/reference/layouts/Divider.html :Example: >>> pn.Column( ... '# Lorem Ipsum', ... pn.layout.Divider(), ... 'A very long text... ' >>> ) """ width_policy = param.ObjectSelector(default="fit", readonly=True) _bokeh_model = BkDiv def _get_model(self, doc, root=None, parent=None, comm=None): properties = self._process_param_change(self._init_params()) properties['style'] = {'width': '100%', 'height': '100%'} model = self._bokeh_model(text='<hr style="margin: 0px">', **properties) if root is None: root = model self._models[root.ref['id']] = (model, parent) return model
StarcoderdataPython
3259581
<gh_stars>0 from db import DB import nltk import random import classifiers import dill, os.path def getClassifier(all=True): if os.path.isfile("classifier.pkl"): with open("classifier.pkl", 'rb') as file: classifier = dill.load(file) classifier.show_most_informative_features(15) file.close() return classifier conn = DB() data = conn.getTrainingData() random.shuffle(data) feature_sets = [(classifiers.getFeatures(d), "yes" if d["is_valid"] else "no") for d in data] if all: train_set, test_set = feature_sets, feature_sets else: train_set, test_set = feature_sets[:1500], feature_sets[1500:] classifier = nltk.NaiveBayesClassifier.train(train_set) classifier.show_most_informative_features(10) conn.close() print(nltk.classify.accuracy(classifier, test_set)) with open("classifier.pkl", 'wb') as file: dill.dump(classifier, file) file.close() return classifier if __name__ == "__main__": classifier = getClassifier() conn = DB() #conn.create() data = conn.getTrainingData() for row in data: features = classifiers.getFeatures(row) is_valid = classifier.classify(features) == "yes" if row["is_valid"] != is_valid: print("{}->{} {} {}".format(row["is_valid"], is_valid, row["id"], row["title"])) conn.close()
StarcoderdataPython
3284292
<gh_stars>1-10 import logging logger = logging.getLogger('root') ''' def read(conn, cursor, sql): try: cursor.execute(sql) rows = cursor.fetchall() for row in rows: print("ADMISSION =", row[0]) print("NAME =", row[1]) print("AGE =", row[2]) print("COURSE =", row[3]) print("DEPARTMENT =", row[4], "\n") logger.debug("Operation done successfully") return true except: logger.error("Read failed") return false '''
StarcoderdataPython