Returns InlineModelAdmin for attached images.
        'lang' is the language for GearsUploader (can be 'en' and 'ru' at the
        moment). 'max_width' is default resize width parameter to be set in
        widget.
433663
def attachedimages_inline_factory(lang='en', max_width='', debug=False):
    '''  
    '''

    class _AttachedImagesInline(GenericTabularInline):
        model = AttachedImage
        form = attachedimage_form_factory(lang, debug)
        template = 'generic_images/attached_images_inline.html'
        max_w = max_width

    return _AttachedImagesInline
459923
def get_size(data, default_width=0, default_height=0):
    

    height = default_height
    width = default_width
    filetype = None

    # Original version:
    # https://github.com/shibukawa/imagesize_py
    #
    # The MIT License (MIT)
    #
    # Copyright © 2016 Yoshiki Shibukawa
    #
    # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
    #
    # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    #
    # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

    size = len(data)
    # handle GIFs
    if size >= 10 and data[:6] in (b'GIF87a', b'GIF89a'):
        # Check to see if content_type is correct
        try:
            width, height = struct.unpack("<hh", data[6:10])
            filetype = "gif"
        except struct.error:
            raise ValueError("Invalid GIF file")
    # see png edition spec bytes are below chunk length then and finally the
    elif size >= 24 and data.startswith(b'\211PNG\r\n\032\n') and data[12:16] == b'IHDR':
        try:
            width, height = struct.unpack(">LL", data[16:24])
            filetype = "png"
        except struct.error:
            raise ValueError("Invalid PNG file")
    # Maybe this is for an older PNG version.
    elif size >= 16 and data.startswith(b'\211PNG\r\n\032\n'):
        # Check to see if we have the right content type
        try:
            width, height = struct.unpack(">LL", data[8:16])
            filetype = "png"
        except struct.error:
            raise ValueError("Invalid PNG file")
    # handle JPEGs
    elif size >= 2 and data.startswith(b'\377\330'):
        try:
            # Not very efficient to copy data to a buffer
            fhandle = io.BytesIO(data)
            size = 2
            ftype = 0
            while not 0xc0 <= ftype <= 0xcf:
                fhandle.seek(size, 1)
                byte = fhandle.read(1)
                while ord(byte) == 0xff:
                    byte = fhandle.read(1)
                ftype = ord(byte)
                size = struct.unpack('>H', fhandle.read(2))[0] - 2
            # We are at a SOFn block
            fhandle.seek(1, 1)  # Skip `precision' byte.
            height, width = struct.unpack('>HH', fhandle.read(4))
            filetype = "jpg"
        except struct.error:
            raise ValueError("Invalid JPEG file")
    # End of https://github.com/shibukawa/imagesize_py

    # handle SVG
    elif size >= 10 and data.startswith(b'<?xml'):
        filetype = "svg"
        fhandle = io.BytesIO(data)
        tree = ElementTree()
        try:
            tree.parse(fhandle)
        except ParseError:
            raise ValueError("Invalid SVG file")

        root = tree.getroot()

        try:
            width = _svg_convert_size(root.attrib.get("width", "0"))
            height = _svg_convert_size(root.attrib.get("height", "0"))
        except IndexError:
            raise ValueError("Invalid SVG file")

    return width, height, filetype
531532
function get_margin_width() {
    //ignore image width, use same width as on predefined bullet List_Bullet_Frame_Decorator
    //for proper alignment of bullet image and text. Allow image to not fitting on left border.
    //This controls the extra indentation of text to make room for the bullet image.
    //Here use actual image size, not predefined bullet size 
    //return $this->_frame->get_style()->get_font_size()*List_Bullet_Frame_Decorator::BULLET_SIZE + 
    //  2 * List_Bullet_Frame_Decorator::BULLET_PADDING;

    // Small hack to prevent indenting of list text
    // Image Might not exist, then position like on list_bullet_frame_decorator fallback to none. 
    if ( $this->_frame->get_style()->list_style_position === "outside" ||
         $this->_width == 0) 
      return 0;
    //This aligns the "inside" image position with the text.
    //The text starts to the right of the image.
    //Between the image and the text there is an added margin of image width.
    //Where this comes from is unknown.
    //The corresponding List_Bullet_Frame_Decorator sets a smaller margin. bullet size?
    return $this->_width + 2 * List_Bullet_Frame_Decorator::BULLET_PADDING;
  }
