text:
package io.fabric8.gateway.fabric.support.http;

import io.fabric8.common.util.Strings;
import io.fabric8.zookeeper.internal.SimplePathTemplate;
import io.fabric8.gateway.ServiceDetails;
import io.fabric8.gateway.handlers.http.HttpMappingRule;
import io.fabric8.gateway.handlers.http.MappedServices;
import io.fabric8.gateway.loadbalancer.LoadBalancer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * A set of HTTP mapping rules for applying add and remove service events to (typically from ZooKeeper but could be any discovery system).
 */
public class HttpMappingRuleBase implements HttpMappingRule {
    private static final transient Logger LOG = LoggerFactory.getLogger(HttpMappingRuleBase.class);

    private final SimplePathTemplate uriTemplate;
    /**
     * The version used if no "version" expression is used in the {@link #uriTemplate} and no
     * {@link #enabledVersion} is specified
     */
    private final String gatewayVersion;
    private final String enabledVersion;
    private final LoadBalancer loadBalancer;
    private final boolean reverseHeaders;

    private Map<String, MappedServices> mappingRules = new ConcurrentHashMap<String, MappedServices>();

    private Set<Runnable> changeListeners = new CopyOnWriteArraySet<Runnable>();

    public HttpMappingRuleBase(SimplePathTemplate uriTemplate, String gatewayVersion, String enabledVersion, LoadBalancer loadBalancer, boolean reverseHeaders) {
        this.uriTemplate = uriTemplate;
        this.gatewayVersion = gatewayVersion;
        this.enabledVersion = enabledVersion;
        this.loadBalancer = loadBalancer;
        this.reverseHeaders = reverseHeaders;
    }

    /**
     * Populates the parameters from the URL of the service so they can be reused in the URI template
     */
    public static void populateUrlParams(Map<String, String> params, String service) {
        try {
            URL url = new URL(service);
            params.put("contextPath", url.getPath());
            params.put("protocol", url.getProtocol());
            params.put("host", url.getHost());
            params.put("port", "" + url.getPort());

        } catch (MalformedURLException e) {
            LOG.warn("Invalid URL '" + service + "'. " + e);
        }
    }

    @Override
    public String toString() {
        return "HttpMappingRuleBase{" +
                "uriTemplate=" + uriTemplate +
                ", loadBalancer=" + loadBalancer +
                ", enabledVersion='" + enabledVersion + '\'' +
                ", reverseHeaders=" + reverseHeaders +
                ", gatewayVersion='" + gatewayVersion + '\'' +
                '}';
    }

    @Override
    public void appendMappedServices(Map<String, MappedServices> rules) {
        rules.putAll(mappingRules);
    }

    public String getGatewayVersion() {
        return gatewayVersion;
    }

    public SimplePathTemplate getUriTemplate() {
        return uriTemplate;
    }

    /**
     * Given a path being added or removed, update the services.
     *
     * @param remove        whether to remove (if true) or add (if false) this mapping
     * @param path          the path that this mapping is bound
     * @param services      the HTTP URLs of the services to map to
     * @param defaultParams the default parameters to use in the URI templates such as for version and container
     * @param serviceDetails
     */
    public void updateMappingRules(boolean remove, String path, List<String> services, Map<String, String> defaultParams, ServiceDetails serviceDetails) {
        SimplePathTemplate pathTemplate = getUriTemplate();
        if (pathTemplate != null) {
            boolean versionSpecificUri = pathTemplate.getParameterNames().contains("version");

            String versionId = defaultParams.get("version");
            if (!remove && Strings.isNotBlank(versionId) && !versionSpecificUri && gatewayVersion != null) {
                // lets ignore this mapping if the version does not match
                if (!gatewayVersion.equals(versionId)) {
                    remove = true;
                }
            }

            Map<String, String> params = new HashMap<String, String>();
            if (defaultParams != null) {
                params.putAll(defaultParams);
            }
            params.put("servicePath", path);

            for (String service : services) {
                populateUrlParams(params, service);
                String fullPath = pathTemplate.bindByNameNonStrict(params);
                if (remove) {
                    MappedServices rule = mappingRules.get(fullPath);
                    if (rule != null) {
                        List<String> serviceUrls = rule.getServiceUrls();
                        serviceUrls.remove(service);
                        if (serviceUrls.isEmpty()) {
                            mappingRules.remove(fullPath);
                        }
                    }
                } else {
                    MappedServices mappedServices = new MappedServices(service, serviceDetails, loadBalancer, reverseHeaders);
                    MappedServices oldRule = mappingRules.put(fullPath, mappedServices);
                    if (oldRule != null) {
                        mappedServices.getServiceUrls().addAll(oldRule.getServiceUrls());
                    }
                }
            }
        }
        fireMappingRulesChanged();
    }

    @Override
    public void addChangeListener(Runnable listener) {
        changeListeners.add(listener);
    }

    @Override
    public void removeChangeListener(Runnable listener) {
        changeListeners.remove(listener);
    }

    protected void fireMappingRulesChanged() {
        for (Runnable changeListener : changeListeners) {
            changeListener.run();
        }
    }

}


text:
package org.apache.hadoop.yarn.server.resourcemanager.reservation;

import org.apache.hadoop.yarn.api.records.ReservationRequest;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.util.resource.Resources;

import java.util.HashMap;
import java.util.Map;

final class ReservationSystemUtil {

  private ReservationSystemUtil() {
    // not called
  }

  public static Resource toResource(ReservationRequest request) {
    Resource resource = Resources.multiply(request.getCapability(),
        (float) request.getNumContainers());
    return resource;
  }

  public static Map<ReservationInterval, Resource> toResources(
      Map<ReservationInterval, ReservationRequest> allocations) {
    Map<ReservationInterval, Resource> resources =
        new HashMap<ReservationInterval, Resource>();
    for (Map.Entry<ReservationInterval, ReservationRequest> entry :
        allocations.entrySet()) {
      resources.put(entry.getKey(),
          toResource(entry.getValue()));
    }
    return resources;
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.rhythm.louie.service;

import java.util.Collection;

import com.rhythm.louie.jms.MessageHandler;

import com.rhythm.louie.request.RequestContext;
import com.rhythm.louie.request.data.Result;
import com.rhythm.louie.service.command.PBCommand;

/**
 *
 * @author chris
 */
public interface Service {
    static final String PK_CHECK_ERROR = "Invalid request Parameters!";

    Result executeCommand(RequestContext req) throws Exception;

    Collection<PBCommand> getCommands();

    String getServiceName();

    Class<?> getServiceInterface();

    void initialize() throws Exception;

    void shutdown() throws Exception;

    MessageHandler getMessageHandler();

    boolean isReserved();

}


text:
/*************************************************************************/
/*  audio_stream_ogg_vorbis.cpp                                          */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* 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.                */
/*************************************************************************/
#include "audio_stream_ogg_vorbis.h"

size_t AudioStreamPlaybackOGGVorbis::_ov_read_func(void *p_dst,size_t p_data, size_t p_count, void *_f) {

	//printf("read to %p, %i bytes, %i nmemb, %p\n",p_dst,p_data,p_count,_f);
	FileAccess *fa=(FileAccess*)_f;
	size_t read_total = p_data*p_count;

	if (fa->eof_reached())
		return 0;

	uint8_t *dst=(uint8_t*)p_dst;

	int read = fa->get_buffer(dst, read_total);

	return read;
}

int AudioStreamPlaybackOGGVorbis::_ov_seek_func(void *_f,ogg_int64_t offs, int whence) {

	//printf("seek to %p, offs %i, whence %i\n",_f,(int)offs,whence);

#ifdef SEEK_SET
	//printf("seek set defined\n");
	FileAccess *fa=(FileAccess*)_f;

	if (whence==SEEK_SET) {

		fa->seek(offs);
	} else if (whence==SEEK_CUR) {

		fa->seek(fa->get_pos()+offs);
	} else if (whence==SEEK_END) {

		fa->seek_end(offs);
	} else {

		ERR_PRINT("BUG, wtf was whence set to?\n");
	}
	int ret=fa->eof_reached()?-1:0;
	//printf("returning %i\n",ret);
	return ret;

#else
	return -1; // no seeking
#endif

}
int AudioStreamPlaybackOGGVorbis::_ov_close_func(void *_f) {

//	printf("close %p\n",_f);
	if (!_f)
		return 0;
	FileAccess *fa=(FileAccess*)_f;
	if (fa->is_open())
		fa->close();
	return 0;
}
long AudioStreamPlaybackOGGVorbis::_ov_tell_func(void *_f) {

	//printf("close %p\n",_f);

	FileAccess *fa=(FileAccess*)_f;
	return fa->get_pos();
}

int AudioStreamPlaybackOGGVorbis::mix(int16_t* p_bufer,int p_frames) {

	if (!playing)
		return 0;

	int total=p_frames;
	while (true) {

		int todo = p_frames;

		if (todo==0 || todo<MIN_MIX) {
			break;
		}

		//printf("to mix %i - mix me %i bytes\n",to_mix,to_mix*stream_channels*sizeof(int16_t));

		#ifdef BIG_ENDIAN_ENABLED
		long ret=ov_read(&vf,(char*)p_bufer,todo*stream_channels*sizeof(int16_t), 1, 2, 1, &current_section);
		#else
		long ret=ov_read(&vf,(char*)p_bufer,todo*stream_channels*sizeof(int16_t), 0, 2, 1, &current_section);
		#endif

		if (ret<0) {

			playing = false;
			ERR_EXPLAIN("Error reading OGG Vorbis File: "+file);
			ERR_BREAK(ret<0);
		} else if (ret==0) { // end of song, reload?

			ov_clear(&vf);

			_close_file();

			if (!has_loop()) {

				playing=false;
				repeats=1;
				break;
			}

			f=FileAccess::open(file,FileAccess::READ);

			int errv = ov_open_callbacks(f,&vf,NULL,0,_ov_callbacks);
			if (errv!=0) {
				playing=false;
				break;; // :(
			}

			if (loop_restart_time) {
				bool ok = ov_time_seek(&vf,loop_restart_time)==0;
				if (!ok) {
					playing=false;
					//ERR_EXPLAIN("loop restart time rejected");
					ERR_PRINT("loop restart time rejected")
				}

				frames_mixed=stream_srate*loop_restart_time;
			} else {

				frames_mixed=0;
			}
			repeats++;
			continue;

		}

		ret/=stream_channels;
		ret/=sizeof(int16_t);

		frames_mixed+=ret;

		p_bufer+=ret*stream_channels;
		p_frames-=ret;

	}

	return total-p_frames;

}

void AudioStreamPlaybackOGGVorbis::play(float p_from) {

	if (playing)
		stop();

	if (_load_stream()!=OK)
		return;

	frames_mixed=0;
	playing=true;
	if (p_from>0) {
		seek_pos(p_from);
	}
}

void AudioStreamPlaybackOGGVorbis::_close_file() {

	if (f) {

		memdelete(f);
		f=NULL;
	}
}

bool AudioStreamPlaybackOGGVorbis::is_playing() const {
	return playing;
}
void AudioStreamPlaybackOGGVorbis::stop() {

	_clear_stream();
	playing=false;
	//_clear();
}

float AudioStreamPlaybackOGGVorbis::get_pos() const {

	int32_t frames = int32_t(frames_mixed);
	if (frames < 0)
		frames=0;
	return double(frames) / stream_srate;
}

void AudioStreamPlaybackOGGVorbis::seek_pos(float p_time) {

	if (!playing)
		return;
	bool ok = ov_time_seek(&vf,p_time)==0;
	ERR_FAIL_COND(!ok);
	frames_mixed=stream_srate*p_time;
}

String AudioStreamPlaybackOGGVorbis::get_stream_name() const  {

	return "";
}

void AudioStreamPlaybackOGGVorbis::set_loop(bool p_enable) {

	loops=p_enable;
}

bool AudioStreamPlaybackOGGVorbis::has_loop() const {

	return loops;
}

int AudioStreamPlaybackOGGVorbis::get_loop_count() const {
	return repeats;
}

Error AudioStreamPlaybackOGGVorbis::set_file(const String& p_file) {

	file=p_file;
	stream_valid=false;
	Error err;
	f=FileAccess::open(file,FileAccess::READ,&err);

	if (err) {
		ERR_FAIL_COND_V( err, err );
	}

	int errv = ov_open_callbacks(f,&vf,NULL,0,_ov_callbacks);
	switch(errv) {

		case OV_EREAD: { // - A read from media returned an error.
			memdelete(f); f=NULL;
			ERR_FAIL_V( ERR_FILE_CANT_READ );
		} break;
		case OV_EVERSION:  // - Vorbis version mismatch.
		case OV_ENOTVORBIS: { // - Bitstream is not Vorbis data.
			memdelete(f); f=NULL;
			ERR_FAIL_V( ERR_FILE_UNRECOGNIZED );
		} break;
		case OV_EBADHEADER: { // - Invalid Vorbis bitstream header.
			memdelete(f); f=NULL;
			ERR_FAIL_V( ERR_FILE_CORRUPT );
		} break;
		case OV_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption.
			memdelete(f); f=NULL;
			ERR_FAIL_V( ERR_BUG );
		} break;
	}
	const vorbis_info *vinfo=ov_info(&vf,-1);
	stream_channels=vinfo->channels;
	stream_srate=vinfo->rate;
	ogg_int64_t len = ov_time_total(&vf,-1);
	length=len/1000.0;
	ov_clear(&vf);
	memdelete(f);
	f=NULL;
	stream_valid=true;

	return OK;
}

Error AudioStreamPlaybackOGGVorbis::_load_stream()  {

	ERR_FAIL_COND_V(!stream_valid,ERR_UNCONFIGURED);

	_clear_stream();
	if (file=="")
		return ERR_INVALID_DATA;

	Error err;
	f=FileAccess::open(file,FileAccess::READ,&err);
	if (err) {
		ERR_FAIL_COND_V( err, err );
	}

	int errv = ov_open_callbacks(f,&vf,NULL,0,_ov_callbacks);
	switch(errv) {

		case OV_EREAD: { // - A read from media returned an error.
			memdelete(f); f=NULL;
			ERR_FAIL_V( ERR_FILE_CANT_READ );
		} break;
		case OV_EVERSION:  // - Vorbis version mismatch.
		case OV_ENOTVORBIS: { // - Bitstream is not Vorbis data.
			memdelete(f); f=NULL;
			ERR_FAIL_V( ERR_FILE_UNRECOGNIZED );
		} break;
		case OV_EBADHEADER: { // - Invalid Vorbis bitstream header.
			memdelete(f); f=NULL;
			ERR_FAIL_V( ERR_FILE_CORRUPT );
		} break;
		case OV_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption.
			memdelete(f); f=NULL;
			ERR_FAIL_V( ERR_BUG );
		} break;
	}
	repeats=0;
	stream_loaded=true;

