Download, convert and save a caffe model
557208
def convert_caffe_model(model_name, meta_info, dst_dir='./model'):
    """"""

    (prototxt, caffemodel, mean) = download_caffe_model(model_name, meta_info, dst_dir)
    model_name = os.path.join(dst_dir, model_name)
    convert_model(prototxt, caffemodel, model_name)
    if isinstance(mean, str):
        mx_mean = model_name + '-mean.nd'
        convert_mean(mean, mx_mean)
        mean = mx_mean
    return (model_name, mean)
402497
def download_dataset(tournament, unzip):
    """"""
    click.echo(napi.download_current_dataset(tournament=tournament, unzip=unzip))
921015
def main():
    """"""

    parser = argparse.ArgumentParser(
        description='Tool for testing caffe to mxnet conversion layer by layer')
    parser.add_argument('--image_url', type=str,
                        default='https://github.com/dmlc/web-data/raw/master/mxnet/doc/'\
                                'tutorials/python/predict_image/cat.jpg',
                        help='input image to test inference, can be either file path or url')
    parser.add_argument('--caffe_prototxt_path', type=str,
                        default='./model.prototxt',
                        help='path to caffe prototxt')
    parser.add_argument('--caffe_model_path', type=str,
                        default='./model.caffemodel',
                        help='path to caffe weights')
    parser.add_argument('--caffe_mean', type=str,
                        default='./model_mean.binaryproto',
                        help='path to caffe mean file')
    parser.add_argument('--mean_diff_allowed', type=int, default=1e-03,
                        help='mean difference allowed between caffe blob and mxnet blob')
    parser.add_argument('--max_diff_allowed', type=int, default=1e-01,
                        help='max difference allowed between caffe blob and mxnet blob')
    parser.add_argument('--gpu', type=int, default=-1, help='the gpu id used for predict')
    args = parser.parse_args()
    convert_and_compare_caffe_to_mxnet(args.image_url, args.gpu, args.caffe_prototxt_path,
                                       args.caffe_model_path, args.caffe_mean,
                                       args.mean_diff_allowed, args.max_diff_allowed)
175528
function parseCoffeeDocs(file, fn) {
  fs.readFile(file, function(err, data) {
    if (err) {
      fn(err);
    }

    var js = coffee.compile(data.toString());
    var regex = /\/\**([\s\S]*?)\*\//gm;
    var fragments = js.match(regex);
    var docs = [];

    for (var i = 0; i < fragments.length; i++) {
      var fragment = fragments[i];
      var doc = doctrine.parse(fragment, {unwrap: true});

      docs.push(doc);

      if (i === fragments.length - 1) {
        fn(null, docs);
      }
    }
  });
}
144379
def simxLoadModel(clientID, modelPathAndName, options, operationMode):
    '''
    
    '''
    baseHandle = ct.c_int()
    if (sys.version_info[0] == 3) and (type(modelPathAndName) is str):
        modelPathAndName=modelPathAndName.encode('utf-8')
    return c_LoadModel(clientID, modelPathAndName, options, ct.byref(baseHandle), operationMode), baseHandle.value
355154
def parse_caffemodel(file_path):
    
    f = open(file_path, 'rb')
    contents = f.read()

    net_param = caffe_pb2.NetParameter()
    net_param.ParseFromString(contents)

    layers = find_layers(net_param)
    return layers
1237364
def train_and_save(self, model_filename, cannon_data_filename, 
        clobber=False, **kwargs):
        

        if any(map(os.path.exists,
            (model_filename, cannon_data_filename))) and not clobber:
            raise IOError("output file already exists")

        trained = self.train_global(**kwargs)
        with open(cannon_data_filename, "wb") as fp:
            pickle.dump(trained, fp, -1)

        self._configuration["model_grid"]["cannon_data"] = cannon_data_filename
        logger.info("Cannon coefficients pickled to {}".format(
            cannon_data_filename))

        self.save(model_filename, clobber)

        return True
1343048
def save(self, *args, **kwargs):
        """"""
        self.clean()

        if not self.slug:
            self.slug = slugify(self.name)

        super(SpecialCoverage, self).save(*args, **kwargs)

        if self.query and self.query != {}:
            # Always save and require client to filter active date range
            self._save_percolator()
368865
@Override
  public void saveModel(BackendModel m, String model_path) {
    ((DeepwaterCaffeModel) m).saveModel(model_path);
  }
776603
def save_model(self, request, obj, form, change):
        
        if 'config.menu_structure' in form.changed_data:
            from menus.menu_pool import menu_pool
            menu_pool.clear(all=True)
        return super(BlogConfigAdmin, self).save_model(request, obj, form, change)
844132
def cafferesnet101(num_classes=1000, pretrained='imagenet'):
    
    model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes)
    if pretrained is not None:
        settings = pretrained_settings['cafferesnet101'][pretrained]
        assert num_classes == settings['num_classes'], \
            "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes)
        model.load_state_dict(model_zoo.load_url(settings['url']))
        model.input_space = settings['input_space']
        model.input_size = settings['input_size']
        model.input_range = settings['input_range']
        model.mean = settings['mean']
        model.std = settings['std']
    return model
806707
def to_fp32(learn:Learner):
    ""
    learn.data.remove_tfm(batch_to_half)
    for cb in learn.callbacks: 
        if isinstance(cb, MixedPrecision): learn.callbacks.remove(cb)
    learn.model = learn.model.float()
    return learn
1245328
def save_session_to_file(self, sessionfile):
        """"""
        pickle.dump(requests.utils.dict_from_cookiejar(self._session.cookies), sessionfile)