56081
def reorder_translation_formset_by_language_code(inline_admin_form):
    
    lang_to_form = dict([(form.form.initial['language_id'], form)
                         for form in inline_admin_form])
    return [lang_to_form[language_code] for language_code in
        get_language_code_list()]
1026530
def default_asset_manager(self):
        
        cache_path = None
        cache_directory = self.config['CACHE_DIRECTORY']
        if cache_directory:
            cache_directory = cache_directory.format(version=__version__)
            cache_path = os.path.join(self.instance_path, cache_directory)
        return GitHubAssetManager(
            cache_path, self.config['STYLE_URLS'], self.quiet)
485673
def get_feincms_inlines(self, model, request):
        
        model._needs_content_types()

        inlines = []
        for content_type in model._feincms_content_types:
            if not self.can_add_content(request, content_type):
                continue

            attrs = {
                '__module__': model.__module__,
                'model': content_type,
            }

            if hasattr(content_type, 'feincms_item_editor_inline'):
                inline = content_type.feincms_item_editor_inline
                attrs['form'] = inline.form

                #if hasattr(content_type, 'feincms_item_editor_form'):
                #    warnings.warn(
                #        'feincms_item_editor_form on %s is ignored because '
                #        'feincms_item_editor_inline is set too' % content_type,
                #        RuntimeWarning)

            else:
                inline = FeinCMSInline
                attrs['form'] = getattr(
                    content_type, 'feincms_item_editor_form', inline.form)

            name = '%sFeinCMSInline' % content_type.__name__
            # TODO: We generate a new class every time. Is that really wanted?
            inline_class = type(str(name), (inline,), attrs)
            inlines.append(inline_class)
        return inlines
154415
def language_support(f, attribute, options)
      return if Fae.languages.blank?

      attribute_array = attribute.to_s.split('_')
      language_suffix = attribute_array.pop
      return unless Fae.languages.has_key?(language_suffix.to_sym) || Fae.languages.has_key?(language_suffix)

      label = attribute_array.push("(#{language_suffix})").join(' ').titleize
      options[:label] = label unless options[:label].present?

      if options[:wrapper_html].present?
        options[:wrapper_html].deep_merge!({ data: { language: language_suffix } })
      else
        options[:wrapper_html] = { data: { language: language_suffix } }
      end
    end
353667
@Override protected void resizeDynamicText() {
        double maxWidth = unitText.isVisible() ? width - size * 0.275 : width - size * 0.1;
        double fontSize = 0.24 * size;
        valueText.setFont(Fonts.latoRegular(fontSize));
        if (valueText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(valueText, maxWidth, fontSize); }

        maxWidth = width - size * 0.55;
        fontSize = size * 0.18;
        deviationText.setFont(Fonts.latoRegular(fontSize));
        if (deviationText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(deviationText, maxWidth, fontSize); }

        maxWidth = width - size * 0.9;
        fontSize = size * 0.12;
        deviationUnitText.setFont(Fonts.latoRegular(fontSize));
        if (deviationUnitText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(deviationUnitText, maxWidth, fontSize); }
    }