	return OK;
}

float AudioStreamPlaybackOGGVorbis::get_length() const {

	if (!stream_loaded) {
		if (const_cast<AudioStreamPlaybackOGGVorbis*>(this)->_load_stream()!=OK)
			return 0;
	}
	return length;
}

void AudioStreamPlaybackOGGVorbis::_clear_stream() {

	if (!stream_loaded)
		return;

	ov_clear(&vf);
	_close_file();

	stream_loaded=false;
	stream_channels=1;
	playing=false;
}

void AudioStreamPlaybackOGGVorbis::set_paused(bool p_paused) {

	paused=p_paused;
}

bool AudioStreamPlaybackOGGVorbis::is_paused(bool p_paused) const {

	return paused;
}

AudioStreamPlaybackOGGVorbis::AudioStreamPlaybackOGGVorbis() {

	loops=false;
	playing=false;
	_ov_callbacks.read_func=_ov_read_func;
	_ov_callbacks.seek_func=_ov_seek_func;
	_ov_callbacks.close_func=_ov_close_func;
	_ov_callbacks.tell_func=_ov_tell_func;
	f = NULL;
	stream_loaded=false;
	stream_valid=false;
	repeats=0;
	paused=true;
	stream_channels=0;
	stream_srate=0;
	current_section=0;
	length=0;
	loop_restart_time=0;
}

AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() {

	_clear_stream();

}

RES ResourceFormatLoaderAudioStreamOGGVorbis::load(const String &p_path, const String& p_original_path, Error *r_error) {
	if (r_error)
		*r_error=OK;

	AudioStreamOGGVorbis *ogg_stream = memnew(AudioStreamOGGVorbis);
	ogg_stream->set_file(p_path);
	return Ref<AudioStreamOGGVorbis>(ogg_stream);
}

void ResourceFormatLoaderAudioStreamOGGVorbis::get_recognized_extensions(List<String> *p_extensions) const {

	p_extensions->push_back("ogg");
}
String ResourceFormatLoaderAudioStreamOGGVorbis::get_resource_type(const String &p_path) const {

	if (p_path.extension().to_lower()=="ogg")
		return "AudioStreamOGGVorbis";
	return "";
}

bool ResourceFormatLoaderAudioStreamOGGVorbis::handles_type(const String& p_type) const {
	return (p_type=="AudioStream" || p_type=="AudioStreamOGG" || p_type=="AudioStreamOGGVorbis");
}


text:
package com.fly.firefly.utils.LazyList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.fly.firefly.R;
import com.koushikdutta.ion.Ion;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ImageLoader {

    MemoryCache memoryCache=new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews= Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;
    Context context;
    Handler handler=new Handler();//handler to display images in UI thread

    public ImageLoader(Context context){
        fileCache=new FileCache(context);
        executorService= Executors.newFixedThreadPool(5);
        this.context = context;
    }

    final int stub_id= R.drawable.loading1;
    public void DisplayImage(String url, ImageView imageView, ProgressBar loader) {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null)
        {

        imageView.setImageBitmap(bitmap);
         if (loader !=null){
                loader.setVisibility(View.INVISIBLE);
          }

        }
        else
        {
            queuePhoto(url, imageView, loader);
            imageView.setImageResource(stub_id);
        }
    }

    private void queuePhoto(String url, ImageView imageView, ProgressBar holder)
    {
        PhotoToLoad p=new PhotoToLoad(url, imageView, holder);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url)
    {
        File f=fileCache.getFile(url);

        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
        {
            return b;
        }

        try {

            Log.d("url---", url);
            Uri uri = Uri.parse(url);
            Map<String, Object> params = new HashMap<String, Object>();
            String o = uri.getQueryParameter("o");
            String i = uri.getQueryParameter("i");
            String k = uri.getQueryParameter("k");
            params.put("o", o);
            params.put("i", i);
            params.put("k", k);
            Bitmap imageTemp = Ion.with(context)
                    .load(url)
                    .setBodyParameter("o", o)
                    .setBodyParameter("i", i)
                    .setBodyParameter("k", k)
                    .asBitmap()
                    .get();
            return imageTemp;
        } catch (Throwable ex){
            ex.printStackTrace();
            if(ex instanceof OutOfMemoryError)
                memoryCache.clear();
            return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            Log.d("get image", "image----");
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream stream1=new FileInputStream(f);
            BitmapFactory.decodeStream(stream1, null, o);
            stream1.close();

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            FileInputStream stream2=new FileInputStream(f);
            Bitmap bitmap= BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public ProgressBar holder;
        public PhotoToLoad(String u, ImageView i, ProgressBar h){
            url=u;
            imageView=i;
            holder = h;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad=photoToLoad;
        }

        @Override
        public void run() {
            try{
                if(imageViewReused(photoToLoad))
                    return;
                Bitmap bmp=getBitmap(photoToLoad.url);
                memoryCache.put(photoToLoad.url, bmp);
                if(imageViewReused(photoToLoad))
                    return;
                BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
                handler.post(bd);
            }catch(Throwable th){
                th.printStackTrace();
            }
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad){
        String tag=imageViews.get(photoToLoad.imageView);
        if(tag==null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
        public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null) {
                Log.d("bitmap ", "bitmap displayer");
                photoToLoad.imageView.setImageBitmap(bitmap);
                if (photoToLoad.holder != null){
                    photoToLoad.holder.setVisibility(View.INVISIBLE);
                }

            }
            else {
                photoToLoad.imageView.setImageResource(stub_id);
                if (photoToLoad.holder != null) {
                    photoToLoad.holder.setVisibility(View.INVISIBLE);
                }
            }
        }
    }
}


text:
require 'chefspec'

RSpec.configure do |config|
  config.expect_with(:rspec) { |c| c.syntax = :expect }
end


text:
import { __assign, __extends, __read, __spreadArray, __values } from '../../tslib/tslib.js';
/**
 * Mixin to add `MDCObserver` functionality to an optional base class.
 *
 * @deprecated Prefer MDCObserverFoundation for stricter closure compliance.
 * @template C Optional base class constructor type.
 * @param baseClass - Optional base class.
 * @return A class that extends the optional base class with `MDCObserver`
 *     functionality.
 */