371680
def _save_table(self, raw=False, cls=None, force_insert=None, force_update=None, using=None, update_fields=None):
        
        # Connection aliasing
        connection = connections[using]

        create = bool(force_insert or not self.dn)

        # Prepare fields
        if update_fields:
            target_fields = [
                self._meta.get_field(name)
                for name in update_fields
            ]
        else:
            target_fields = [
                field
                for field in cls._meta.get_fields(include_hidden=True)
                if field.concrete and not field.primary_key
            ]

        def get_field_value(field, instance):
            python_value = getattr(instance, field.attname)
            return field.get_db_prep_save(python_value, connection=connection)

        if create:
            old = None
        else:
            old = cls.objects.using(using).get(dn=self._saved_dn)
        changes = {
            field.db_column: (
                None if old is None else get_field_value(field, old),
                get_field_value(field, self),
            )
            for field in target_fields
        }

        # Actual saving

        old_dn = self.dn
        new_dn = self.build_dn()
        updated = False

        # Insertion
        if create:
            # FIXME(rbarrois): This should be handled through a hidden field.
            hidden_values = [
                ('objectClass', [obj_class.encode('utf-8') for obj_class in self.object_classes])
            ]
            new_values = hidden_values + [
                (colname, change[1])
                for colname, change in sorted(changes.items())
                if change[1] != []
            ]
            new_dn = self.build_dn()
            logger.debug("Creating new LDAP entry %s", new_dn)
            connection.add_s(new_dn, new_values)

        # Update
        else:
            modlist = []
            for colname, change in sorted(changes.items()):
                old_value, new_value = change
                if old_value == new_value:
                    continue
                modlist.append((
                    ldap.MOD_DELETE if new_value == [] else ldap.MOD_REPLACE,
                    colname,
                    new_value,
                ))

            if new_dn != old_dn:
                logger.debug("renaming ldap entry %s to %s", old_dn, new_dn)
                connection.rename_s(old_dn, self.build_rdn())

            if modlist:
                logger.debug("Modifying existing LDAP entry %s", new_dn)
                connection.modify_s(new_dn, modlist)
            updated = True

        self.dn = new_dn

        # Finishing
        self._saved_dn = self.dn
        return updated
909508
def get_model(app, model):
    """"""
    if 'get_model' not in _LAZY_LOADS:
        _lazy_load_get_model()

    _get_model = _LAZY_LOADS['get_model']
    return _get_model(app, model)
1003263
def export_model(model, model_type, export_dir, model_column_fn):
  
  wide_columns, deep_columns = model_column_fn()
  if model_type == 'wide':
    columns = wide_columns
  elif model_type == 'deep':
    columns = deep_columns
  else:
    columns = wide_columns + deep_columns
  feature_spec = tf.feature_column.make_parse_example_spec(columns)
  example_input_fn = (
      tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec))
  model.export_savedmodel(export_dir, example_input_fn,
                          strip_default_attrs=True)
137463
def save_model(model_folder: str, model_name: str, model: Model,
               compiler_options: Dict[str, str]) -> None:
    

    objects = {'dae_residual': None, 'initial_residual': None, 'variable_metadata': None, 'delay_arguments': None}
    for o in objects.keys():
        f = getattr(model, o + '_function')

        if compiler_options.get('codegen', False):
            objects[o] = _codegen_model(model_folder, f, '{}_{}'.format(model_name, o))
        else:
            objects[o] = f

    # Output metadata
    db_file = os.path.join(model_folder, model_name + ".pymoca_cache")
    with open(db_file, 'wb') as f:
        db = {}

        # Store version
        db['version'] = __version__

        # Include references to the shared libraries (codegen) or pickled functions (cache)
        db.update(objects)

        db['library_os'] = os.name

        db['options'] = compiler_options

        # Describe variables per category
        for key in ['states', 'der_states', 'alg_states', 'inputs', 'parameters', 'constants']:
            db[key] = [e.to_dict() for e in getattr(model, key)]


        # Caching using CasADi functions will lead to constants seemingly
        # depending on MX variables. Figuring out that they do not is slow,
        # especially when doing it on a lazy function call, as would be the
        # case when reading from cache. So instead, we do the depency check
        # once when saving the model.

        # Metadata dependency checking
        parameter_vector = ca.veccat(*[v.symbol for v in model.parameters])

        for k, key in enumerate(['states', 'alg_states', 'inputs', 'parameters', 'constants']):
            metadata_shape = (len(getattr(model, key)), len(CASADI_ATTRIBUTES))
            m = db[key + "__metadata_dependent"] = np.zeros(metadata_shape, dtype=bool)
            for i, v in enumerate(getattr(model, key)):
                for j, tmp in enumerate(CASADI_ATTRIBUTES):
                    attr = getattr(v, tmp)
                    if (isinstance(attr, ca.MX) and not attr.is_constant()
                        and ca.depends_on(attr, parameter_vector)):
                        m[i, j] = True

        # Delay dependency checking
        if model.delay_states:

            all_symbols = [model.time,
                           *model._symbols(model.states),
                           *model._symbols(model.der_states),
                           *model._symbols(model.alg_states),
                           *model._symbols(model.inputs),
                           *model._symbols(model.constants),
                           *model._symbols(model.parameters)]
            symbol_to_index = {x: i for i, x in enumerate(all_symbols)}

            expressions, durations = zip(*model.delay_arguments)

            duration_dependencies = []
            for dur in durations:
                duration_dependencies.append(
                    [symbol_to_index[var] for var in ca.symvar(dur) if ca.depends_on(dur, var)])
            db['__delay_duration_dependent'] = duration_dependencies

        db['outputs'] = model.outputs

        db['delay_states'] = model.delay_states

        db['alias_relation'] = model.alias_relation

        pickle.dump(db, f, protocol=-1)