403646
function normalizeConfig(config, locale) {
  // Set current locale of i18n context.
  if (config.i18n && (config.i18n.locales instanceof Array)) {
    config.metadata.global.$locale = locale || config.i18n.locales[0];
    config.metadata.global.$locales = config.i18n.locales;
    config.metadata.global.$route = function(s) { return helpers.getNormalizedPath(helpers.getLocalizedPath(s, locale, config.i18n.locales)); };
  }
  else {
    config.metadata.global.$route = function(s) { return helpers.getNormalizedPath(s); };
  }

  // Set defaults for metalsmith-layouts.
  if (!_.get(config, `layouts.directory`)) _.set(config, `layouts.directory`, path.join(config.src, `layouts`));
  _.merge(config.layouts, _.get(config, _.get(config, `layouts.engine`)));

  // Set defaults for metalsmith-in-place.
  _.merge(config.inPlace, _.get(config, _.get(config, `inPlace.engine`)));

  // Set defaults for metalsmith-permalinks.
  config.permalinks = { relative: false, linksets: [] };

  // Set defaults for metalsmith-pagination.
  config.pagination = {};

  // Set defaults for metalsmith-tags.
  if (config.tags) {
    if ((typeof config.tags.layout === `string`) && _.isEmpty(path.extname(config.tags.layout)))
      config.tags.layout = `${config.tags.layout}.${config.layouts.engine}`;

    if (typeof config.tags.path === `string` && _.isEmpty(path.extname(config.tags.path))) {
      if (!_.endsWith(config.tags.path, `/`)) config.tags.path = `${config.tags.path}/`;
      config.tags.path = `${config.tags.path}index.html`;
    }

    if (typeof config.tags.skipMetadata !== `boolean`) config.tags.skipMetadata = true;
  }

  // Set defaults for metalsmith-collections.
  if (config.collections) {
    for (let collectionName in config.collections) {
      const data = _.get(config.collections, collectionName);
      let pattern = _.get(data, `pattern`);
      let permalink = _.get(data, `permalink`) || path.join(collectionName, `:slug`);
      let date = _.get(data, `date`);
      let paginate = _.get(data, `paginate`);

      if (typeof data.layout !== `string`) data.layout = collectionName;

      if (_.isEmpty(path.extname(data.layout))) {
        data.layout = `${data.layout}.${config.layouts.engine}`;
      }

      if (data.metadata && (typeof data.metadata.layout === `string`) && _.isEmpty(path.extname(data.metadata.layout))) {
        data.metadata.layout = `${data.metadata.layout}.${config.layouts.engine}`;
      }

      if (paginate) {
        if ((typeof paginate.layout === `string`) && _.isEmpty(path.extname(paginate.layout)))
          paginate.layout = `${paginate.layout}.${config.layouts.engine}`;

        if (typeof paginate.path === `string` && _.isEmpty(path.extname(paginate.path))) {
          if (!_.endsWith(paginate.path, `/`)) paginate.path = `${paginate.path}/`;
          paginate.path = `${paginate.path}index.html`;
        }

        if (typeof paginate.first === `string` && _.isEmpty(path.extname(paginate.first))) {
          if (!_.endsWith(paginate.first, `/`)) paginate.first = `${paginate.first}/`;
          paginate.first = `${paginate.first}index.html`;
          paginate.noPageOne = true;
        }

        config.pagination[`collections.${collectionName}`] = paginate;
      }

      if (pattern) {
        config.metadata.collections[collectionName] = {
          pattern: pattern,
          metadata: _.merge(data.metadata || {}, {
            layout: data.layout
          })
        };
      }

      if (permalink) {
        if (_.startsWith(permalink, `/`)) permalink = permalink.substr(1);
        config.permalinks.linksets.push({
          match: { collection: collectionName },
          pattern: locale ? `${locale}/${permalink}` : permalink,
          date: date
        });
      }
    }
  }

  return config;
}
1069678
def ConvCnstrMODMaskOptionsDefaults(method='fista'):
    

    dflt = copy.deepcopy(ccmodmsk_class_label_lookup(method).Options.defaults)
    if method == 'fista':
        dflt.update({'MaxMainIter': 1, 'BackTrack':
                     {'gamma_u': 1.2, 'MaxIter': 50}})
    else:
        dflt.update({'MaxMainIter': 1, 'AutoRho':
                     {'Period': 10, 'AutoScaling': False,
                      'RsdlRatio': 10.0, 'Scaling': 2.0,
                      'RsdlTarget': 1.0}})
    return dflt
1290349
private function maxUploadFilesize(): string
    {
        $bytes = UploadedFile::getMaxFilesize();
        $kb    = intdiv($bytes + 1023, 1024);

        return I18N::translate('%s KB', I18N::number($kb));
    }
425483
def load_model():
    
    logging.info("Load language model...")
    ngram_arpa_t = pkg_resources.resource_filename('hwrt',
                                                   'misc/ngram.arpa.tar.bz2')
    with tarfile.open(ngram_arpa_t, 'r:bz2') as tar:
        tarfolder = tempfile.mkdtemp()
        tar.extractall(path=tarfolder)
    ngram_arpa_f = os.path.join(tarfolder, 'ngram.arpa')
    with open(ngram_arpa_f) as f:
        content = f.read()
    ngram_model = NgramLanguageModel()
    ngram_model.load_from_arpa_str(content)
    return ngram_model