export function mdcObserver(baseClass) {
    if (baseClass === void 0) { baseClass = /** @class */ (function () {
        function class_1() {
        }
        return class_1;
    }()); }
    // Mixin classes cannot use private members and Symbol() cannot be used in 3P
    // for IE11.
    var unobserveMap = new WeakMap();
    return /** @class */ (function (_super) {
        __extends(MDCObserver, _super);
        function MDCObserver() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        MDCObserver.prototype.observe = function (target, observers) {
            var e_1, _a;
            var _this = this;
            var cleanup = [];
            try {
                for (var _b = __values(Object.keys(observers)), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var property = _c.value;
                    var observer = observers[property].bind(this);
                    cleanup.push(observeProperty(target, property, observer));
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            var unobserve = function () {
                var e_2, _a;
                try {
                    for (var cleanup_1 = __values(cleanup), cleanup_1_1 = cleanup_1.next(); !cleanup_1_1.done; cleanup_1_1 = cleanup_1.next()) {
                        var cleanupFn = cleanup_1_1.value;
                        cleanupFn();
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (cleanup_1_1 && !cleanup_1_1.done && (_a = cleanup_1.return)) _a.call(cleanup_1);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
                var unobserves = unobserveMap.get(_this) || [];
                var index = unobserves.indexOf(unobserve);
                if (index > -1) {
                    unobserves.splice(index, 1);
                }
            };
            var unobserves = unobserveMap.get(this);
            if (!unobserves) {
                unobserves = [];
                unobserveMap.set(this, unobserves);
            }
            unobserves.push(unobserve);
            return unobserve;
        };
        MDCObserver.prototype.setObserversEnabled = function (target, enabled) {
            setObserversEnabled(target, enabled);
        };
        MDCObserver.prototype.unobserve = function () {
            var e_3, _a;
            // Iterate over a copy since unobserve() will remove themselves from the
            // array
            var unobserves = unobserveMap.get(this) || [];
            try {
                for (var _b = __values(__spreadArray([], __read(unobserves))), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var unobserve = _c.value;
                    unobserve();
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_3) throw e_3.error; }
            }
        };
        return MDCObserver;
    }(baseClass));
}
/**
 * Observe a target's property for changes. When a property changes, the
 * provided `Observer` function will be invoked with the properties current and
 * previous values.
 *
 * The returned cleanup function will stop listening to changes for the
 * provided `Observer`.
 *
 * @template T The observed target type.
 * @template K The observed property.
 * @param target - The target to observe.
 * @param property - The property of the target to observe.
 * @param observer - An observer function to invoke each time the property
 *     changes.
 * @return A cleanup function that will stop observing changes for the provided
 *     `Observer`.
 */
export function observeProperty(target, property, observer) {
    var targetObservers = installObserver(target, property);
    var observers = targetObservers.getObservers(property);
    observers.push(observer);
    return function () {
        observers.splice(observers.indexOf(observer), 1);
    };
}
/**
 * A Map of all `TargetObservers` that have been installed.
 */
var allTargetObservers = new WeakMap();
/**
 * Installs a `TargetObservers` for the provided target (if not already
 * installed), and replaces the given property with a getter and setter that
 * will respond to changes and call `TargetObservers`.
 *
 * Subsequent calls to `installObserver()` with the same target and property
 * will not override the property's previously installed getter/setter.
 *
 * @template T The observed target type.
 * @template K The observed property to create a getter/setter for.
 * @param target - The target to observe.
 * @param property - The property to create a getter/setter for, if needed.
 * @return The installed `TargetObservers` for the provided target.
 */
function installObserver(target, property) {
    var observersMap = new Map();
    if (!allTargetObservers.has(target)) {
        allTargetObservers.set(target, {
            isEnabled: true,
            getObservers: function (key) {
                var observers = observersMap.get(key) || [];
                if (!observersMap.has(key)) {
                    observersMap.set(key, observers);
                }
                return observers;
            },
            installedProperties: new Set()
        });
    }
    var targetObservers = allTargetObservers.get(target);
    if (targetObservers.installedProperties.has(property)) {
        // The getter/setter has already been replaced for this property
        return targetObservers;
    }
    // Retrieve (or create if it's a plain property) the original descriptor from
    // the target...
    var descriptor = getDescriptor(target, property) || {
        configurable: true,
        enumerable: true,
        value: target[property],
        writable: true
    };
    // ...and create a copy that will be used for the observer.
    var observedDescriptor = __assign({}, descriptor);
    var descGet = descriptor.get, descSet = descriptor.set;
    if ('value' in descriptor) {
        // The descriptor is a simple value (not a getter/setter).
        // For our observer descriptor that we copied, delete the value/writable
        // properties, since they are incompatible with the get/set properties
        // for descriptors.
        delete observedDescriptor.value;
        delete observedDescriptor.writable;
        // Set up a simple getter...
        var value_1 = descriptor.value;
        descGet = function () { return value_1; };
        // ...and setter (if the original property was writable).
        if (descriptor.writable) {
            descSet = function (newValue) {
                value_1 = newValue;
            };
        }
    }
    if (descGet) {
        observedDescriptor.get = function () {
            // `this as T` needed for closure conformance
            return descGet.call(this);
        };
    }
    if (descSet) {
        observedDescriptor.set = function (newValue) {
            var e_4, _a;
            // `thus as T` needed for closure conformance
            var previous = descGet ? descGet.call(this) : newValue;
            descSet.call(this, newValue);
            if (targetObservers.isEnabled && (!descGet || newValue !== previous)) {
                try {
                    for (var _b = __values(targetObservers.getObservers(property)), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var observer = _c.value;
                        observer(newValue, previous);
                    }
                }
                catch (e_4_1) { e_4 = { error: e_4_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_4) throw e_4.error; }
                }
            }
        };
    }
    targetObservers.installedProperties.add(property);
    Object.defineProperty(target, property, observedDescriptor);
    return targetObservers;
}
/**
 * Retrieves the descriptor for a property from the provided target. This
 * function will walk up the target's prototype chain to search for the
 * descriptor.
 *
 * @template T The target type.
 * @template K The property type.
 * @param target - The target to retrieve a descriptor from.
 * @param property - The name of the property to retrieve a descriptor for.
 * @return the descriptor, or undefined if it does not exist. Keep in mind that
 *     plain properties may not have a descriptor defined.
 */
export function getDescriptor(target, property) {
    var descriptorTarget = target;
    var descriptor;
    while (descriptorTarget) {
        descriptor = Object.getOwnPropertyDescriptor(descriptorTarget, property);
        if (descriptor) {
            break;
        }
        // Walk up the instance's prototype chain in case the property is declared
        // on a superclass.
        descriptorTarget = Object.getPrototypeOf(descriptorTarget);
    }
    return descriptor;
}
/**
 * Enables or disables all observers for a provided target. Changes to observed
 * properties will not call any observers when disabled.
 *
 * @template T The observed target type.
 * @param target - The target to enable or disable observers for.
 * @param enabled - True to enable or false to disable observers.
 */
export function setObserversEnabled(target, enabled) {
    var targetObservers = allTargetObservers.get(target);
    if (targetObservers) {
        targetObservers.isEnabled = enabled;
    }
}
//# sourceMappingURL=observer.js.map


text:
/**
 * File description
 */

/**
 * Sample class
 * @class Point
 * @param {Object} [coords]
 * @param {Int} coords.x
 * @param {Int} coords.y
 */
function Point(options) {

}

/*
 * This should be skipped
 */

    /**
     * Tells if point was ever initilized with coordinates
     * @property {Boolean} [initilized=false]
     */
    Point.prototype.initilized = false;

    /**
     * Moves point by x,y
     * @method move
     * @param {Object} [by]
     * @param {Int} by.x
     * @param {Int} by.y
     */
    Point.prototype.move = function(by) {

    }


text:
package net.paoding.rose.controllers;

import net.paoding.rose.RoseVersion;
import net.paoding.rose.web.ControllerInterceptorAdapter;
import net.paoding.rose.web.Invocation;

import org.apache.commons.logging.LogFactory;

/**
 *
 * @author 王志亮 [qieqie.wang@gmail.com]
 *
 */
public class RoseToolsInterceptor extends ControllerInterceptorAdapter {

    @Override
    public Object before(Invocation inv) throws Exception {
        Class<?> controllerClass = inv.getControllerClass();
        if (!LogFactory.getLog(controllerClass).isDebugEnabled()) {
            String msg = String.format("warning: set logger.%s to debug level first. "
                    + "<br> Rose-Version: %s", controllerClass.getName(), RoseVersion.getVersion());
            return Utils.wrap(msg);
        }
        return true;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<labels>
	Projekt
	Potvrzený
	Přidělený osobě
	Přidělený k rolím
	Vlastník je osoba
	Vlastníkem jsou role
	Já jsem vlastník
	Vytvořeno osobou
	Vytvořeno rolemi
	Nadřazený úkol
	Veřejný
	Způsob fakturace
	Název
	Plné znění
	Typ
	Pracovní položka
	Řízení času
	Datum splnění
	Datum splnění (dynamické)
	Počáteční datum
	Počáteční datum (dynamické)
	Závěrečné datum
	Závěrečné datum (dynamické)
	Naposledy upraveno
	Naposledy upraveno (dynamické)
	Datum vytvoření
	Datum vytvoření (dynamické)
	ID projektu
	Status projektu
	Celý název
	Název projektu
	Zákazník
	Role projektu
	Vedoucí projektu
	Projektový dozor
	Řízení času
	Počáteční datum projektu
	Závěrečné datum projektu
	Termín ukončení projektu
	Datum vytvoření
	Datum vytvoření (dynamické)
	Naposledy upraveno
	Naposledy upraveno (dynamické)
	Projekty
	Úkol z filtru úkolů
	Přiřazen k projektu
	Má projekt(y) sse stavem
	Má úkoly vytvořené před/po
	Má úkoly vytvořené od/do (dynamicky)
</labels>


text:
class AuthorizationController < ApplicationController

  before_action { warden.authenticate! scope: :user }

  def authorize
    if (tenant = Tenant.where(id: params[:tenant_id]).first)
      tenant.switch do
        errors = nil
        auth = @authorization = Setup::Authorization.where(id: params[:id]).first
        if auth
          if auth.check
            if auth.is_a?(Setup::CallbackAuthorization)
              begin
                cenit_token = CallbackAuthorizationToken.create(authorization: auth, data: {})
                url = auth.authorize_url(cenit_token: cenit_token)
                cenit_token.save
                session[:oauth_state] = cenit_token.token

                redirect_to url
              rescue Exception => ex
                errors = [ex.message]
              end
            else
              render_form_for(auth)
            end
          else
            errors = auth.errors.full_messages
          end

          if errors
            @errors = errors
            render :errors, status: :unprocessable_entity
          end
        else
          render :not_found, status: :not_found
        end
      end
    else
      render :not_found, status: :not_found
    end
  end

  def show
    if (error = params[:error])
      @errors = [error]
    end
    @authorization = (tenant = Tenant.where(id: params[:tenant_id]).first) &&
      tenant.switch { Setup::Authorization.where(id: params[:id]).first }

    render :not_found, status: :not_found unless @authorization
  end

  def render_form_for(auth)
    render :form
  end
end


text:
declare namespace java {
  namespace lang {

    class UnknownError extends java.lang.VirtualMachineError {
      public constructor()
      public constructor(arg0: java.lang.String | string)
    }

  }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8"></meta>
		<meta name="generator" content="JsDoc Toolkit"></meta>
		<title>enchant.gl.physics.Rigid | JsDoc Reference</title>

		<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"></meta>
		<meta name="mobileoptimized" content="0"></meta>

		<link rel="stylesheet" href="../css/all.css" media="all"></link>
		<link rel="stylesheet" href="../css/handheld.css" media="only screen and (max-width: 660px)"></link>
		<link rel="stylesheet" href="../css/handheld.css" media="handheld"></link>
		<link rel="stylesheet" href="../css/screen.css" media="screen and (min-width: 661px)"></link>

			Classes
			Files

Classes

		<input type="text" name="classFilter" class="classFilter" id="ClassFilter" placeholder="Filter"></input>

_global_

enchant . Action

enchant . ActionEventTarget

enchant . Avatar

enchant . avatar . AvatarCharacter

enchant . avatar . AvatarMonster

enchant . AvatarBG

enchant . box2d . PhysicsWorld

enchant . box2d . PhySprite

enchant . CanvasLayer

enchant . Class

enchant . Class . MixingRecipe

enchant . Core

enchant . DOMSound

enchant . Easing

enchant . Entity

enchant . ENV

enchant . Event

enchant . EventTarget

enchant . gl . AmbientLight

enchant . gl . Bone

enchant . gl . Buffer

enchant . gl . Camera3D

enchant . gl . collada . AbstractColladaSprite3D

enchant . gl . collada . ColladaBone

enchant . gl . collada . ColladaMesh

enchant . gl . collada . ColladaSkeleton

enchant . gl . collada . ColladaSkeletonSpriteMesh

enchant . gl . collada . ColladaSprite3D

enchant . gl . collision . AABB

enchant . gl . collision . Bounding

enchant . gl . collision . BS

enchant . gl . collision . OBB

enchant . gl . DirectionalLight

enchant . gl . Framebuffer

enchant . gl . KeyFrameManager

enchant . gl . Light3D

enchant . gl . Mesh

enchant . gl . mmd . MAnimation

enchant . gl . mmd . MMesh

enchant . gl . mmd . MSprite3D

enchant . gl . physics . PhyBox

enchant . gl . physics . PhyCapsule

enchant . gl . physics . PhyContainer

enchant . gl . physics . PhyCube

enchant . gl . physics . PhyCylinder

enchant . gl . physics . PhyPlane

enchant . gl . physics . PhyScene3D

enchant . gl . physics . PhySphere

enchant . gl . physics . PhySprite3D

enchant . gl . physics . Rigid

enchant . gl . physics . RigidBox

enchant . gl . physics . RigidCapsule

enchant . gl . physics . RigidContainer

enchant . gl . physics . RigidCube

enchant . gl . physics . RigidCylinder

enchant . gl . physics . RigidPlane

enchant . gl . physics . RigidSphere

enchant . gl . physics . World

enchant . gl . PointLight

enchant . gl . Pose

enchant . gl . Quat

enchant . gl . Scene3D

enchant . gl . Shader

enchant . gl . Skeleton

enchant . gl . Sprite3D

enchant . gl . State

enchant . gl . Texture

enchant . Group

enchant . Label

enchant . LoadingScene .

enchant . Map

enchant . nineleap . Core

enchant . nineleap . memory . Core

enchant . nineleap . memory . HttpRequest

enchant . nineleap . memory . LocalStorage

enchant . nineleap . memory . MemoryWrite

enchant . nineleap . SplashScene

enchant . nineleap . twitter . Core

enchant . nineleap . twitter . TwitterRequest

enchant . nineleap . twitter . TwitterStatusData

enchant . nineleap . twitter . TwitterUserData

enchant . Node

enchant . ParallelAction

enchant . PhyBoxSprite

enchant . PhyCircleSprite

enchant . Scene

enchant . Sprite

enchant . Surface

enchant . Timeline

enchant . Tween

enchant . ui . APad

enchant . ui . Bar

enchant . ui . Button

enchant . ui . LifeLabel

enchant . ui . MutableText

enchant . ui . Pad

enchant . ui . ScoreLabel

enchant . ui . TimeLabel

enchant . ui . VirtualMap

enchant . WebAudioSound

enchant . widget . Alert

enchant . widget . AlertScene

enchant . widget . Button

enchant . widget . Confirm

enchant . widget . ConfirmScene

enchant . widget . EntityGroup

enchant . widget . GestureDetector

enchant . widget . IconMenu

enchant . widget . Input

enchant . widget . InputCheckBox

enchant . widget . InputScene

enchant . widget . InputSelectBox

enchant . widget . InputTextArea

enchant . widget . InputTextBox

enchant . widget . ListElement

enchant . widget . ListItem

enchant . widget . ListItemVertical

enchant . widget . ListView

enchant . widget . Modal

enchant . widget . NavigationBar

enchant . widget . Ninepatch

enchant . widget . Prompt

enchant . widget . PromptScene

enchant . widget . ScrollView

enchant . wiiu

Object

		Documentation generator: JsDoc Toolkit 2.4.0

		Template: Codeview 1.2

		Generated on: 2013-4-1 1:14

			Class enchant.gl.physics.Rigid

Defined in: physics.gl.enchant.js

Class Summary

							Constructor Attributes
							Constructor Name and Description

									enchant.gl.physics.Rigid(shape, mass, linearDamping, angularDamping)

Rigid body object.

Field Summary

								Field Attributes
								Field Name and Description

										friction

Rigid frictions.

										restitution

Rigid restitutions.

										rigidBody

Ammo rigid body object

										world

World that Rigid belongs to

Method Summary

								Method Attributes
								Method Name and Description

activate(force)

Make Rigid valid.

applyCentralImpulse(powerX, powerY, powerZ)

Add power to Rigid.

applyImpulse(powerX, powerY, powerZ, positonX, positonY, positonZ)

Add power to Rigid.

clearForces()

Stops Rigid object.

contactTest(rigid)

Collision detection with another Rigid object.

kinematize()

Kinematize Rigid.

rotationApply(quat)

Applies rotation expressed in quaternion to Rigid.

rotationSet(quat)

Set posture expressed in quaternion in Rigid.

scale(x, y, z)

Expand and contract Rigid.

translate(x, y, z)

Move Rigid in a parallel direciton.

						Class Detail

						enchant.gl.physics.Rigid(shape, mass, linearDamping, angularDamping)

						Rigid body object.
Add to World and activate.

Parameters:

									 shape

Ammo.btCollisionShape object.

									{Number}  mass

Mass of rigid object.

									{Number}  linearDamping

Rate of decay of speed on straight line speed of rigid object.

									{Number}  angularDamping

Rate of decay of angled speed of rigid object.

See:

enchant.gl.physics.RigidBox

enchant.gl.physics.RigidCube

enchant.gl.physics.RigidSphere

enchant.gl.physics.RigidCylinder

enchant.gl.physics.RigidCapsule

enchant.gl.physics.RigidPlane

enchant.gl.physics.RigidContainer

						Field Detail

							{Number}

							friction

							Rigid frictions.

							{Number}

							restitution

							Rigid restitutions.

							rigidBody

							Ammo rigid body object

							world

							World that Rigid belongs to

						Method Detail

									activate(force)

									Make Rigid valid.

Parameters:

												{Boolean} force

Forcibly make valid.

									applyCentralImpulse(powerX, powerY, powerZ)

									Add power to Rigid.
Power is added to the center of Rigid.

Parameters:

												{Number} powerX

Power in x axis.

												{Number} powerY

Power in y axis.

												{Number} powerZ

Power in z axis.

									applyImpulse(powerX, powerY, powerZ, positonX, positonY, positonZ)

									Add power to Rigid.
Power is added to the specified position.

Parameters:

												{Number} powerX

x axis power.

												{Number} powerY

y axis power.

												{Number} powerZ

z axis power.

												{Number} positonX

Coordinate on x axis to add power to.

												{Number} positonY

Coordinate on y axis to add power to.

												{Number} positonZ

Coordinate on z axis to add power to.

									clearForces()

									Stops Rigid object.

									{Boolean}

									contactTest(rigid)

									Collision detection with another Rigid object.

Parameters:

												{enchant.gl.physics.Rigid} rigid

Rigid to be judged.

Returns:

{Boolean} bool Presence or absence of rigid.

									kinematize()

									Kinematize Rigid.

									rotationApply(quat)

									Applies rotation expressed in quaternion to Rigid.

Parameters:

												{enchant.gl.Quat} quat

									rotationSet(quat)

									Set posture expressed in quaternion in Rigid.

Parameters:

												{enchant.gl.Quat} quat

									scale(x, y, z)

									Expand and contract Rigid.
Expand or contract each axis the designated amount from the current rate of expansion in World.

Parameters:

												{Number} x

Rate of expansion on x axis.

												{Number} y

Rate of expansion on y axis.

												{Number} z

Rate of expansion on z axis.

									translate(x, y, z)

									Move Rigid in a parallel direciton.
Move the designated amount in a parallel direction along each axis from the current World position.

Parameters:

												{Number} x

Amount of parallel movement along x axis.

												{Number} y

Amount of parallel movement along y axis.

												{Number} z

Amount of parallel movement along z axis.


text:
package org.apache.hadoop.metrics2.sink.timeline.availability;

import junit.framework.Assert;
import org.apache.hadoop.metrics2.sink.timeline.AbstractTimelineMetricsSink;
import org.apache.hadoop.metrics2.sink.timeline.TimelineMetrics;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collection;

public class AbstractTimelineMetricSinkTest {

  @Test
  public void testParseHostsStringIntoCollection() {
    AbstractTimelineMetricsSink sink = new TestTimelineMetricsSink();
    Collection<String> hosts;

    hosts = sink.parseHostsStringIntoCollection("");
    Assert.assertTrue(hosts.isEmpty());

    hosts = sink.parseHostsStringIntoCollection("test1.123.abc.def.local");
    Assert.assertTrue(hosts.size() == 1);
    Assert.assertTrue(hosts.contains("test1.123.abc.def.local"));

    hosts = sink.parseHostsStringIntoCollection("test1.123.abc.def.local ");
    Assert.assertTrue(hosts.size() == 1);
    Assert.assertTrue(hosts.contains("test1.123.abc.def.local"));

    hosts = sink.parseHostsStringIntoCollection("test1.123.abc.def.local,test1.456.abc.def.local");
    Assert.assertTrue(hosts.size() == 2);

    hosts = sink.parseHostsStringIntoCollection("test1.123.abc.def.local, test1.456.abc.def.local");
    Assert.assertTrue(hosts.size() == 2);
    Assert.assertTrue(hosts.contains("test1.123.abc.def.local"));
    Assert.assertTrue(hosts.contains("test1.456.abc.def.local"));

  }

  private class TestTimelineMetricsSink extends AbstractTimelineMetricsSink {
    @Override
    protected String getCollectorUri(String host) {
      return "";
    }

    @Override
    protected String getCollectorProtocol() {
      return "http";
    }

    @Override
    protected String getCollectorPort() {
      return "2181";
    }

    @Override
    protected int getTimeoutSeconds() {
      return 10;
    }

    @Override
    protected String getZookeeperQuorum() {
      return "localhost:2181";
    }

    @Override
    protected Collection<String> getConfiguredCollectorHosts() {
      return Arrays.asList("localhost");
    }

    @Override
    protected String getHostname() {
      return "h1";
    }

    @Override
    protected boolean isHostInMemoryAggregationEnabled() {
      return true;
    }

    @Override
    protected int getHostInMemoryAggregationPort() {
      return 61888;
    }

    @Override
    public boolean emitMetrics(TimelineMetrics metrics) {
      super.init();
      return super.emitMetrics(metrics);
    }
  }
}


text:
<?php

namespace CRUDlex;

use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
use Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder;
use CRUDlex\AbstractData;
use CRUDlex\Entity;

/**
 * This class setups CRUDlex with some events so the passwords get salted and
 * hashed properly.
 */
class UserSetup
{

    /**
     * The encoder to use.
     */
    protected $encoder;

    /**
     * Gets a closure for possibly generating a password hash in the entity.
     *
     * @param AbstractData $data
     * the AbstractData instance managing the users
     *
     * @param string $passwordField
     * the Entity fieldname of the password hash
     *
     * @param string $saltField
     * the Entity fieldname of the password hash salt
     */
    protected function getPWHashFunction(AbstractData $data, $passwordField, $saltField)
    {
        $that = $this;
        return function(Entity $entity) use ($data, $passwordField, $saltField, $that) {
            $password = $entity->get($passwordField);

            if (!$password) {
                return true;
            }

            $salt = $entity->get($saltField);
            $newSalt = $that->possibleGenSalt($salt, $entity, $saltField);

            $passwordHash = $this->encoder->encodePassword($password, $salt);

            $doGenerateHash = $that->doGenerateHash($data, $entity, $passwordField, $password, $newSalt);

            if ($doGenerateHash) {
                $entity->set($passwordField, $passwordHash);
            }
            return true;
        };
    }

    /**
     * Constructor.
     *
     * @param PasswordEncoderInterface $encoder
     * the encoder to use, defaults to BCryptPasswordEncoder if null is given
     */
    public function __construct(PasswordEncoderInterface $encoder = null)
    {
        $this->encoder = $encoder;
        if ($this->encoder === null) {
            $this->encoder = new BCryptPasswordEncoder(13);
        }
    }

    /**
     * Generates a new salt if the given salt is null.
     *
     * @param string $salt
     * the salt to override if null
     * @param Entity
     * the entity getting the new salt
     * @param string $saltField
     * the field holding the salt in the entity
     *
     * @return boolean
     * true if a new salt was generated
     */
    public function possibleGenSalt(&$salt, Entity $entity, $saltField)
    {
        if (!$salt) {
            $salt = $this->getSalt(40);
            $entity->set($saltField, $salt);
            return true;
        }
        return false;
    }

    /**
     * Determines whether the entity needs a new hash generated.
     *
     * @param AbstractData $data
     * the CRUDlex data instance of the user entity
     * @param Entity $entity
     * the entity
     * @param string $passwordField
     * the field holding the password hash in the entity
     * @param string $password
     * the current password hash
     * @param boolean $newSalt
     * whether a new password hash salt was generated
     *
     * @return boolean
     * true if the entity needs a new hash
     */
    public function doGenerateHash(AbstractData $data, Entity $entity, $passwordField, $password, $newSalt)
    {
        $doGenerateHash = true;
        $id = $entity->get('id');
        if ($id !== null) {
            $oldEntity = $data->get($entity->get('id'));
            $doGenerateHash = $oldEntity->get($passwordField) !== $password || $newSalt;
        }
        return $doGenerateHash;
    }

    /**
     * Generates a random salt of the given length.
     *
     * @param int $len
     * the desired length
     *
     * @return string
     * a random salt of the given length
     */
    public function getSalt($len)
    {
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#$%^&*()-=_+';
        $l = strlen($chars) - 1;
        $str = '';
        for ($i = 0; $i < $len; ++$i) {
            $str .= $chars[mt_rand(0, $l)];
        }
        return $str;
    }

    /**
     * Setups CRUDlex with some events so the passwords get salted and
     * hashed properly.
     *
     * @param AbstractData $data
     * the AbstractData instance managing the users
     *
     * @param string $passwordField
     * the Entity fieldname of the password hash
     *
     * @param string $saltField
     * the Entity fieldname of the password hash salt
     */
    public function addEvents(AbstractData $data, $passwordField = 'password', $saltField = 'salt')
    {

        $that = $this;
        $saltGenFunction = function(Entity $entity) use ($saltField, $that) {
            $salt = $that->getSalt(40);
            $entity->set($saltField, $salt);
            return true;
        };

        $data->getEvents()->push('before', 'create', $saltGenFunction);

        $pwHashFunction = $this->getPWHashFunction($data, $passwordField, $saltField);

        $data->getEvents()->push('before', 'create', $pwHashFunction);
        $data->getEvents()->push('before', 'update', $pwHashFunction);

    }

}


text: A functional MUD driver in Haskell.


text:
/**
@module ember
@submodule ember-htmlbars
*/

import { appendSimpleBoundView } from "ember-views/views/simple_bound_view";
import { isStream } from "ember-metal/streams/utils";
import lookupHelper from "ember-htmlbars/system/lookup-helper";

export default function block(env, morph, view, path, params, hash, template, inverse) {
  var helper = lookupHelper(path, view, env);

  var options = {
    morph: morph,
    template: template,
    inverse: inverse,
    isBlock: true
  };
  var result = helper.helperFunction.call(view, params, hash, options, env);

  if (isStream(result)) {
    appendSimpleBoundView(view, morph, result);
  } else {
    morph.setContent(result);
  }
}


text:
cask "redis-pro" do
  version "1.4.0"
  sha256 "2774e8e86df88eab76c61a342e58c7d31656551bee354eca212ee9d53762a96c"

  url "https://github.com/cmushroom/redis-pro/releases/download/#{version}/redis-pro.dmg"
  name "redis-pro"
  desc "Redis desktop"
  homepage "https://github.com/cmushroom/redis-pro"

  app "redis-pro.app"

  zap trash: [
    "~/Library/Application Scripts/com.cmushroom.redis-pro",
    "~/Library/Application Support/com.cmushroom.redis-pro",
    "~/Library/Caches/com.cmushroom.redis-pro",
    "~/Library/Containers/com.cmushroom.redis-pro",
    "~/Library/Preferences/com.cmushroom.redis-pro.plist",
    "~/Library/Saved Application State/com.cmushroom.redis-pro.savedState",
  ]
end


text:
<!DOCTYPE html>

	<meta charset="utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<title>jQuery custom scrollbar demo</title>
	<meta name="viewport" content="width=device-width, initial-scale=1" />

	<link rel="stylesheet" href="style.css">

	<link rel="stylesheet" href="../jquery.mCustomScrollbar.css">

textarea example

				<form>

						<textarea>Start typing...</textarea>

				</form>

Plugin home Project on Github MIT License


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="generator" content="ApiGen 2.8.0" />

	<title>File classes/shortcodes/class-wc-shortcode-checkout.php | WooCommerce</title>

	<link rel="stylesheet" type="text/css" media="all" href="resources/bootstrap.min-2450451432.css" />
	<link rel="stylesheet" type="text/css" media="all" href="resources/style-1319793728.css" />

				WooCommerce

							Package

							Class

							Tree

							Download

							← Back to WooDocs

		<form id="search" class="form-search">
			<input type="hidden" name="cx" value="" />
			<input type="hidden" name="ie" value="UTF-8" />
			<input type="text" name="q" class="search-query" placeholder="Search" />
		</form>

Packages

WooCommerce

Abstracts

Admin

Coupons

Dashboard

Import

Importers

Install

Orders

Products

Reports

Settings

System

Taxonomies

Updates

Users

WritePanels

Classes

Emails

Integrations

Payment

Products

Shipping

Walkers

Functions

AJAX

Shortcodes

Cart

Change

Password

Checkout

Edit

Address

Lost

Password

My

Account

Order

Tracking

Pay

Thankyou

View

Order

Templates

Archives

Cart

Checkout

Forms

Loop

Orders

Product

Tabs

Widgets

Classes

WC_Shortcode_Checkout

 1 <?php
 2 /**
 3  * Checkout Shortcode
 4  *
 5  * Used on the checkout page, the checkout shortcode displays the checkout process.
 6  *
 7  * @author      WooThemes
 8  * @category    Shortcodes
 9  * @package     WooCommerce/Shortcodes/Checkout
10  * @version     2.0.0
11  */
12
13 class WC_Shortcode_Checkout {
14
15     /**
16      * Get the shortcode content.
17      *
18      * @access public
19      * @param array $atts
20      * @return string
21      */
22     public static function get( $atts ) {
23         global $woocommerce;
24         return $woocommerce->shortcode_wrapper( array( __CLASS__, 'output' ), $atts );
25     }
26
27     /**
28      * Output the shortcode.
29      *
30      * @access public
31      * @param array $atts
32      * @return void
33      */
34     public static function output( $atts ) {
35         global $woocommerce;
36
37         // Show non-cart errors
38         $woocommerce->show_messages();
39
40         // Check cart has contents
41         if ( sizeof( $woocommerce->cart->get_cart() ) == 0 ) return;
42
43         // Calc totals
44         $woocommerce->cart->calculate_totals();
45
46         // Check cart contents for errors
47         do_action('woocommerce_check_cart_items');
48
49         // Get checkout object
50         $checkout = $woocommerce->checkout();
51
52         if ( empty( $_POST ) && $woocommerce->error_count() > 0 ) {
53
54             woocommerce_get_template( 'checkout/cart-errors.php', array( 'checkout' => $checkout ) );
55
56         } else {
57
58             $non_js_checkout = ! empty( $_POST['woocommerce_checkout_update_totals'] ) ? true : false;
59
60             if ( $woocommerce->error_count() == 0 && $non_js_checkout )
61                 $woocommerce->add_message( __( 'The order totals have been updated. Please confirm your order by pressing the Place Order button at the bottom of the page.', 'woocommerce' ) );
62
63             woocommerce_get_template( 'checkout/form-checkout.php', array( 'checkout' => $checkout ) );
64
65         }
66     }
67 }

		WooCommerce API documentation generated by ApiGen 2.8.0


text:
jQuery(window).load(function() {
/*global jQuery:false */
"use strict";

  jQuery('.widgetflexslider').flexslider({
    animation: "slide",
    animationLoop: true,
    itemWidth: 320,
	slideshowSpeed: 10000,
	useCSS: false,
    itemMargin: 0,
    minItems: 1,
    maxItems: 3
  });

});


text:
import argparse
import glob
import importlib
import os
import sys

class Conf:
    def __init__(self):
        sys.path.insert(0, '.')
        sys.setrecursionlimit(15000)
        self.root = os.path.realpath('.')
        self.parser = None
        self.args = None
        path = '{0}/version.txt'.format(os.path.realpath(
            os.path.dirname(__file__)))
        with open(path) as f:
            self.version = f.read().strip()

    def parse_arguments(self):
        self.parser = argparse.ArgumentParser()
        self.parser.add_argument('challenge', nargs='?',
                                 help='the challenge to run, to scaffold or '
                                      'to test')
        self.parser.add_argument('-f', '--file', action='store',
                                 help='load sample from given file')
        self.parser.add_argument('-k', '--klass', action='store_true',
                                 help='use sample form challenge class file')
        self.parser.add_argument('-l', '--list', action='store_true',
                                 help='list challenges')
        self.parser.add_argument('-s', '--scaffold', action='store_true',
                                 help="scaffold challenge")
        self.parser.add_argument('-u', '--unittest', action='store_true',
                                 help='unittest challenge')
        self.parser.add_argument('-v', '--verbose', action='store_true',
                                 help='verbose output')
        self.parser.add_argument('-V', '--version', action='version',
                                 version='%(prog)s {}'.format(self.version))
        self.parser.add_argument('-w', '--write', action='store_true',
                                 help='write input and sample file into '
                                      'challenge directory')
        if len(sys.argv) == 1:
            self.print_help()
        self.args = self.parser.parse_args()
        if self.args.challenge and self.args.challenge[-1:] == '/':
            self.args.challenge = self.args.challenge[0:-1]

    def print_help(self):
        self.parser.print_help()
        sys.exit(1)

    def get_challenge_dir(self):
        return self.root + '/' + self.args.challenge

    def get_challenge_file(self):
        challenge = self.args.challenge
        return self.root + '/' + challenge + '/challenge.py'

    def get_challenge_init_file(self):
        challenge = self.args.challenge
        return self.root + '/' + challenge + '/__init__.py'

    def get_unittest_file(self):
        challenge = self.args.challenge
        return self.root + '/' + challenge + '/test.py'

    def get_input_file(self):
        return os.path.realpath(self.args.file)

    def get_sample_file(self):
        return os.path.realpath(self.get_challenge_dir() + '/sample.txt')

    def get_result_file(self):
        return os.path.realpath(self.get_challenge_dir() + '/result.txt')

    def get_latest_file(self):
        return os.path.realpath(self.get_challenge_dir() + '/latest.txt')

    def get_latest_at_root(self):
        return os.path.realpath(self.root + '/latest.txt')

    def get_challenges(self):
        pattern = self.root + '/*/'
        return [d for d in (os.path.basename(d[:-1])
                            for d in glob.glob(pattern))
                if d[0:1] == d[0:1].upper() and d[0:1] != '_'
                ]

    def get_challenge_name(self):
        return self.args.challenge

    def get_full_qualified_challenge_name(self):
        challenge = self.get_challenge_name()
        return challenge + '.challenge.' + challenge + 'Challenge'

    def get_full_qualified_unittest_name(self):
        challenge = self.get_challenge_name()
        return challenge + '.test.' + challenge + 'Test'

    def get_challenge(self):
        return self.get_class(self.get_full_qualified_challenge_name())()

    def get_unittest(self):
        return self.get_class(self.get_full_qualified_unittest_name())

    @staticmethod
    def get_class(class_):
        parts = class_.split('.')
        module = ".".join(parts[:-1])
        return getattr(importlib.import_module(module), parts[-1])


text:
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="deploy" name="models_core">
	<import file="${user.home}/conf/adligo/builds/gwt-build.xml"/>
</project>


text:
package iscsi

import (
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/klog"
	"k8s.io/kubernetes/pkg/util/keymutex"
	"k8s.io/kubernetes/pkg/util/mount"
	utilstrings "k8s.io/kubernetes/pkg/util/strings"
	"k8s.io/kubernetes/pkg/volume"
	ioutil "k8s.io/kubernetes/pkg/volume/util"
	"k8s.io/kubernetes/pkg/volume/util/volumepathhandler"
)

// This is the primary entrypoint for volume plugins.
func ProbeVolumePlugins() []volume.VolumePlugin {
	return []volume.VolumePlugin{&iscsiPlugin{}}
}

type iscsiPlugin struct {
	host        volume.VolumeHost
	targetLocks keymutex.KeyMutex
}

var _ volume.VolumePlugin = &iscsiPlugin{}
var _ volume.PersistentVolumePlugin = &iscsiPlugin{}
var _ volume.BlockVolumePlugin = &iscsiPlugin{}

const (
	iscsiPluginName = "kubernetes.io/iscsi"
)

func (plugin *iscsiPlugin) Init(host volume.VolumeHost) error {
	plugin.host = host
	plugin.targetLocks = keymutex.NewHashed(0)
	return nil
}

func (plugin *iscsiPlugin) GetPluginName() string {
	return iscsiPluginName
}

func (plugin *iscsiPlugin) GetVolumeName(spec *volume.Spec) (string, error) {
	tp, _, iqn, lun, err := getISCSITargetInfo(spec)
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("%v:%v:%v", tp, iqn, lun), nil
}

func (plugin *iscsiPlugin) CanSupport(spec *volume.Spec) bool {
	return (spec.Volume != nil && spec.Volume.ISCSI != nil) || (spec.PersistentVolume != nil && spec.PersistentVolume.Spec.ISCSI != nil)
}

func (plugin *iscsiPlugin) RequiresRemount() bool {
	return false
}

func (plugin *iscsiPlugin) SupportsMountOption() bool {
	return true
}

func (plugin *iscsiPlugin) SupportsBulkVolumeVerification() bool {
	return false
}

func (plugin *iscsiPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode {
	return []v1.PersistentVolumeAccessMode{
		v1.ReadWriteOnce,
		v1.ReadOnlyMany,
	}
}

func (plugin *iscsiPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) {
	if pod == nil {
		return nil, fmt.Errorf("nil pod")
	}
	secret, err := createSecretMap(spec, plugin, pod.Namespace)
	if err != nil {
		return nil, err
	}
	return plugin.newMounterInternal(spec, pod.UID, &ISCSIUtil{}, plugin.host.GetMounter(plugin.GetPluginName()), plugin.host.GetExec(plugin.GetPluginName()), secret)
}

func (plugin *iscsiPlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, manager diskManager, mounter mount.Interface, exec mount.Exec, secret map[string]string) (volume.Mounter, error) {
	readOnly, fsType, err := getISCSIVolumeInfo(spec)
	if err != nil {
		return nil, err
	}
	iscsiDisk, err := createISCSIDisk(spec, podUID, plugin, manager, secret)
	if err != nil {
		return nil, err
	}

	if iscsiDisk != nil {

		//Add volume metrics
		iscsiDisk.MetricsProvider = volume.NewMetricsStatFS(iscsiDisk.GetPath())
	}
	return &iscsiDiskMounter{
		iscsiDisk:    iscsiDisk,
		fsType:       fsType,
		readOnly:     readOnly,
		mounter:      &mount.SafeFormatAndMount{Interface: mounter, Exec: exec},
		exec:         exec,
		deviceUtil:   ioutil.NewDeviceHandler(ioutil.NewIOHandler()),
		mountOptions: ioutil.MountOptionFromSpec(spec),
	}, nil
}

// NewBlockVolumeMapper creates a new volume.BlockVolumeMapper from an API specification.
func (plugin *iscsiPlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.BlockVolumeMapper, error) {
	// If this is called via GenerateUnmapDeviceFunc(), pod is nil.
	// Pass empty string as dummy uid since uid isn't used in the case.
	var uid types.UID
	var secret map[string]string
	var err error
	if pod != nil {
		uid = pod.UID
		secret, err = createSecretMap(spec, plugin, pod.Namespace)
		if err != nil {
			return nil, err
		}
	}
	return plugin.newBlockVolumeMapperInternal(spec, uid, &ISCSIUtil{}, plugin.host.GetMounter(plugin.GetPluginName()), plugin.host.GetExec(plugin.GetPluginName()), secret)
}

func (plugin *iscsiPlugin) newBlockVolumeMapperInternal(spec *volume.Spec, podUID types.UID, manager diskManager, mounter mount.Interface, exec mount.Exec, secret map[string]string) (volume.BlockVolumeMapper, error) {
	readOnly, _, err := getISCSIVolumeInfo(spec)
	if err != nil {
		return nil, err
	}
	iscsiDisk, err := createISCSIDisk(spec, podUID, plugin, manager, secret)
	if err != nil {
		return nil, err
	}
	return &iscsiDiskMapper{
		iscsiDisk:  iscsiDisk,
		readOnly:   readOnly,
		exec:       exec,
		deviceUtil: ioutil.NewDeviceHandler(ioutil.NewIOHandler()),
	}, nil
}

func (plugin *iscsiPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {
	return plugin.newUnmounterInternal(volName, podUID, &ISCSIUtil{}, plugin.host.GetMounter(plugin.GetPluginName()), plugin.host.GetExec(plugin.GetPluginName()))
}

func (plugin *iscsiPlugin) newUnmounterInternal(volName string, podUID types.UID, manager diskManager, mounter mount.Interface, exec mount.Exec) (volume.Unmounter, error) {
	return &iscsiDiskUnmounter{
		iscsiDisk: &iscsiDisk{
			podUID:          podUID,
			VolName:         volName,
			manager:         manager,
			plugin:          plugin,
			MetricsProvider: volume.NewMetricsStatFS(plugin.host.GetPodVolumeDir(podUID, utilstrings.EscapeQualifiedNameForDisk(iscsiPluginName), volName)),
		},
		mounter:    mounter,
		exec:       exec,
		deviceUtil: ioutil.NewDeviceHandler(ioutil.NewIOHandler()),
	}, nil
}

// NewBlockVolumeUnmapper creates a new volume.BlockVolumeUnmapper from recoverable state.
func (plugin *iscsiPlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error) {
	return plugin.newUnmapperInternal(volName, podUID, &ISCSIUtil{}, plugin.host.GetExec(plugin.GetPluginName()))
}

func (plugin *iscsiPlugin) newUnmapperInternal(volName string, podUID types.UID, manager diskManager, exec mount.Exec) (volume.BlockVolumeUnmapper, error) {
	return &iscsiDiskUnmapper{
		iscsiDisk: &iscsiDisk{
			podUID:  podUID,
			VolName: volName,
			manager: manager,
			plugin:  plugin,
		},
		exec:       exec,
		deviceUtil: ioutil.NewDeviceHandler(ioutil.NewIOHandler()),
	}, nil
}

func (plugin *iscsiPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) {
	// Find globalPDPath from pod volume directory(mountPath)
	var globalPDPath string
	mounter := plugin.host.GetMounter(plugin.GetPluginName())
	paths, err := mounter.GetMountRefs(mountPath)
	if err != nil {
		return nil, err
	}
	for _, path := range paths {
		if strings.Contains(path, plugin.host.GetPluginDir(iscsiPluginName)) {
			globalPDPath = path
			break
		}
	}
	// Couldn't fetch globalPDPath
	if len(globalPDPath) == 0 {
		return nil, fmt.Errorf("couldn't fetch globalPDPath. failed to obtain volume spec")
	}

	// Obtain iscsi disk configurations from globalPDPath
	device, _, err := extractDeviceAndPrefix(globalPDPath)
	if err != nil {
		return nil, err
	}
	bkpPortal, iqn, err := extractPortalAndIqn(device)
	if err != nil {
		return nil, err
	}
	iface, _ := extractIface(globalPDPath)
	iscsiVolume := &v1.Volume{
		Name: volumeName,
		VolumeSource: v1.VolumeSource{
			ISCSI: &v1.ISCSIVolumeSource{
				TargetPortal:   bkpPortal,
				IQN:            iqn,
				ISCSIInterface: iface,
			},
		},
	}
	return volume.NewSpecFromVolume(iscsiVolume), nil
}

func (plugin *iscsiPlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error) {
	pluginDir := plugin.host.GetVolumeDevicePluginDir(iscsiPluginName)
	blkutil := volumepathhandler.NewBlockVolumePathHandler()
	globalMapPathUUID, err := blkutil.FindGlobalMapPathUUIDFromPod(pluginDir, mapPath, podUID)
	if err != nil {
		return nil, err
	}
	klog.V(5).Infof("globalMapPathUUID: %v, err: %v", globalMapPathUUID, err)
	// Retrieve volume information from globalMapPathUUID
	// globalMapPathUUID example:
	// plugins/kubernetes.io/{PluginName}/{DefaultKubeletVolumeDevicesDirName}/{volumePluginDependentPath}/{pod uuid}
	// plugins/kubernetes.io/iscsi/volumeDevices/iface-default/192.168.0.10:3260-iqn.2017-05.com.example:test-lun-0/{pod uuid}
	globalMapPath := filepath.Dir(globalMapPathUUID)
	return getVolumeSpecFromGlobalMapPath(volumeName, globalMapPath)
}

type iscsiDisk struct {
	VolName       string
	podUID        types.UID
	Portals       []string
	Iqn           string
	Lun           string
	Iface         string
	chapDiscovery bool
	chapSession   bool
	secret        map[string]string
	InitiatorName string
	plugin        *iscsiPlugin
	// Utility interface that provides API calls to the provider to attach/detach disks.
	manager diskManager
	volume.MetricsProvider
}

func (iscsi *iscsiDisk) GetPath() string {
	name := iscsiPluginName
	// safe to use PodVolumeDir now: volume teardown occurs before pod is cleaned up
	return iscsi.plugin.host.GetPodVolumeDir(iscsi.podUID, utilstrings.EscapeQualifiedNameForDisk(name), iscsi.VolName)
}

func (iscsi *iscsiDisk) iscsiGlobalMapPath(spec *volume.Spec) (string, error) {
	mounter, err := volumeSpecToMounter(spec, iscsi.plugin.host, iscsi.plugin.targetLocks, nil /* pod */)
	if err != nil {
		klog.Warningf("failed to get iscsi mounter: %v", err)
		return "", err
	}
	return iscsi.manager.MakeGlobalVDPDName(*mounter.iscsiDisk), nil
}

func (iscsi *iscsiDisk) iscsiPodDeviceMapPath() (string, string) {
	name := iscsiPluginName
	return iscsi.plugin.host.GetPodVolumeDeviceDir(iscsi.podUID, utilstrings.EscapeQualifiedNameForDisk(name)), iscsi.VolName
}

type iscsiDiskMounter struct {
	*iscsiDisk
	readOnly     bool
	fsType       string
	volumeMode   v1.PersistentVolumeMode
	mounter      *mount.SafeFormatAndMount
	exec         mount.Exec
	deviceUtil   ioutil.DeviceUtil
	mountOptions []string
}

var _ volume.Mounter = &iscsiDiskMounter{}

func (b *iscsiDiskMounter) GetAttributes() volume.Attributes {
	return volume.Attributes{
		ReadOnly:        b.readOnly,
		Managed:         !b.readOnly,
		SupportsSELinux: true,
	}
}

// Checks prior to mount operations to verify that the required components (binaries, etc.)
// to mount the volume are available on the underlying node.
// If not, it returns an error
func (b *iscsiDiskMounter) CanMount() error {
	return nil
}

func (b *iscsiDiskMounter) SetUp(fsGroup *int64) error {
	return b.SetUpAt(b.GetPath(), fsGroup)
}

func (b *iscsiDiskMounter) SetUpAt(dir string, fsGroup *int64) error {
	// diskSetUp checks mountpoints and prevent repeated calls
	err := diskSetUp(b.manager, *b, dir, b.mounter, fsGroup)
	if err != nil {
		klog.Errorf("iscsi: failed to setup")
	}
	return err
}

type iscsiDiskUnmounter struct {
	*iscsiDisk
	mounter    mount.Interface
	exec       mount.Exec
	deviceUtil ioutil.DeviceUtil
}

var _ volume.Unmounter = &iscsiDiskUnmounter{}

// Unmounts the bind mount, and detaches the disk only if the disk
// resource was the last reference to that disk on the kubelet.
func (c *iscsiDiskUnmounter) TearDown() error {
	return c.TearDownAt(c.GetPath())
}

func (c *iscsiDiskUnmounter) TearDownAt(dir string) error {
	return ioutil.UnmountPath(dir, c.mounter)
}

// Block Volumes Support
type iscsiDiskMapper struct {
	*iscsiDisk
	readOnly   bool
	exec       mount.Exec
	deviceUtil ioutil.DeviceUtil
}

var _ volume.BlockVolumeMapper = &iscsiDiskMapper{}

func (b *iscsiDiskMapper) SetUpDevice() (string, error) {
	return "", nil
}

func (b *iscsiDiskMapper) MapDevice(devicePath, globalMapPath, volumeMapPath, volumeMapName string, podUID types.UID) error {
	return ioutil.MapBlockVolume(devicePath, globalMapPath, volumeMapPath, volumeMapName, podUID)
}

type iscsiDiskUnmapper struct {
	*iscsiDisk
	exec       mount.Exec
	deviceUtil ioutil.DeviceUtil
}

var _ volume.BlockVolumeUnmapper = &iscsiDiskUnmapper{}

// Even though iSCSI plugin has attacher/detacher implementation, iSCSI plugin
// needs volume detach operation during TearDownDevice(). This method is only
// chance that operations are done on kubelet node during volume teardown sequences.
func (c *iscsiDiskUnmapper) TearDownDevice(mapPath, _ string) error {
	err := c.manager.DetachBlockISCSIDisk(*c, mapPath)
	if err != nil {
		return fmt.Errorf("iscsi: failed to detach disk: %s\nError: %v", mapPath, err)
	}
	klog.V(4).Infof("iscsi: %q is unmounted, deleting the directory", mapPath)
	err = os.RemoveAll(mapPath)
	if err != nil {
		return fmt.Errorf("iscsi: failed to delete the directory: %s\nError: %v", mapPath, err)
	}
	klog.V(4).Infof("iscsi: successfully detached disk: %s", mapPath)
	return nil
}

// GetGlobalMapPath returns global map path and error
// path: plugins/kubernetes.io/{PluginName}/volumeDevices/{ifaceName}/{portal-some_iqn-lun-lun_id}
func (iscsi *iscsiDisk) GetGlobalMapPath(spec *volume.Spec) (string, error) {
	return iscsi.iscsiGlobalMapPath(spec)
}

// GetPodDeviceMapPath returns pod device map path and volume name
// path: pods/{podUid}/volumeDevices/kubernetes.io~iscsi
// volumeName: pv0001
func (iscsi *iscsiDisk) GetPodDeviceMapPath() (string, string) {
	return iscsi.iscsiPodDeviceMapPath()
}

func portalMounter(portal string) string {
	if !strings.Contains(portal, ":") {
		portal = portal + ":3260"
	}
	return portal
}

// get iSCSI volume info: readOnly and fstype
func getISCSIVolumeInfo(spec *volume.Spec) (bool, string, error) {
	// for volume source, readonly is in volume spec
	// for PV, readonly is in PV spec. PV gets the ReadOnly flag indirectly through the PVC source
	if spec.Volume != nil && spec.Volume.ISCSI != nil {
		return spec.Volume.ISCSI.ReadOnly, spec.Volume.ISCSI.FSType, nil
	} else if spec.PersistentVolume != nil &&
		spec.PersistentVolume.Spec.ISCSI != nil {
		return spec.ReadOnly, spec.PersistentVolume.Spec.ISCSI.FSType, nil
	}

	return false, "", fmt.Errorf("Spec does not reference an ISCSI volume type")
}

// get iSCSI target info: target portal, portals, iqn, and lun
func getISCSITargetInfo(spec *volume.Spec) (string, []string, string, int32, error) {
	if spec.Volume != nil && spec.Volume.ISCSI != nil {
		return spec.Volume.ISCSI.TargetPortal, spec.Volume.ISCSI.Portals, spec.Volume.ISCSI.IQN, spec.Volume.ISCSI.Lun, nil
	} else if spec.PersistentVolume != nil &&
		spec.PersistentVolume.Spec.ISCSI != nil {
		return spec.PersistentVolume.Spec.ISCSI.TargetPortal, spec.PersistentVolume.Spec.ISCSI.Portals, spec.PersistentVolume.Spec.ISCSI.IQN, spec.PersistentVolume.Spec.ISCSI.Lun, nil
	}

	return "", nil, "", 0, fmt.Errorf("Spec does not reference an ISCSI volume type")
}

// get iSCSI initiator info: iface and initiator name
func getISCSIInitiatorInfo(spec *volume.Spec) (string, *string, error) {
	if spec.Volume != nil && spec.Volume.ISCSI != nil {
		return spec.Volume.ISCSI.ISCSIInterface, spec.Volume.ISCSI.InitiatorName, nil
	} else if spec.PersistentVolume != nil &&
		spec.PersistentVolume.Spec.ISCSI != nil {
		return spec.PersistentVolume.Spec.ISCSI.ISCSIInterface, spec.PersistentVolume.Spec.ISCSI.InitiatorName, nil
	}

	return "", nil, fmt.Errorf("Spec does not reference an ISCSI volume type")
}

// get iSCSI Discovery CHAP boolean
func getISCSIDiscoveryCHAPInfo(spec *volume.Spec) (bool, error) {
	if spec.Volume != nil && spec.Volume.ISCSI != nil {
		return spec.Volume.ISCSI.DiscoveryCHAPAuth, nil
	} else if spec.PersistentVolume != nil &&
		spec.PersistentVolume.Spec.ISCSI != nil {
		return spec.PersistentVolume.Spec.ISCSI.DiscoveryCHAPAuth, nil
	}

	return false, fmt.Errorf("Spec does not reference an ISCSI volume type")
}

// get iSCSI Session CHAP boolean
func getISCSISessionCHAPInfo(spec *volume.Spec) (bool, error) {
	if spec.Volume != nil && spec.Volume.ISCSI != nil {
		return spec.Volume.ISCSI.SessionCHAPAuth, nil
	} else if spec.PersistentVolume != nil &&
		spec.PersistentVolume.Spec.ISCSI != nil {
		return spec.PersistentVolume.Spec.ISCSI.SessionCHAPAuth, nil
	}

	return false, fmt.Errorf("Spec does not reference an ISCSI volume type")
}

// get iSCSI CHAP Secret info: secret name and namespace
func getISCSISecretNameAndNamespace(spec *volume.Spec, defaultSecretNamespace string) (string, string, error) {
	if spec.Volume != nil && spec.Volume.ISCSI != nil {
		if spec.Volume.ISCSI.SecretRef != nil {
			return spec.Volume.ISCSI.SecretRef.Name, defaultSecretNamespace, nil
		}
		return "", "", nil
	} else if spec.PersistentVolume != nil &&
		spec.PersistentVolume.Spec.ISCSI != nil {
		secretRef := spec.PersistentVolume.Spec.ISCSI.SecretRef
		secretNs := defaultSecretNamespace
		if secretRef != nil {
			if len(secretRef.Namespace) != 0 {
				secretNs = secretRef.Namespace
			}
			return secretRef.Name, secretNs, nil
		}
		return "", "", nil
	}

	return "", "", fmt.Errorf("Spec does not reference an ISCSI volume type")
}

func createISCSIDisk(spec *volume.Spec, podUID types.UID, plugin *iscsiPlugin, manager diskManager, secret map[string]string) (*iscsiDisk, error) {
	tp, portals, iqn, lunStr, err := getISCSITargetInfo(spec)
	if err != nil {
		return nil, err
	}

	lun := strconv.Itoa(int(lunStr))
	portal := portalMounter(tp)
	var bkportal []string
	bkportal = append(bkportal, portal)
	for _, p := range portals {
		bkportal = append(bkportal, portalMounter(string(p)))
	}

	iface, initiatorNamePtr, err := getISCSIInitiatorInfo(spec)
	if err != nil {
		return nil, err
	}

	var initiatorName string
	if initiatorNamePtr != nil {
		initiatorName = *initiatorNamePtr
	}
	chapDiscovery, err := getISCSIDiscoveryCHAPInfo(spec)
	if err != nil {
		return nil, err
	}
	chapSession, err := getISCSISessionCHAPInfo(spec)
	if err != nil {
		return nil, err
	}

	return &iscsiDisk{
		podUID:        podUID,
		VolName:       spec.Name(),
		Portals:       bkportal,
		Iqn:           iqn,
		Lun:           lun,
		Iface:         iface,
		chapDiscovery: chapDiscovery,
		chapSession:   chapSession,
		secret:        secret,
		InitiatorName: initiatorName,
		manager:       manager,
		plugin:        plugin}, nil
}

func createSecretMap(spec *volume.Spec, plugin *iscsiPlugin, namespace string) (map[string]string, error) {
	var secret map[string]string
	chapDiscover, err := getISCSIDiscoveryCHAPInfo(spec)
	if err != nil {
		return nil, err
	}
	chapSession, err := getISCSISessionCHAPInfo(spec)
	if err != nil {
		return nil, err
	}
	if chapDiscover || chapSession {
		secretName, secretNamespace, err := getISCSISecretNameAndNamespace(spec, namespace)
		if err != nil {
			return nil, err
		}

		if len(secretName) > 0 && len(secretNamespace) > 0 {
			// if secret is provideded, retrieve it
			kubeClient := plugin.host.GetKubeClient()
			if kubeClient == nil {
				return nil, fmt.Errorf("Cannot get kube client")
			}
			secretObj, err := kubeClient.CoreV1().Secrets(secretNamespace).Get(secretName, metav1.GetOptions{})
			if err != nil {
				err = fmt.Errorf("Couldn't get secret %v/%v error: %v", secretNamespace, secretName, err)
				return nil, err
			}
			secret = make(map[string]string)
			for name, data := range secretObj.Data {
				klog.V(4).Infof("retrieving CHAP secret name: %s", name)
				secret[name] = string(data)
			}
		}
	}
	return secret, err
}

func createVolumeFromISCSIVolumeSource(volumeName string, iscsi v1.ISCSIVolumeSource) *v1.Volume {
	return &v1.Volume{
		Name: volumeName,
		VolumeSource: v1.VolumeSource{
			ISCSI: &iscsi,
		},
	}
}

func createPersistentVolumeFromISCSIPVSource(volumeName string, iscsi v1.ISCSIPersistentVolumeSource) *v1.PersistentVolume {
	block := v1.PersistentVolumeBlock
	return &v1.PersistentVolume{
		ObjectMeta: metav1.ObjectMeta{
			Name: volumeName,
		},
		Spec: v1.PersistentVolumeSpec{
			PersistentVolumeSource: v1.PersistentVolumeSource{
				ISCSI: &iscsi,
			},
			VolumeMode: &block,
		},
	}
}

func getVolumeSpecFromGlobalMapPath(volumeName, globalMapPath string) (*volume.Spec, error) {
	// Retrieve volume spec information from globalMapPath
	// globalMapPath example:
	// plugins/kubernetes.io/{PluginName}/{DefaultKubeletVolumeDevicesDirName}/{volumePluginDependentPath}
	// plugins/kubernetes.io/iscsi/volumeDevices/iface-default/192.168.0.10:3260-iqn.2017-05.com.example:test-lun-0

	// device: 192.168.0.10:3260-iqn.2017-05.com.example:test-lun-0
	device, _, err := extractDeviceAndPrefix(globalMapPath)
	if err != nil {
		return nil, err
	}
	bkpPortal, iqn, err := extractPortalAndIqn(device)
	if err != nil {
		return nil, err
	}
	arr := strings.Split(device, "-lun-")
	if len(arr) < 2 {
		return nil, fmt.Errorf("failed to retrieve lun from globalMapPath: %v", globalMapPath)
	}
	lun, err := strconv.Atoi(arr[1])
	if err != nil {
		return nil, err
	}
	iface, found := extractIface(globalMapPath)
	if !found {
		return nil, fmt.Errorf("failed to retrieve iface from globalMapPath: %v", globalMapPath)
	}
	iscsiPV := createPersistentVolumeFromISCSIPVSource(volumeName,
		v1.ISCSIPersistentVolumeSource{
			TargetPortal:   bkpPortal,
			IQN:            iqn,
			Lun:            int32(lun),
			ISCSIInterface: iface,
		},
	)
	klog.V(5).Infof("ConstructBlockVolumeSpec: TargetPortal: %v, IQN: %v, Lun: %v, ISCSIInterface: %v",
		iscsiPV.Spec.PersistentVolumeSource.ISCSI.TargetPortal,
		iscsiPV.Spec.PersistentVolumeSource.ISCSI.IQN,
		iscsiPV.Spec.PersistentVolumeSource.ISCSI.Lun,
		iscsiPV.Spec.PersistentVolumeSource.ISCSI.ISCSIInterface,
	)
	return volume.NewSpecFromPersistentVolume(iscsiPV, false), nil
}