1221283
def imagenet_preprocess_example(example, mode, resize_size=None,
                                normalize=True):
  """"""
  resize_size = resize_size or [299, 299]
  assert resize_size[0] == resize_size[1]

  image = example["inputs"]
  if mode == tf.estimator.ModeKeys.TRAIN:
    image = preprocess_for_train(image, image_size=resize_size[0],
                                 normalize=normalize)
  else:
    image = preprocess_for_eval(image, image_size=resize_size[0],
                                normalize=normalize)

  example["inputs"] = image
  return example
147296
def width_max(self, width_max):
        
        if width_max is None:
            self._width_limits[1] = None
            return

        width_max = float(width_max)
        assert(self.width_min <= width_max)

        self._width_limits[1] = width_max
        self._update_layout()
414738
def get_model(model, ctx, opt):
    """"""
    kwargs = {'ctx': ctx, 'pretrained': opt.use_pretrained, 'classes': classes}
    if model.startswith('resnet'):
        kwargs['thumbnail'] = opt.use_thumbnail
    elif model.startswith('vgg'):
        kwargs['batch_norm'] = opt.batch_norm

    net = models.get_model(model, **kwargs)
    if opt.resume:
        net.load_parameters(opt.resume)
    elif not opt.use_pretrained:
        if model in ['alexnet']:
            net.initialize(mx.init.Normal())
        else:
            net.initialize(mx.init.Xavier(magnitude=2))
    net.cast(opt.dtype)
    return net
1229996
public com.google.appengine.v1.ManualScalingOrBuilder getManualScalingOrBuilder() {
    if (scalingCase_ == 5) {
       return (com.google.appengine.v1.ManualScaling) scaling_;
    }
    return com.google.appengine.v1.ManualScaling.getDefaultInstance();
  }
1047779
public function enqueueAdmin()
    {
        if (!$this->isModularityPage()) {
            return;
        }

        // Style
        wp_register_style('modularity', MODULARITY_URL . '/dist/css/modularity.' . self::$assetSuffix . '.css', false, filemtime(MODULARITY_PATH . '/dist/css/modularity.' . self::$assetSuffix . '.css'));
        wp_enqueue_style('modularity');

        // Scripts
        wp_register_script('modularity', MODULARITY_URL . '/dist/js/modularity.' . self::$assetSuffix . '.js', false, filemtime(MODULARITY_PATH . '/dist/js/modularity.' . self::$assetSuffix . '.js'), true);
        wp_localize_script('modularity', 'modularityAdminLanguage', array(
            'langedit' => __('Edit', 'modularity'),
            'langimport' => __('Import', 'modularity'),
            'langremove' => __('Remove', 'modularity'),
            'langhide' => __('Hide module', 'modularity'),
            'actionRemove' => __('Are you sure you want to remove this module?', 'modularity'),
            'isSaving' => __('Saving…', 'modularity'),
            'close' => __('Close', 'modularity'),
            'width' => __('Width', 'modularity'),
            'widthOptions' => $this->editor->getWidthOptions(),
            'deprecated' => __('Deprecated', 'modularity')
        ));
        wp_enqueue_script('modularity');

        add_action('admin_head', function () {
            echo "
                <script>
                    var admin_url = '" . admin_url() . "';
                </script>
            ";
        });

        // If editor
        if (\Modularity\Helper\Wp::isEditor()) {
            wp_enqueue_script('jquery-ui-sortable');
            wp_enqueue_script('jquery-ui-draggable');
            wp_enqueue_script('jquery-ui-droppable');

            add_action('admin_head', function () {
                global $post;
                global $archive;

                if (isset($_GET['id']) && is_numeric($_GET['id']) && get_post_status($_GET['id'])) {
                    $id = $_GET['id'];
                } else {
                    $id = isset($post->ID) ? $post->ID : "'" . $archive . "'";
                }

                echo "
                    <script>
                        var modularity_post_id = " . $id . "
                    </script>
                ";
            }, 10);
        }
    }