text:
package leoisasmendi.android.com.suricatepodcast.services;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.session.MediaSessionManager;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.content.ContextCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v7.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.RemoteViews;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import leoisasmendi.android.com.suricatepodcast.MainActivity;
import leoisasmendi.android.com.suricatepodcast.R;
import leoisasmendi.android.com.suricatepodcast.data.PlaylistItem;
import leoisasmendi.android.com.suricatepodcast.provider.DataProvider;
import leoisasmendi.android.com.suricatepodcast.utils.ParserUtils;
import leoisasmendi.android.com.suricatepodcast.utils.PlaybackStatus;
import leoisasmendi.android.com.suricatepodcast.utils.StorageUtil;
import leoisasmendi.android.com.suricatepodcast.widget.PodcastWidgetProvider;

public class MediaPlayerService extends Service implements MediaPlayer.OnCompletionListener,
        MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener,
        MediaPlayer.OnInfoListener, MediaPlayer.OnBufferingUpdateListener,
        AudioManager.OnAudioFocusChangeListener {

    private final String TAG = getClass().getSimpleName();

    // Binder given to clients
    private final IBinder iBinder = new LocalBinder();
    private MediaPlayer mediaPlayer;
    //Used to pause/resume MediaPlayer
    private int resumePosition;
    private AudioManager audioManager;

    //Handle incoming phone calls
    private boolean ongoingCall = false;
    private PhoneStateListener phoneStateListener;
    private TelephonyManager telephonyManager;

    //List of available Audio files
    private int audioIndex = -1;
    private PlaylistItem activeAudio; //an object of the currently playing audio
    private Cursor mCursor;

    private BroadcastReceiver playNewAudio = getNewAudioBroadcastReceiver();
    //Becoming noisy (headphone removed)
    private BroadcastReceiver becomingNoisyReceiver = getBecomingNoisyReceiver();

    public static final String ACTION_PLAY = "leoisasmendi.android.com.suricatepodcast.ACTION_PLAY";
    public static final String ACTION_PAUSE = "leoisasmendi.android.com.suricatepodcast.ACTION_PAUSE";
    public static final String ACTION_PREVIOUS = "leoisasmendi.android.com.suricatepodcast.ACTION_PREVIOUS";
    public static final String ACTION_NEXT = "leoisasmendi.android.com.suricatepodcast.ACTION_NEXT";
    public static final String ACTION_STOP = "leoisasmendi.android.com.suricatepodcast.ACTION_STOP";

    public static final String STATUS_ERROR = "leoisasmendi.android.com.suricatepodcast.STATUS_ERROR";
    public static final String STATUS_DONE = "leoisasmendi.android.com.suricatepodcast.STATUS_DONE";
    public static final String STATUS_FETCHING = "leoisasmendi.android.com.suricatepodcast.STATUS_FETCHING";

    public static final String STATUS_PLAYING = "leoisasmendi.android.com.suricatepodcast.STATUS_PLAYING";
    public static final String STATUS_STOPED = "leoisasmendi.android.com.suricatepodcast.STATUS_STOPED";
    public static final String STATUS_PAUSED = "leoisasmendi.android.com.suricatepodcast.STATUS_PAUSED";
    public static final String MEDIA_UPDATED = "leoisasmendi.android.com.suricatepodcast.MEDIA_UPDATED";
    public static final String NOTIFICATION = "leoisasmendi.android.com.suricatepodcast";
    public static final String STATUS = "status";

    //MediaSession
    private MediaSessionManager mediaSessionManager;
    private MediaSessionCompat mediaSession;
    private MediaControllerCompat.TransportControls transportControls;

    //AudioPlayer notification ID
    private static final int NOTIFICATION_ID = 101;

    public MediaPlayerService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // Perform one-time setup procedures

        mCursor = getContentResolver().query(DataProvider.CONTENT_URI,
                null,
                "",
                null,
                null);
        // Manage incoming phone calls during playback.
        // Pause MediaPlayer on incoming call,
        // Resume on hangup.
        callStateListener();
        //ACTION_AUDIO_BECOMING_NOISY -- change in audio outputs -- BroadcastReceiver
        registerBecomingNoisyReceiver();
        //Listen for new Audio to play -- BroadcastReceiver
        register_playNewAudio();
    }

    private void initMediaPlayer() {
        mediaPlayer = new MediaPlayer();
        //Set up MediaPlayer event listeners
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnErrorListener(this);
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnBufferingUpdateListener(this);
        mediaPlayer.setOnSeekCompleteListener(this);
        mediaPlayer.setOnInfoListener(this);
        //Reset so that the MediaPlayer is not pointing to another data source
        mediaPlayer.reset();

        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            publishStatus(STATUS_FETCHING);
            // Set the data source to the mediaFile location
            mediaPlayer.setDataSource(activeAudio.getAudio());
            mediaPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
            publishStatus(STATUS_ERROR);
            stopSelf();
            Log.d(TAG, "initMediaPlayer: " + R.string.media_player_error_1);
        }
    }

    private void initMediaSession() throws RemoteException {
        if (mediaSessionManager != null) return; //mediaSessionManager exists

        mediaSessionManager = (MediaSessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE);
        // Create a new MediaSession
        mediaSession = new MediaSessionCompat(getApplicationContext(), "AudioPlayer");
        //Get MediaSessions transport controls
        transportControls = mediaSession.getController().getTransportControls();
        //set MediaSession -> ready to receive media commands
        mediaSession.setActive(true);
        //indicate that the MediaSession handles transport control commands
        // through its MediaSessionCompat.Callback.
        mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);

        //Set mediaSession's MetaData
        updateMetaData();

        // Attach Callback to receive MediaSession updates
        mediaSession.setCallback(new MediaSessionCompat.Callback() {
            // Implement callbacks
            @Override
            public void onPlay() {
                super.onPlay();
                resumeMedia();
                publishStatus(STATUS_PLAYING);
                buildNotification(PlaybackStatus.PLAYING);
            }

            @Override
            public void onPause() {
                super.onPause();
                pauseMedia();
                publishStatus(STATUS_PAUSED);
                buildNotification(PlaybackStatus.PAUSED);
            }

            @Override
            public void onSkipToNext() {
                super.onSkipToNext();
                skipToNext();
                updateMetaData();
                buildNotification(PlaybackStatus.PLAYING);
            }

            @Override
            public void onSkipToPrevious() {
                super.onSkipToPrevious();
                skipToPrevious();
                updateMetaData();
                buildNotification(PlaybackStatus.PLAYING);
            }

            @Override
            public void onStop() {
                super.onStop();
                publishStatus(STATUS_STOPED);
                removeNotification();
                //Stop the service
                stopSelf();
            }

        });
    }

    private void publishStatus(String status) {
        Intent intent = new Intent(NOTIFICATION);
        if (status.equals(MEDIA_UPDATED)) {
            intent.putExtra("EXTRA_TITLE", activeAudio.getTitle());
            intent.putExtra("EXTRA_DURATION", activeAudio.getDuration());
        }
        intent.putExtra(STATUS, status);
        sendBroadcast(intent);
    }

    private void updateMetaData() {

        if (activeAudio != null) {
            Bitmap albumArt = BitmapFactory.decodeResource(getResources(),
                    R.drawable.ic_default_poster); //replace with medias albumArt
            // Update the current metadata
            mediaSession.setMetadata(new MediaMetadataCompat.Builder()
                    .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, albumArt)
                    .putString(MediaMetadataCompat.METADATA_KEY_TITLE, activeAudio.getTitle())
                    .build());
        }

    }

    private void buildNotification(PlaybackStatus playbackStatus) {

        //TODO: REFACTOR updateWidget method
        updateWidgets(playbackStatus);

        int notificationAction = R.drawable.ic_media_control_pause;//needs to be initialized
        PendingIntent play_pauseAction = null;

        //Build a new notification according to the current state of the MediaPlayer
        if (playbackStatus == PlaybackStatus.PLAYING) {
            notificationAction = R.drawable.ic_media_control_pause;
            //create the pause action
            play_pauseAction = playbackAction(1);
        } else if (playbackStatus == PlaybackStatus.PAUSED) {
            notificationAction = R.drawable.ic_media_control_play;
            //create the play action
            play_pauseAction = playbackAction(0);
        }

        //TODO: replace this with my icon
        Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),
                R.drawable.ic_default_poster); //replace with your own image

        // Create a new Notification
        NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setShowWhen(false)
                // Set the Notification style
                .setStyle(new NotificationCompat.MediaStyle()
                        // Attach our MediaSession token
                        .setMediaSession(mediaSession.getSessionToken())
                        // Show our playback controls in the compact notification view.
                        .setShowActionsInCompactView(0, 1, 2))
                // Set the Notification color
                .setColor(ContextCompat.getColor(getBaseContext(), R.color.colorPrimaryDark))
                // Set the large and small icons
                .setLargeIcon(largeIcon)
                .setSmallIcon(R.drawable.ic_headphones)
                // Set Notification content information
                .setContentText(activeAudio.getTitle())
                // Add playback actions
                .addAction(R.drawable.ic_media_control_prev, "previous", playbackAction(3))
                .addAction(notificationAction, "pause", play_pauseAction)
                .addAction(R.drawable.ic_media_control_next, "next", playbackAction(2));

        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFICATION_ID, notificationBuilder.build());
    }

    private void updateWidgets(PlaybackStatus playbackStatus) {

        final RemoteViews view = new RemoteViews(getPackageName(), R.layout.podcast_widget_player);

        if (playbackStatus == PlaybackStatus.PLAYING) {
            view.setImageViewResource(R.id.widget_play, R.drawable.media_player_pause_24x24);
        } else if (playbackStatus == PlaybackStatus.PAUSED) {
            view.setImageViewResource(R.id.widget_play, R.drawable.media_player_play_24x24);
        }

        view.setTextViewText(R.id.widget_title, activeAudio.getTitle());
        view.setTextViewText(R.id.widget_length, activeAudio.getDuration());

        Picasso.with(getBaseContext()).setLoggingEnabled(true);

        Target target = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                view.setImageViewBitmap(R.id.widget_thumbail, bitmap);
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
                view.setImageViewResource(R.id.widget_thumbail, R.drawable.picture);
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
                view.setImageViewResource(R.id.widget_thumbail, R.drawable.picture);
            }
        };

        Picasso.with(getBaseContext())
                .load(activeAudio.getPoster())
                .into(target);

        // Push update for this widget to the home screen
        ComponentName thisWidget = new ComponentName(this, PodcastWidgetProvider.class);
        AppWidgetManager manager = AppWidgetManager.getInstance(this);
        manager.updateAppWidget(thisWidget, view);
    }

    private void removeNotification() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(NOTIFICATION_ID);
    }

    private PendingIntent playbackAction(int actionNumber) {
        Intent playbackAction = new Intent(this, MediaPlayerService.class);
        switch (actionNumber) {
            case 0:
                // Play
                playbackAction.setAction(ACTION_PLAY);
                return PendingIntent.getService(this, actionNumber, playbackAction, 0);
            case 1:
                // Pause
                playbackAction.setAction(ACTION_PAUSE);
                return PendingIntent.getService(this, actionNumber, playbackAction, 0);
            case 2:
                // Next track
                playbackAction.setAction(ACTION_NEXT);
                return PendingIntent.getService(this, actionNumber, playbackAction, 0);
            case 3:
                // Previous track
                playbackAction.setAction(ACTION_PREVIOUS);
                return PendingIntent.getService(this, actionNumber, playbackAction, 0);
            default:
                break;
        }
        return null;
    }

    private void handleIncomingActions(Intent playbackAction) {
        if (playbackAction == null || playbackAction.getAction() == null) return;

        String actionString = playbackAction.getAction();
        if (actionString.equalsIgnoreCase(ACTION_PLAY)) {
            transportControls.play();
        } else if (actionString.equalsIgnoreCase(ACTION_PAUSE)) {
            transportControls.pause();
        } else if (actionString.equalsIgnoreCase(ACTION_NEXT)) {
            transportControls.skipToNext();
        } else if (actionString.equalsIgnoreCase(ACTION_PREVIOUS)) {
            transportControls.skipToPrevious();
        } else if (actionString.equalsIgnoreCase(ACTION_STOP)) {
            transportControls.stop();
        }
    }

    private void loadActiveAudio() {

        if (audioIndex != -1 && audioIndex < mCursor.getCount()) {
            //index is in a valid range
            mCursor.moveToPosition(audioIndex);
            activeAudio = ParserUtils.buildPlaylistItem(mCursor);
        } else {
            stopSelf();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return iBinder;
    }

    //The system calls this method when an activity, requests the service be started
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            //Load data from SharedPreferences
            StorageUtil storage = new StorageUtil(getApplicationContext());
            audioIndex = storage.loadAudioIndex();
            Log.d(TAG, "onStartCommand: " + R.string.media_player_connecting);
            loadActiveAudio();

        } catch (NullPointerException e) {
            Log.d(TAG, "onStartCommand: " + R.string.media_player_error_1);
            stopSelf();
        }

        //Request audio focus
        if (!requestAudioFocus()) {
            //Could not gain focus
            stopSelf();
        }

        if (mediaSessionManager == null) {
            try {
                initMediaSession();
                initMediaPlayer();
            } catch (RemoteException e) {
                e.printStackTrace();
                stopSelf();
            }
            buildNotification(PlaybackStatus.PLAYING);
        }

        //Handle Intent action from MediaSession.TransportControls
        handleIncomingActions(intent);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            stopMedia();
            mediaPlayer.release();
        }
        removeAudioFocus();
        //Disable the PhoneStateListener
        if (phoneStateListener != null) {
            telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
        }

        removeNotification();

        //unregister BroadcastReceivers
        unregisterReceiver(becomingNoisyReceiver);
        unregisterReceiver(playNewAudio);

        //clear cached playlist
        new StorageUtil(getApplicationContext()).clearCachedAudioPlaylist();
        mCursor.close();
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
        //Invoked indicating buffering status of
        //a media resource being streamed over the network.
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        //Invoked when playback of a media source has completed.
        stopMedia();
        //stop the service
        stopSelf();
    }

    //Handle errors
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        //Invoked when there has been an error during an asynchronous operation
        Log.d(TAG, "onError: " + R.string.media_player_error_2);
        switch (what) {
            case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
                Log.d("MediaPlayer Error", "MEDIA ERROR NOT VALID FOR PROGRESSIVE PLAYBACK " + extra);
                break;
            case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
                Log.d("MediaPlayer Error", "MEDIA ERROR SERVER DIED " + extra);
                break;
            case MediaPlayer.MEDIA_ERROR_UNKNOWN:
                Log.d("MediaPlayer Error", "MEDIA ERROR UNKNOWN " + extra);
                break;
        }
        return false;
    }

    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        //Invoked to communicate some info.
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        //Invoked when the media source is ready for playback.
        Log.d(TAG, "onPrepared: " + R.string.media_player_successful_fetch);
        publishStatus(STATUS_DONE);
        playMedia();
    }

    @Override
    public void onSeekComplete(MediaPlayer mp) {
        //Invoked indicating the completion of a seek operation.
    }

    @Override
    public void onAudioFocusChange(int focusState) {
        //Invoked when the audio focus of the system is updated.
        switch (focusState) {
            case AudioManager.AUDIOFOCUS_GAIN:
                // resume playback
                if (mediaPlayer == null) initMediaPlayer();
                else if (!mediaPlayer.isPlaying()) mediaPlayer.start();
                mediaPlayer.setVolume(1.0f, 1.0f);
                break;
            case AudioManager.AUDIOFOCUS_LOSS:
                // Lost focus for an unbounded amount of time: stop playback and release media player
                if (mediaPlayer.isPlaying()) mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
                break;
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                // Lost focus for a short time, but we have to stop
                // playback. We don't release the media player because playback
                // is likely to resume
                if (mediaPlayer.isPlaying()) mediaPlayer.pause();
                break;
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                // Lost focus for a short time, but it's ok to keep playing
                // at an attenuated level
                if (mediaPlayer.isPlaying()) mediaPlayer.setVolume(0.1f, 0.1f);
                break;
        }
    }

    private boolean requestAudioFocus() {
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            //Focus gained
            return true;
        }
        //Could not gain focus
        return false;
    }

    private boolean removeAudioFocus() {
        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED ==
                audioManager.abandonAudioFocus(this);
    }

    private BroadcastReceiver getNewAudioBroadcastReceiver() {
        return new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                //Get the new media index form SharedPreferences
                audioIndex = new StorageUtil(getApplicationContext()).loadAudioIndex();
                loadActiveAudio();

                //A PLAY_NEW_AUDIO action received
                //reset mediaPlayer to play the new Audio
                stopMedia();
                mediaPlayer.reset();
                initMediaPlayer();
                updateMetaData();
                buildNotification(PlaybackStatus.PLAYING);
            }
        };
    }

    private void register_playNewAudio() {
        //Register playNewMedia receiver
        IntentFilter filter = new IntentFilter(MainActivity.Broadcast_PLAY_NEW_AUDIO);
        registerReceiver(playNewAudio, filter);
    }

    //Handle incoming phone calls
    private void callStateListener() {
        // Get the telephony manager
        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        //Starting listening for PhoneState changes
        phoneStateListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                switch (state) {
                    //if at least one call exists or the phone is ringing
                    //pause the MediaPlayer
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                    case TelephonyManager.CALL_STATE_RINGING:
                        if (mediaPlayer != null) {
                            pauseMedia();
                            ongoingCall = true;
                        }
                        break;
                    case TelephonyManager.CALL_STATE_IDLE:
                        // Phone idle. Start playing.
                        if (mediaPlayer != null) {
                            if (ongoingCall) {
                                ongoingCall = false;
                                resumeMedia();
                            }
                        }
                        break;
                }
            }
        };
        // Register the listener with the telephony manager
        // Listen for changes to the device call state.
        telephonyManager.listen(phoneStateListener,
                PhoneStateListener.LISTEN_CALL_STATE);
    }

    //Becoming noisy (headphone removed)
    private BroadcastReceiver getBecomingNoisyReceiver() {
        return new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //pause audio on ACTION_AUDIO_BECOMING_NOISY
                pauseMedia();
                buildNotification(PlaybackStatus.PAUSED);
            }
        };
    }

    private void registerBecomingNoisyReceiver() {
        //register after getting audio focus
        IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
        registerReceiver(becomingNoisyReceiver, intentFilter);
    }

    //MEDIA PLAYER BASIC CONTROLS

    private void playMedia() {
        if (!mediaPlayer.isPlaying()) {
            Log.d(TAG, "playMedia: " + R.string.media_player_playing);
            mediaPlayer.start();
            publishStatus(MEDIA_UPDATED);
            publishStatus(STATUS_PLAYING);
        }
    }

    private void stopMedia() {
        if (mediaPlayer == null) return;
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            publishStatus(STATUS_STOPED);
        }
    }

    private void pauseMedia() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            resumePosition = mediaPlayer.getCurrentPosition();
            publishStatus(STATUS_PAUSED);
        }
    }

    private void resumeMedia() {
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.seekTo(resumePosition);
            mediaPlayer.start();
            publishStatus(STATUS_PLAYING);
        }
    }

    private void skipToNext() {

        if (audioIndex == mCursor.getCount() - 1) {
            //if last in playlist
            audioIndex = 0;
        } else {
            //get next in playlist
            audioIndex = ++audioIndex;
        }

        loadActiveAudio();
        //Update stored index
        new StorageUtil(getApplicationContext()).storeAudioIndex(audioIndex);
        stopMedia();
        //reset mediaPlayer
        mediaPlayer.reset();
        initMediaPlayer();
    }

    private void skipToPrevious() {

        if (audioIndex == 0) {
            audioIndex = mCursor.getCount() - 1;
        } else {
            audioIndex = --audioIndex;
        }

        loadActiveAudio();
        //Update stored index
        new StorageUtil(getApplicationContext()).storeAudioIndex(audioIndex);
        stopMedia();
        //reset mediaPlayer
        mediaPlayer.reset();
        initMediaPlayer();
    }

    // INNER CLASS
    public class LocalBinder extends Binder {
        public MediaPlayerService getService() {
            return MediaPlayerService.this;
        }
    }
}


text:
MYHOME=hdfs:///user/crogers

INFILE=${MYHOME}/hbase-dump-2015-10-01-2015-12-01-aman-webpage-descriptions-tokens.seq
FEATURES=features.hair-eye
MODEL=dig-hair-eye-train.model
OUTDIR=hbase-dump-2015-10-01-2015-12-01-aman-webpage-crf-hair-eyes.seq
NUM_EXECUTORS=350

source ${DIG_CRF_HOME}/checkMemexConnection.sh
${DIG_CRF_HOME}/buildPythonFiles.sh
source ${DIG_CRF_HOME}/limitMemexExecutors.sh

PYTHON_EGG_CACHE=./python-eggs
export PYTHON_EGG_CACHE

# Dangerous!
echo "Clearing the output folder: ${OUTDIR}"
hadoop fs -rm -r -f ${OUTDIR}

echo "Copying the feature control file and CRF model to Hadoop."
hadoop fs -copyFromLocal -f ${DIG_CRF_HOME}/data/config/$FEATURES $MYHOME/$FEATURES
hadoop fs -copyFromLocal -f ${DIG_CRF_HOME}/data/config/$MODEL $MYHOME/$MODEL

echo "Creating the Python Egg cache folder: $PYTHON_EGG_CACHE"
hadoop fs -mkdir -p $PYTHON_EGG_CACHE

echo "Submitting the job to the Memex cluster."
time spark-submit \
    --master 'yarn-client' \
    --num-executors ${NUM_EXECUTORS} \
    --py-files ${DIG_CRF_HOME}/CRF++-0.58/python/dist/mecab_python-0.0.0-py2.7-linux-x86_64.egg,${DIG_CRF_HOME}/pythonFiles.zip \
    --conf "spark.executorEnv.PYTHON_EGG_CACHE=${PYTHON_EGG_CACHE}" \
    --driver-java-options -Dlog4j.configuration=file:${DIG_CRF_HOME}/data/config/quieter-log4j.properties \
    ${DIG_CRF_HOME}/src/applyCrf/applyCrfSparkTest.py \
    -- \
    --featlist ${MYHOME}/${FEATURES} \
    --model ${MYHOME}/${MODEL} \
    --download \
    --input ${INFILE} --inputSeq --justTokens \
    --output ${MYHOME}/${OUTDIR} --outputSeq \
    --verbose

redpajama_set_name: RedPajamaGithub


text:
Hydra-DHCP
==========

Hydra, a high performance and resilient DHCP server is a research project towards a distributed and scalable
DHCP service in Erlang/OTP for next generations IPAM scenarios.

This is the source code of an Erlang/OTP application designed to function as a DHCP (Dynamic Host Configuration Protocol)
service featuring scalability and resilence thanks to the great OTP framework capabilities.

This is work in progress, yet a rebarized "shell" is provided from day one to manage the entire OTP application as a command-line
Unix program, so for the most part you only need to follow the install instructions to get a single standalone "hdcp-server" escript bundle.

As Aug'14 this project is on hold so updates will make their way on a very slow fashion.

Project status
===============

[![Build Status](https://travis-ci.org/AngelitoJ/Hydra-DHCP.svg?branch=master)](https://travis-ci.org/AngelitoJ/Hydra-DHCP)

The repository is registered on Travis-ci, so a green status means all software compile and unit tests (if any) went fine.

We will provide a stable release on reaching v 1.0.

- Escript fronted                 :
	- Command-line parsing , and complete statup and shutdoen of the bundle OTP application.

- Cross module get-opt            :
	- Gathering of options specs across all bundled modules.

- Main OTP tree                   :
	- Simple (non distributed) applicaction startup with config data provided from escript frontend.

- Console server                  :

- Table master                    :
	- Simple inheritance from process deaths, and service of ETS table identifiers to any process.

- UDP Driver                      :
	- UDP port configurable via command-line.
	- Iface and server ID configuration in progress.

- Middleman DHCP encoder / decoder:

- DORA Cache manager              :
	- Helps middlemen processes to figure out which FSM is managing client state, and also spawn new FSM on request.

- DORA DHCP State machine         :
	- Manages entire DHCP server state machine for every client. FSM can stop storing data into a suitable pool server (which also presist lease info to a DETS file).

- Address Pool Servers            :
	- 'Simple pool type' this type manages a simple range of IP's, and a list of options using a ETS table and a DETS table to persist lease information. Simple format suitable for file:consult() usage:
		- Pool name {name, "Universidad"}
    	- A range of IP's {range, {192,168,1,2}, {192,168,1,253}}
		- A list of Options
			- {lease_time, 3600}
        	- {renewal_time, 1800}
        	- {rebinding_time, 3000}
        	- {subnet_mask, {255, 255, 255, 0}}
        	- {broadcast_address, {192, 168, 1, 255}}
        	- {dns_server, {192, 168, 1, 1}}
        	- {domain_name, "uah.es"}
        	- {router, {192, 168, 1, 254}}

    - Init functions mostly finished ( file parse, load and state/tables population)

Brief Project roadmap
======================

- Basic DHCP service
	- Simple file based data backend and SQL storage backend.
	- DHCP Fingerprinting

- High Performance DHCP Service
	- Hydra mode: Serving a pool of UDP ports (on suitable platforms with iptables like capabilities)

- Distributed DHCP service
	- Master/Slave HA schemes.
	- Multimaster HA (Mnesia)

Basic application architecture
==============================
                                       [Top Supervisor]
                                              |
          --------------------------------------------------------------------------------------------
         |                        |                      |                        |                   |
    [Supervisor]            [Supervisor]           [Supervisor]             [Supervisor]         [Supervisor]
         |                        |                 |    |                        |                   |
         |                        |    Pid?         |    |                        |               [Console]
         |                        |     --->[FSM cache] [*]                       |                   |
	[UDP_SRV_SRV]                 |    |                 |                        |              [Table Heir]
	     |                  [MIDDLEMAN_SRV]          [DORA_FSM]             [ADDR_POOL_SRV]
	     |                        |                      |                        |
	      --UDP binaries--> [MIDDLEMAN_SRV]          [DORA_FSM]             [ADDR_POOL_SRV]
	                              |                      |                        |
                                  |                  [DORA_FSM]             [ADDR_POOL_SRV]
	                              |                      |                        |
	                               --Erlang Terms--> [DORA_FSM]             [ADDR_POOL_SRV]
	                                                     |                        |
	                                                     |                        |
                                                          --Erlang Terms--> [ADDR_POOL_SRV]

    [*] Simple_one_for_one Supervisor

	1. UDP_DRV_SRV
		- One per UDP port served (currently on UDP port), dispatch UDP messages between network hosts and erlang processes.
	2. MIDDLEMAN_SRV
		- At least one per core, transform UDP message into erlang terms and viceversa, and talks (async) to DORA finite state machines.
	3. DORA_FSM
		- One per active client, manage the entire DHCP exchange state machine (a.k.a DORA) and talks (sync) to pool servers
		 to get leases.
	4. ADDR_POOL_SRV
		- One per addr pool configured, manages client leases and pool policies.

	5. Miscelaneous servers.
		- Console service: frontend offering services to print all the various structures on the application.
		- Table heir:  Responsible for ets tables used across the various workers.

SYSTEM REQUIREMENTS
===================

	1. Base Operating System
		- Unix-like compatible operating systems
			- Currently tested on Mac OS X 10.8.5 (development platform)

	2. Erlang environment
		- Currently tested on Erlang R16B03-1

INSTALL
=======

	1. Get Erlang/OTP.
	2. Get rebar.
		$ git clone git://github.com/rebar/rebar.git
		$ cd rebar
		$ ./bootstrap
		Recompile: src/getopt
		...
		Recompile: src/rebar_utils
		==> rebar (compile)

		move the result rebar file to somewhere in yout $PATH

	3. Clone this repository.

	4. Build the application.

		- cd Hydra-DHCP
		- rebar clean
		- rebar compile
		- rebar escriptize

	5. Run the server

		bash-3.2$ ./dhcp_server --help

		Hydra, a high performance and resilent Erlang DHCP server.
		Copyright: 2014 Angel J. Alvarez Miguel
		Version: 0.1

		Usage: ./dhcp_server [-D <pool_dir>] [-P <procs>] [-V] [-v] [-d <debug>] [-?] [-M <middleman_pool_factor>] [-U <udp_port>]

		-D, --pooldir		Pool data directory.
		-P, --cores			Number of workers (default 2*core).
		-V, --version		Show software version.
		-v, --verbose		Show all actions performed.
		-d, --debug			Show debug info.
		-?, --help			Show this help.
		-M, --middleman		Use 1, 2 or 4 middlemen (packet processors) per core
		-U, --udp			UDP listening port.

  		Remember you need root privileges to open port 67, instead you can try something like this:

  		$ ./dhcp_server --udp 2000

  		so you dont need to be root... do you?

  		$ sudo ./dhcp_service

  		Once the server start, you should see something like this

		bash-3.2$ ./dhcp_server --timeout 10 --udp 9000

		Hydra, a high performance and resilent Erlang DHCP server.
		Copyright: 2014 Angel J. Alvarez Miguel
		Version: 0.1

		top_sup: Init, I got 5 children to spawn..
		misc_sup: Init..
		[console_srv]: Init...
		[ets_master_srv]: Init..
		[addr_pool_sup] Initiating, got 2 address pools to setup
		[addr_pool_srv_1]: Initiating pool from file ./data/pool2.dat..
		[addr_pool_srv_1]: Creating ETS pool named 'Universidad2'..
		[ets_master_srv]: Pid {<0.38.0>,#Ref<0.0.0.90>} asked for 'Universidad2', we sent not_found..
		[addr_pool_srv_1]: Creating DETS leases table named 'Universidad2.leases'..
		[addr_pool_srv_1]: Populating pool from {10,10,0,2} to {10,10,1,253}..
		[addr_pool_srv_1]: option: {lease_time,3600}
		[addr_pool_srv_1]: option: {renewal_time,1800}
		[addr_pool_srv_1]: option: {rebinding_time,3000}
		[addr_pool_srv_1]: option: {subnet_mask,{255,255,254,0}}
		[addr_pool_srv_1]: option: {dns_server,{192,168,1,1}}
		[addr_pool_srv_1]: option: {domain_name,"uah.es"}
		[addr_pool_srv_1]: option: {router,{10,10,1,254}}
		[addr_pool_srv_1]: Transferring client leases to ETS pool.
		[addr_pool_srv_2]: Initiating pool from file ./data/pool1.dat..
		[addr_pool_srv_2]: Creating ETS pool named 'Universidad'..
		[ets_master_srv]: Pid {<0.44.0>,#Ref<0.0.0.129>} asked for 'Universidad', we sent not_found..
		[addr_pool_srv_2]: Creating DETS leases table named 'Universidad.leases'..
		[addr_pool_srv_2]: Populating pool from {192,168,1,2} to {192,168,1,253}..
		[addr_pool_srv_2]: option: {lease_time,3600}
		[addr_pool_srv_2]: option: {renewal_time,1800}
		[addr_pool_srv_2]: option: {rebinding_time,3000}
		[addr_pool_srv_2]: option: {subnet_mask,{255,255,255,0}}
		[addr_pool_srv_2]: option: {broadcast_address,{192,168,1,255}}
		[addr_pool_srv_2]: option: {dns_server,{192,168,1,1}}
		[addr_pool_srv_2]: option: {domain_name,"uah.es"}
		[addr_pool_srv_2]: option: {router,{192,168,1,254}}
		[addr_pool_srv_2]: Transferring client leases to ETS pool.
		dora_cache_sup: Init..
		dora_cache_srv: Init..
		[dora_dyn_sup]: Init..
		[middleman_sup]: Init.. I got 4 children to spawn
		[middleman_srv_1]: Init..
		[middleman_srv_2]: Init..
		[middleman_srv_3]: Init..
		[middleman_srv_4]: Init..
		network_sup: Init..
		udp_driver_srv: Init..
		udp_driver_srv: I got 4 middleman pids..
		udp_driver_srv: Opening UPD port 9000..
		Application started...

		[MAIN] Application Timeout
		Application stopped...

Authors
=======

- Angel J. Alvarez Miguel <angeljalvarezmiguel at gmail dot com>

References
==========

- "Erlang Programming", Cesarini, Thompson, 2009, O'Reilly.
- "The DHCP Handbook 2nd Ed.", Droms n Lemon, 2003, Sams.
- "IP ADDRESS MANAGEMENT Principles and Practice", Rooney, 2011, IEEE Press.
- RFC 2131, 6361


text:
This is the server side. There are just three files here:

app.js - sets up the application

api.js - a module implementing the API

schemas.js - mongoose schemas.


text:
namespace JetBlack.Diagnostics.Monitoring
{
    /// <summary>
    /// Describes a class which manages composite performance counter.
    ///
    /// Composite counters are typically used to monitor changes: e.g. average time spent.
    /// </summary>
    public interface ICompositeCounter : ICounter
    {
        /// <summary>
        /// The base performance counter.
        /// </summary>
        IPerformanceCounter CounterBase { get; }
    }
}


text:
namespace frm {

////////////////////////////////////////////////////////////////////////////////
// Serializer
// Base class for serialization handlers. A set of Serialize() free functions
// are also provided which implicitly log an error if the serialization fails.
////////////////////////////////////////////////////////////////////////////////
class Serializer
{
public:
	enum Mode
	{
		Mode_Read,
		Mode_Write
	};

	Mode                getMode() const                              { return m_mode;  }
	void                setMode(Mode _mode)                          { onModeChange(_mode); m_mode = _mode; }
	const char*         getError() const                             { return m_errStr.isEmpty() ? nullptr : (const char*)m_errStr; }
	void                setError(const char* _msg, ...);

	// Return false if _name is not found, or if the end of the current object is reached. If in an object/array and _name is not specified,
	// advance to the next element.
	virtual bool        beginObject(const char* _name = nullptr) = 0;
	virtual void        endObject() = 0;

	// Return false if _name is not found, or if the end of the current array is reached. If in an object/array and _name is not specified,
	// advance to the next element.
	virtual bool        beginArray(uint& _length_, const char* _name = nullptr) = 0;
	virtual void        endArray() = 0;

	// Variant for fixed-sized arrays or cases where _length_ isn't required.
	bool                beginArray(const char* _name = nullptr)      { uint n = 0; return beginArray(n, _name); }

	// Get the name of the current value. Return "" if the current value is an array member.
	virtual const char* getName() const = 0;

	// Get the index of the current value.
	virtual uint32      getIndex() const = 0;

	// Serialize a value. If in an object/array and _name is not specified, advance to the next element.
	virtual bool        value(bool&       _value_, const char* _name = nullptr) = 0;
	virtual bool        value(sint8&      _value_, const char* _name = nullptr) = 0;
	virtual bool        value(uint8&      _value_, const char* _name = nullptr) = 0;
	virtual bool        value(sint16&     _value_, const char* _name = nullptr) = 0;
	virtual bool        value(uint16&     _value_, const char* _name = nullptr) = 0;
	virtual bool        value(sint32&     _value_, const char* _name = nullptr) = 0;
	virtual bool        value(uint32&     _value_, const char* _name = nullptr) = 0;
	virtual bool        value(sint64&     _value_, const char* _name = nullptr) = 0;
	virtual bool        value(uint64&     _value_, const char* _name = nullptr) = 0;
	virtual bool        value(float32&    _value_, const char* _name = nullptr) = 0;
	virtual bool        value(float64&    _value_, const char* _name = nullptr) = 0;
	virtual bool        value(StringBase& _value_, const char* _name = nullptr) = 0;

	// vec* and mat* variants are implemented in terms of beginArray/endArray and value(float&).
	bool                value(vec2& _value_, const char* _name = nullptr);
	bool                value(vec3& _value_, const char* _name = nullptr);
	bool                value(vec4& _value_, const char* _name = nullptr);
	bool                value(mat2& _value_, const char* _name = nullptr);
	bool                value(mat3& _value_, const char* _name = nullptr);
	bool                value(mat4& _value_, const char* _name = nullptr);

	// Helper to avoid explicit cast to StringBase&.
	template <uint kCapacity>
	bool                value(String<kCapacity>& _value_, const char* _name = nullptr)
	{
		 return value((StringBase&)_value_, _name);
	}

	// Directly serialize bytes of binary data with optional compression. When reading, _data_ will be allocated by the function if null, and
	// should subsequently be released via FRM_FREE().
	virtual bool        binary(
		void*&           _data_,
		uint&            _sizeBytes_,
		const char*      _name = nullptr,
		CompressionFlags _compressionFlags = CompressionFlags_None
		) = 0;

	// Return tType as a string.
	template <typename tType>
	static const char* ValueTypeToStr();

protected:
	Mode m_mode;

	Serializer(Mode _mode)
		: m_mode(_mode)
	{
	}
	virtual ~Serializer()
	{
	}

	virtual void onModeChange(Mode _mode)
	{
	}

private:
	String<64> m_errStr;

}; // class Serializer

// Serialize* variants implicitly log an error if _serializer_.value() returns false.
bool Serialize(Serializer& _serializer_, bool&        _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, sint8&       _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, uint8&       _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, sint16&      _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, uint16&      _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, sint32&      _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, uint32&      _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, sint64&      _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, uint64&      _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, float32&     _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, float64&     _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, StringBase&  _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, vec2&        _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, vec3&        _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, vec4&        _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, mat2&        _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, mat3&        _value_, const char* _name = nullptr);
bool Serialize(Serializer& _serializer_, mat4&        _value_, const char* _name = nullptr);
template <uint kCapacity>
bool Serialize(Serializer& _serializer_, String<kCapacity>& _value_, const char* _name = nullptr)
{
	return Serialize(_serializer_, (StringBase&)_value_, _name);
}

// Helper for the common case of serializing an enum to/from a const char*.
template <typename tType, int kCount>
bool SerializeEnum(Serializer& _serializer_, tType& _value_, const char* (&_strList)[kCount], const char* _name = nullptr)
{
	String<32> tmp;
	if (_serializer_.getMode() == Serializer::Mode_Write) {
		FRM_ASSERT((int)_value_ < kCount);
		tmp = _strList[(int)_value_];
	}
	bool ret = Serialize(_serializer_, (StringBase&)tmp, _name);
	if (ret && _serializer_.getMode() == Serializer::Mode_Read) {
		int i = 0;
		for (; i < kCount; ++i) {
			if (tmp == _strList[i]) {
				_value_ = (tType)i;
				break;
			}
		}
		if (i == kCount) {
			_serializer_.setError("Error serializing enum; '%s' not valid", (const char*)tmp);
			ret = false;
		}
	}
	return ret;
}

// Helper for serializing bitflags to individual bools.
template <typename tEnumType>
bool Serialize(Serializer& _serializer_, BitFlags<tEnumType>& _bitFlags_, const char* (&_strList)[BitFlags<tEnumType>::kCount], const char* _name = nullptr)
{
	bool ret = true;

	if (_serializer_.beginObject(_name))
	{
		ret = true;

		for (int i = 0; i < BitFlags<tEnumType>::kCount; ++i)
		{
			bool flag = _bitFlags_.get((tEnumType)i);
			Serialize(_serializer_, flag, _strList[i]); // Allow flags to be optional (don't modify ret).
			_bitFlags_.set((tEnumType)i, flag);
		}

		_serializer_.endObject();
	}
	else
	{
		ret = false;
	}

	return ret;
}

} // namespace frm


text: One click suffix any url !


text:
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Equinox.Infra.Data.Context;

namespace Equinox.Infra.Data.Migrations
{
    [DbContext(typeof(EquinoxContext))]
    partial class EquinoxContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation("ProductVersion", "1.1.0-rtm-22752");

            modelBuilder.Entity("Equinox.Domain.Models.Customer", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnName("Id");

                    b.Property<DateTime>("BirthDate");

                    b.Property<string>("Email")
                        .IsRequired()
                        .HasColumnType("varchar(100)")
                        .HasMaxLength(11);

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasColumnType("varchar(100)")
                        .HasMaxLength(100);

                    b.HasKey("Id");

                    b.ToTable("Customers");
                });
        }
    }
}


text:
var assert = require("assert");
var path = require("path");
var local = path.join.bind(path, __dirname);

describe("Submodule", function() {
  var NodeGit = require("../../");
  var Repository = NodeGit.Repository;
  var RepoUtils = require("../utils/repository_setup");
  var Submodule = NodeGit.Submodule;

  var repoPath = local("../repos/submodule");

  beforeEach(function() {
    var test = this;

    return RepoUtils.createRepository(repoPath)
      .then(function(repo) {
        test.repository = repo;
        return Repository.open(local("../repos/workdir"));
      })
      .then(function(repo) {
        test.workdirRepository = repo;
      });
  });

  it("can walk over the submodules", function() {
    var repo = this.workdirRepository;
    var submoduleName = "vendor/libgit2";

    return repo.getSubmoduleNames()
      .then(function(submodules) {
        assert.equal(submodules.length, 1);

        var submodule = submodules[0];
        assert.equal(submodule, submoduleName);
        return submodule;
      })
      .then(function(submodule) {
        return Submodule.lookup(repo, submodule);
      })
      .then(function(submodule) {
        assert.equal(submodule.name(), submoduleName);
      });
  });

  it("can get submodule status", function() {
    var repo = this.workdirRepository;
    var submoduleName = "vendor/libgit2";

    return Submodule.status(repo, submoduleName, Submodule.IGNORE.NONE)
      .then(function(status) {
        assert.equal(Submodule.STATUS.IN_CONFIG, status);
      });
  });

  it("can get submodule location", function() {
    var repo = this.workdirRepository;
    var submoduleName = "vendor/libgit2";

    return Submodule.lookup(repo, submoduleName)
      .then(function(submodule) {
        return submodule.location();
      })
      .then(function(status) {
        assert.equal(Submodule.STATUS.IN_CONFIG, status);
      });
  });

  it("can set submodule ignore", function() {
    var repo = this.workdirRepository;
    var submoduleName = "vendor/libgit2";

    return Submodule.setIgnore(repo, submoduleName, Submodule.IGNORE.ALL)
      .then(function() {
        return Submodule.lookup(repo, submoduleName);
      })
      .then(function(submodule) {
        assert.equal(Submodule.IGNORE.ALL, submodule.ignore());
      });
  });

  it("can set submodule url", function() {
    var repo = this.workdirRepository;
    var submoduleName = "vendor/libgit2";
    var submoduleUrl = "https://github.com/githubtraining/hellogitworld.git";

    return Submodule.setUrl(repo, submoduleName, submoduleUrl)
      .then(function() {
        return Submodule.lookup(repo, submoduleName);
      })
      .then(function(submodule) {
        assert.equal(submoduleUrl, submodule.url());
      });
  });

  it("can set submodule update", function() {
    var repo = this.workdirRepository;
    var submoduleName = "vendor/libgit2";

    return Submodule.setUpdate(repo, submoduleName, Submodule.UPDATE.NONE)
      .then(function() {
        return Submodule.lookup(repo, submoduleName);
      })
      .then(function(submodule) {
        assert.equal(Submodule.UPDATE.NONE, submodule.updateStrategy());
      });
  });

  it("can setup and finalize submodule add", function() {
    var repo = this.repository;
    var submodulePath = "hellogitworld";
    var submoduleUrl = "https://github.com/githubtraining/hellogitworld.git";

    var submodule;
    var submoduleRepo;

    return NodeGit.Submodule.addSetup(repo, submoduleUrl, submodulePath, 0)
      .then(function(_submodule) {
        submodule = _submodule;

        return submodule.init(0);
      })
      .then(function() {
        return submodule.open();
      })
      .then(function(_submoduleRepo) {
        submoduleRepo = _submoduleRepo;
        return submoduleRepo.fetch("origin", null, null);
      })
      .then(function() {
        return submoduleRepo.getReference("origin/master");
      })
      .then(function(reference) {
        return reference.peel(NodeGit.Object.TYPE.COMMIT);
      })
      .then(function(commit) {
        return submoduleRepo.createBranch("master", commit);
      })
      .then(function() {
        return submodule.addFinalize();
      })
      .then(function() {
        // check whether the submodule exists
        return Submodule.lookup(repo, submodulePath);
      })
      .then(function(submodule) {
        assert.equal(submodule.name(), submodulePath);
        // check whether .gitmodules and the submodule are in the index
        return repo.openIndex();
      })
      .then(function(index) {
        var entries = index.entries();
        assert.equal(entries.length, 2);
        assert.equal(entries[0].path, ".gitmodules");
        assert.equal(entries[1].path, submodulePath);
      });
  });
});


text:
<?php

namespace CmsImage\Mapping;

use CmsFile\Mapping\UploadableInterface;

interface ImageUploadableInterface extends ImageableInterface, UploadableInterface
{

}


text:
title: 5th District school spending in Hamilton County, Tennessee
date: 2016-05-25 00:00:00 -04:00
permalink: "/projects/the-cost-of-education/brief/district-5/"
layout: the-cost-of-education/brief
boe: Karitsa Mosley
commission: Greg Beck
fn: district-5
district: 5th District
description: Learn about school funding in Hamilton County, Tennessee.
project: The cost of education
main: article
---

      School
      Enrollment
      Per-student spending

      Brainerd High
      554
      $9,771

      Dalewood Middle
      296
      $8,817

      Hillcrest Elementary
      276
      $8,088

      Lakeside Academy
      432
      $7,061

      Tyner Academy
      585
      $7,366

      Tyner Middle
      470
      $6,944

      Woodmore Elementary
      347
      $6,897


text:
@implementation SamuraiSandbox

@def_prop_strong( NSString *,	appPath );
@def_prop_strong( NSString *,	docPath );
@def_prop_strong( NSString *,	libPrefPath );
@def_prop_strong( NSString *,	libCachePath );
@def_prop_strong( NSString *,	tmpPath );

@def_singleton( SamuraiSandbox )

+ (void)classAutoLoad
{
	[SamuraiSandbox sharedInstance];
}

- (id)init
{
	self = [super init];
	if ( self )
	{
		NSString *	execName = [[NSBundle mainBundle] infoDictionary][@"CFBundleExecutable"];
		NSString *	execPath = [[NSHomeDirectory() stringByAppendingPathComponent:execName] stringByAppendingPathExtension:@"app"];

		NSArray *	docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSArray *	libPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
		NSString *	prefPath = [[libPaths objectAtIndex:0] stringByAppendingFormat:@"/Preference"];
		NSString *	cachePath = [[libPaths objectAtIndex:0] stringByAppendingFormat:@"/Caches"];
		NSString *	tmpPath = [[libPaths objectAtIndex:0] stringByAppendingFormat:@"/tmp"];

		self.appPath = execPath;
		self.docPath = [docPaths objectAtIndex:0];
		self.tmpPath = tmpPath;

		self.libPrefPath = prefPath;
		self.libCachePath = cachePath;

		[self touch:self.docPath];
		[self touch:self.tmpPath];
		[self touch:self.libPrefPath];
		[self touch:self.libCachePath];
	}
	return self;
}

- (BOOL)touch:(NSString *)path
{
	if ( NO == [[NSFileManager defaultManager] fileExistsAtPath:path] )
	{
		return [[NSFileManager defaultManager] createDirectoryAtPath:path
										 withIntermediateDirectories:YES
														  attributes:nil
															   error:NULL];
	}

	return YES;
}

- (BOOL)touchFile:(NSString *)file
{
	if ( NO == [[NSFileManager defaultManager] fileExistsAtPath:file] )
	{
		return [[NSFileManager defaultManager] createFileAtPath:file
													   contents:[NSData data]
													 attributes:nil];
	}

	return YES;
}

@end

// ----------------------------------
// Unit test
// ----------------------------------

#pragma mark -

#if __SAMURAI_TESTING__

TEST_CASE( Core, Sandbox )
{
}

DESCRIBE( paths )
{
	EXPECTED( nil != [[SamuraiSandbox sharedInstance] appPath] );
	EXPECTED( nil != [[SamuraiSandbox sharedInstance] docPath] );
	EXPECTED( nil != [[SamuraiSandbox sharedInstance] libPrefPath] );
	EXPECTED( nil != [[SamuraiSandbox sharedInstance] libCachePath] );
	EXPECTED( nil != [[SamuraiSandbox sharedInstance] tmpPath] );
}

TEST_CASE_END

#endif	// #if __SAMURAI_TESTING__

#import "_pragma_pop.h"


text:
<?php
/**
 * This is the template for generating the model class of a specified table.
 *
 * @var yii\web\View $this
 * @var yii\gii\generators\model\Generator $generator
 * @var string $tableName full table name
 * @var string $className class name
 * @var yii\db\TableSchema $tableSchema
 * @var string[] $labels list of attribute labels (name => label)
 * @var string[] $rules list of validation rules
 * @var array $relations list of relations (name => relation declaration)
 */

echo "<?php\n";
?>

namespace <?= $generator->ns ?>;

use Yii;

/**
 * This is the model class for table "<?= $tableName ?>".
 *
<?php foreach ($tableSchema->columns as $column): ?>
 * @property <?= "{$column->phpType} \${$column->name}\n" ?>
<?php endforeach; ?>
<?php if (!empty($relations)): ?>
 *
<?php foreach ($relations as $name => $relation): ?>
 * @property <?= $relation[1] . ($relation[2] ? '[]' : '') . ' $' . lcfirst($name) . "\n" ?>
<?php endforeach; ?>
<?php endif; ?>
 */
class <?= $className ?> extends <?= '\\' . ltrim($generator->baseClass, '\\') . "\n" ?>
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '<?= $tableName ?>';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [<?= "\n            " . implode(",\n            ", $rules) . "\n        " ?>];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
<?php foreach ($labels as $name => $label): ?>
            <?= "'$name' => " . $generator->generateString($label) . ",\n" ?>
<?php endforeach; ?>
        ];
    }
<?php foreach ($relations as $name => $relation): ?>

    /**
     * @return \yii\db\ActiveQuery
     */
    public function get<?= $name ?>()
    {
        <?= $relation[0] . "\n" ?>
    }
<?php endforeach; ?>
}


text:
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);

var redis = require("redis"),
client = redis.createClient();
var session_config = require('./config/session');

var routes = require('./routes/index');
var users = require('./routes/users');
var login = require('./routes/login');
var logout = require('./routes/logout');
var config = require('./routes/config');
var config2 = require('./routes/config2');
var save = require('./routes/save');
var reward_vs_weekly = require('./routes/reward_vs_weekly');
var reward_vs_weekly_230 = require('./routes/reward_vs_weekly_230');
var reward_vs_weekly_240 = require('./routes/reward_vs_weekly_240');
var reward_vs_weekly_wanwan_110 = require('./routes/reward_vs_weekly_wanwan_110');
var reward_vs_weekly_gv_110_en = require('./routes/reward_vs_weekly_gv_110_en');
var announcement_090 = require('./routes/announcement_090');
var announcement_100 = require('./routes/announcement_100');
var announcement_102 = require('./routes/announcement_102');
var announcement_103 = require('./routes/announcement_103');
var announcement_200 = require('./routes/announcement_200');
var announcement_gv_100 = require('./routes/announcement_gv_100');
var announcement_gv_110 = require('./routes/announcement_gv_110');
var announcement_gv_120 = require('./routes/announcement_gv_120');
var announcement_gv_120_en = require('./routes/announcement_gv_120_en');
var announcement_200_000066 = require('./routes/announcement_200_000066');
var announcement_200_000005 = require('./routes/announcement_200_000005');
var announcement_200_000020 = require('./routes/announcement_200_000020');
var announcement_200_000023 = require('./routes/announcement_200_000023');
var announcement_200_000054 = require('./routes/announcement_200_000054');
var announcement_200_000108 = require('./routes/announcement_200_000108');
var announcement_200_000440 = require('./routes/announcement_200_000440');
var announcement_200_000491 = require('./routes/announcement_200_000491');
var announcement_200_000582 = require('./routes/announcement_200_000582');
var announcement_200_000800 = require('./routes/announcement_200_000800');

var announcement_210 = require('./routes/announcement_210');
var announcement_210_000066 = require('./routes/announcement_210_000066');
var announcement_210_000005 = require('./routes/announcement_210_000005');
var announcement_210_000020 = require('./routes/announcement_210_000020');
var announcement_210_000023 = require('./routes/announcement_210_000023');
var announcement_210_000054 = require('./routes/announcement_210_000054');
var announcement_210_000108 = require('./routes/announcement_210_000108');
var announcement_210_000440 = require('./routes/announcement_210_000440');
var announcement_210_000491 = require('./routes/announcement_210_000491');
var announcement_210_000582 = require('./routes/announcement_210_000582');
var announcement_210_000800 = require('./routes/announcement_210_000800');

var announcement_220 = require('./routes/announcement_220');
var announcement_220_000961 = require('./routes/announcement_220_000961');
var announcement_220_000442 = require('./routes/announcement_220_000442');

var announcement_230 = require('./routes/announcement_230');
var announcement_230_000013 = require('./routes/announcement_230_000013');
var announcement_230_000023 = require('./routes/announcement_230_000023');

var announcement_240 = require('./routes/announcement_240');
var announcement_240_000020 = require('./routes/announcement_240_000020');
var announcement_240_000066 = require('./routes/announcement_240_000066');
var announcement_240_000078 = require('./routes/announcement_240_000078');
var announcement_240_000023 = require('./routes/announcement_240_000023');
var announcement_240_000054 = require('./routes/announcement_240_000054');

var announcement_250 = require('./routes/announcement_250');
var announcement_250_000066 = require('./routes/announcement_250_000066');
var announcement_250_000078 = require('./routes/announcement_250_000078');
var announcement_250_000023 = require('./routes/announcement_250_000023');
var announcement_250_000054 = require('./routes/announcement_250_000054');

var announcement_260 = require('./routes/announcement_260');
var announcement_260_000066 = require('./routes/announcement_260_000066');
var announcement_260_000023 = require('./routes/announcement_260_000023');
var announcement_260_000054 = require('./routes/announcement_260_000054');
var announcement_260_111245 = require('./routes/announcement_260_111245');
var announcement_260_111264 = require('./routes/announcement_260_111264');

var announcement_270 = require('./routes/announcement_270');
var announcement_270_111264 = require('./routes/announcement_270_111264');

var rewardlist_seoul_200 = require('./routes/rewardlist_seoul_200');
var rewardlist_seoul_200_000005 = require('./routes/rewardlist_seoul_200_000005');
var rewardlist_seoul_200_000020 = require('./routes/rewardlist_seoul_200_000020');
var rewardlist_seoul_200_000023 = require('./routes/rewardlist_seoul_200_000023');
var rewardlist_seoul_200_000054 = require('./routes/rewardlist_seoul_200_000054');
var rewardlist_seoul_200_000108 = require('./routes/rewardlist_seoul_200_000108');
var rewardlist_seoul_200_000440 = require('./routes/rewardlist_seoul_200_000440');
var rewardlist_seoul_200_000491 = require('./routes/rewardlist_seoul_200_000491');
var rewardlist_seoul_200_000582 = require('./routes/rewardlist_seoul_200_000582');
var rewardlist_seoul_200_000800 = require('./routes/rewardlist_seoul_200_000800');

var rewardlist_seoul_210 = require('./routes/rewardlist_seoul_210');
var rewardlist_seoul_210_000005 = require('./routes/rewardlist_seoul_210_000005');
var rewardlist_seoul_210_000020 = require('./routes/rewardlist_seoul_210_000020');
var rewardlist_seoul_210_000023 = require('./routes/rewardlist_seoul_210_000023');
var rewardlist_seoul_210_000054 = require('./routes/rewardlist_seoul_210_000054');
var rewardlist_seoul_210_000108 = require('./routes/rewardlist_seoul_210_000108');
var rewardlist_seoul_210_000440 = require('./routes/rewardlist_seoul_210_000440');
var rewardlist_seoul_210_000491 = require('./routes/rewardlist_seoul_210_000491');
var rewardlist_seoul_210_000582 = require('./routes/rewardlist_seoul_210_000582');
var rewardlist_seoul_210_000800 = require('./routes/rewardlist_seoul_210_000800');

var rewardlist_seoul_220 = require('./routes/rewardlist_seoul_220');
var rewardlist_seoul_220_000961 = require('./routes/rewardlist_seoul_220_000961');
var rewardlist_seoul_220_000442 = require('./routes/rewardlist_seoul_220_000442');

var rewardlist_seoul_230 = require('./routes/rewardlist_seoul_230');
var index_mm = require('./routes/index_mm');

//小包公告
var announcement_rmlite_110 = require('./routes/announcement_rmlite_110');
var announcement_rmlite_110_111225 = require('./routes/announcement_rmlite_110_111225');
var announcement_rmlite_110_000056 = require('./routes/announcement_rmlite_110_000056');

var announcement_rmlite_120 = require('./routes/announcement_rmlite_120');
var announcement_rmlite_120_111225 = require('./routes/announcement_rmlite_120_111225');
var announcement_rmlite_120_111263 = require('./routes/announcement_rmlite_120_111263');
var announcement_rmlite_120_000066 = require('./routes/announcement_rmlite_120_000066');
var announcement_rmlite_120_000016 = require('./routes/announcement_rmlite_120_000016');
var announcement_rmlite_120_000000 = require('./routes/announcement_rmlite_120_000000');
var announcement_rmlite_120_000994 = require('./routes/announcement_rmlite_120_000994');
var announcement_rmlite_120_000056 = require('./routes/announcement_rmlite_120_000056');

var announcement_rmlite_130 = require('./routes/announcement_rmlite_130');
var announcement_rmlite_130_000056 = require('./routes/announcement_rmlite_130_000056');
var announcement_rmlite_131 = require('./routes/announcement_rmlite_131');

var announcement_rmlite_140 = require('./routes/announcement_rmlite_140');

//wanwan
var announcement_wanwan_110 = require('./routes/announcement_wanwan_110');

//anqu
var announcement_120_anqu = require('./routes/announcement_120_anqu');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var options = {
    "client":client,
    "host":session_config.options.host,
    "port":session_config.options.port,
    "ttl":session_config.options.ttl,
    "db":session_config.options.db
};
app.use(session({ store: new RedisStore(options), secret: 'keyboard cat' }));

app.use('/', routes);
app.use('/users', users);
app.use('/login', login);
app.use('/logout', logout);
app.use('/config', config);
app.use('/config2', config2);
app.use('/save', save);
app.use('/reward_vs_weekly', reward_vs_weekly);
app.use('/reward_vs_weekly_230', reward_vs_weekly_230);
app.use('/reward_vs_weekly_240', reward_vs_weekly_240);
app.use('/reward_vs_weekly_wanwan_110', reward_vs_weekly_wanwan_110);
app.use('/reward_vs_weekly_gv_110_en', reward_vs_weekly_gv_110_en);
app.use('/announcement_090', announcement_090);
app.use('/announcement_100', announcement_100);
app.use('/announcement_102', announcement_102);
app.use('/announcement_103', announcement_103);
app.use('/announcement_200', announcement_200);
app.use('/announcement_gv_100', announcement_gv_100);
app.use('/announcement_gv_110', announcement_gv_110);
app.use('/announcement_gv_120', announcement_gv_120);
app.use('/announcement_gv_120_en', announcement_gv_120_en);
app.use('/announcement_200_000066', announcement_200_000066);
app.use('/announcement_200_000005', announcement_200_000005);
app.use('/announcement_200_000020', announcement_200_000020);
app.use('/announcement_200_000023', announcement_200_000023);
app.use('/announcement_200_000054', announcement_200_000054);
app.use('/announcement_200_000108', announcement_200_000108);
app.use('/announcement_200_000440', announcement_200_000440);
app.use('/announcement_200_000491', announcement_200_000491);
app.use('/announcement_200_000582', announcement_200_000582);
app.use('/announcement_200_000800', announcement_200_000800);

app.use('/announcement_210', announcement_210);
app.use('/announcement_210_000066', announcement_210_000066);
app.use('/announcement_210_000005', announcement_210_000005);
app.use('/announcement_210_000020', announcement_210_000020);
app.use('/announcement_210_000023', announcement_210_000023);
app.use('/announcement_210_000054', announcement_210_000054);
app.use('/announcement_210_000108', announcement_210_000108);
app.use('/announcement_210_000440', announcement_210_000440);
app.use('/announcement_210_000491', announcement_210_000491);
app.use('/announcement_210_000582', announcement_210_000582);
app.use('/announcement_210_000800', announcement_210_000800);

app.use('/announcement_220', announcement_220);
app.use('/announcement_220_000961', announcement_220_000961);
app.use('/announcement_220_000442', announcement_220_000442);

app.use('/announcement_230', announcement_230);
app.use('/announcement_230_000013', announcement_230_000013);
app.use('/announcement_230_000023', announcement_230_000023);

app.use('/announcement_240', announcement_240);
app.use('/announcement_240_000020', announcement_240_000020);
app.use('/announcement_240_000066', announcement_240_000066);
app.use('/announcement_240_000078', announcement_240_000078);
app.use('/announcement_240_000023', announcement_240_000023);
app.use('/announcement_240_000054', announcement_240_000054);

app.use('/announcement_250', announcement_250);
app.use('/announcement_250_000066', announcement_250_000066);
app.use('/announcement_250_000078', announcement_250_000078);
app.use('/announcement_250_000023', announcement_250_000023);
app.use('/announcement_250_000054', announcement_250_000054);

app.use('/announcement_260', announcement_260);
app.use('/announcement_260_000066', announcement_260_000066);
app.use('/announcement_260_000023', announcement_260_000023);
app.use('/announcement_260_000054', announcement_260_000054);
app.use('/announcement_260_111245', announcement_260_111245);
app.use('/announcement_260_111264', announcement_260_111264);

app.use('/announcement_270', announcement_270);
app.use('/announcement_270_111264', announcement_270_111264);

app.use('/rewardlist_seoul_200', rewardlist_seoul_200);
app.use('/rewardlist_seoul_200_000005', rewardlist_seoul_200_000005);
app.use('/rewardlist_seoul_200_000020', rewardlist_seoul_200_000020);
app.use('/rewardlist_seoul_200_000023', rewardlist_seoul_200_000023);
app.use('/rewardlist_seoul_200_000054', rewardlist_seoul_200_000054);
app.use('/rewardlist_seoul_200_000108', rewardlist_seoul_200_000108);
app.use('/rewardlist_seoul_200_000440', rewardlist_seoul_200_000440);
app.use('/rewardlist_seoul_200_000491', rewardlist_seoul_200_000491);
app.use('/rewardlist_seoul_200_000582', rewardlist_seoul_200_000582);
app.use('/rewardlist_seoul_200_000800', rewardlist_seoul_200_000800);

app.use('/rewardlist_seoul_210', rewardlist_seoul_210);
app.use('/rewardlist_seoul_210_000005', rewardlist_seoul_210_000005);
app.use('/rewardlist_seoul_210_000020', rewardlist_seoul_210_000020);
app.use('/rewardlist_seoul_210_000023', rewardlist_seoul_210_000023);
app.use('/rewardlist_seoul_210_000054', rewardlist_seoul_210_000054);
app.use('/rewardlist_seoul_210_000108', rewardlist_seoul_210_000108);
app.use('/rewardlist_seoul_210_000440', rewardlist_seoul_210_000440);
app.use('/rewardlist_seoul_210_000491', rewardlist_seoul_210_000491);
app.use('/rewardlist_seoul_210_000582', rewardlist_seoul_210_000582);
app.use('/rewardlist_seoul_210_000800', rewardlist_seoul_210_000800);

app.use('/rewardlist_seoul_220', rewardlist_seoul_220);
app.use('/rewardlist_seoul_220_000961', rewardlist_seoul_220_000961);
app.use('/rewardlist_seoul_220_000442', rewardlist_seoul_220_000442);

app.use('/rewardlist_seoul_230', rewardlist_seoul_230);
app.use('/index_mm', index_mm);

app.use('/announcement_rmlite_110', announcement_rmlite_110);
app.use('/announcement_rmlite_110_111225', announcement_rmlite_110_111225);
app.use('/announcement_rmlite_110_000056', announcement_rmlite_110_000056);

app.use('/announcement_rmlite_120', announcement_rmlite_120);
app.use('/announcement_rmlite_120_111225', announcement_rmlite_120_111225);
app.use('/announcement_rmlite_120_111263', announcement_rmlite_120_111263);
app.use('/announcement_rmlite_120_000066', announcement_rmlite_120_000066);
app.use('/announcement_rmlite_120_000016', announcement_rmlite_120_000016);
app.use('/announcement_rmlite_120_000000', announcement_rmlite_120_000000);
app.use('/announcement_rmlite_120_000994', announcement_rmlite_120_000994);
app.use('/announcement_rmlite_120_000056', announcement_rmlite_120_000056);

app.use('/announcement_rmlite_130', announcement_rmlite_130);
app.use('/announcement_rmlite_130_000056', announcement_rmlite_130_000056);
app.use('/announcement_rmlite_131', announcement_rmlite_131);

app.use('/announcement_rmlite_140', announcement_rmlite_140);

//wanwan
app.use('/announcement_wanwan_110', announcement_wanwan_110);

//anqu
app.use('/announcement_120_anqu', announcement_120_anqu);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;


text:
module Nsync
  module ActiveRecord
    module Consumer
      module ClassMethods
        def nsync_find(ids)
          all(:conditions => {nsync_opts[:id_key] => ids})
        end

        def nsync_add_data(consumer, event_type, filename, data)
          data = data.dup
          if nsync_opts[:id_key].to_s != "id"
            data[nsync_opts[:id_key].to_s] = data.delete("id")
            create(data)
          else
            id = data.delete("id")
            obj = new(data)
            obj.id = id
            obj.save
          end
        end
      end

      module InstanceMethods
        def self.included(base)
          base.send(:extend, ClassMethods)
        end
        def nsync_update(consumer, event_type, filename, data)
          data = data.dup
          if event_type == :deleted
            destroy
          else
            nsync_opts = self.class.nsync_opts
            if nsync_opts[:id_key].to_s != "id"
              data[nsync_opts[:id_key].to_s] = data.delete("id")
            else
              self.id = data.delete("id")
              update_attributes(data)
            end
          end
        end
      end
    end
  end
end


text:
<?php

namespace ZendTest\Barcode\Object;

use Zend\Barcode;

/**
 * @group      Zend_Barcode
 */
class UpceTest extends TestCommon
{
    protected function getBarcodeObject($options = null)
    {
        return new Barcode\Object\Upce($options);
    }

    public function testType()
    {
        $this->assertSame('upce', $this->object->getType());
    }

    public function testChecksum()
    {
        $this->assertSame(9, $this->object->getChecksum('3456789'));
    }

    public function testSetText()
    {
        $this->object->setText('1234567');
        $this->assertSame('1234567', $this->object->getRawText());
        $this->assertSame('12345670', $this->object->getText());
        $this->assertSame('12345670', $this->object->getTextToDisplay());
    }

    public function testSetTextWithout8Characters()
    {
        $this->object->setText('12345');
        $this->assertSame('12345', $this->object->getRawText());
        $this->assertSame('00123457', $this->object->getText());
        $this->assertSame('00123457', $this->object->getTextToDisplay());
    }

    public function testSetTextWithout0or1AtBeginning()
    {
        $this->object->setText('3234567');
        $this->assertSame('3234567', $this->object->getRawText());
        $this->assertSame('02345673', $this->object->getText());
        $this->assertSame('02345673', $this->object->getTextToDisplay());
    }

    public function testSetTextWithoutChecksumHasNoEffect()
    {
        $this->object->setText('1234567');
        $this->object->setWithChecksum(false);
        $this->assertSame('1234567', $this->object->getRawText());
        $this->assertSame('12345670', $this->object->getText());
        $this->assertSame('12345670', $this->object->getTextToDisplay());
    }

    public function testSetTextWithSpaces()
    {
        $this->object->setText(' 1234567 ');
        $this->assertSame('1234567', $this->object->getRawText());
        $this->assertSame('12345670', $this->object->getText());
        $this->assertSame('12345670', $this->object->getTextToDisplay());
    }

    public function testSetTextWithChecksumNotDisplayed()
    {
        $this->object->setText('1234567');
        $this->object->setWithChecksumInText(false);
        $this->assertSame('1234567', $this->object->getRawText());
        $this->assertSame('12345670', $this->object->getText());
        $this->assertSame('12345670', $this->object->getTextToDisplay());
    }

    public function testBadTextDetectedIfChecksumWished()
    {
        $this->setExpectedException('\Zend\Barcode\Object\Exception\ExceptionInterface');
        $this->object->setText('a');
        $this->object->setWithChecksum(true);
        $this->object->getText();
    }

    public function testCheckGoodParams()
    {
        $this->object->setText('1234567');
        $this->assertTrue($this->object->checkParams());
    }

    public function testGetKnownWidthWithoutOrientation()
    {
        $this->object->setText('1234567');
        $this->assertEquals(71, $this->object->getWidth());
        $this->object->setWithQuietZones(false);
        $this->assertEquals(71, $this->object->getWidth(true));
    }

    public function testCompleteGeneration()
    {
        $this->object->setText('1234567');
        $this->object->draw();
        $instructions = $this->loadInstructionsFile('Upce_1234567_instructions');
        $this->assertEquals($instructions, $this->object->getInstructions());
    }

    public function testCompleteGenerationWithBorder()
    {
        $this->object->setText('1234567');
        $this->object->setWithBorder(true);
        $this->object->draw();
        $instructions = $this->loadInstructionsFile(
                'Upce_1234567_border_instructions');
        $this->assertEquals($instructions, $this->object->getInstructions());
    }

    public function testCompleteGenerationWithOrientation()
    {
        $this->object->setText('1234567');
        $this->object->setOrientation(60);
        $this->object->draw();
        $instructions = $this->loadInstructionsFile(
                'Upce_1234567_oriented_instructions');
        $this->assertEquals($instructions, $this->object->getInstructions());
    }

    public function testCompleteGenerationWithBorderWithOrientation()
    {
        $this->object->setText('1234567');
        $this->object->setOrientation(60);
        $this->object->setWithBorder(true);
        $this->object->draw();
        $instructions = $this->loadInstructionsFile(
                'Upce_1234567_border_oriented_instructions');
        $this->assertEquals($instructions, $this->object->getInstructions());
    }

    public function testGetDefaultHeight()
    {
        // Checksum activated => text needed
        $this->object->setText('1234567');
        $this->assertEquals(62, $this->object->getHeight(true));
    }
}


text:
@interface ZLPZoneViewController : UICollectionViewController

@property(nonatomic, assign)NSInteger type;

@end


text:
.. _workflow:

Work flow
--------------------

Work flow of phonopy is shown schematically. There are two ways to
calculate, (1) atomic forces from finite displacements and (2) given
force constants. You can choose one of them. Forces on atoms or force
constants are calculated by your favorite calculator (shown by the
diamonds in the work flow). The boxes are jobs being done by phonopy,
and the circles are input and intermediate output data structures.

.. figure:: procedure.png
   :scale: 65
   :align: center

   Work flow of phonon calculation


text:
This project contains one simple class that could solve sudoku puzzle any difficulty
with field size 9x9 . The code is a bit messed ;)

### Tests

- Rename phpunit.xml.dist to phpunit.xml and change as needed.
- Add sudoku solver sources to your autoload class.
- Run phpunit as usual


text:
<?php

namespace Sylius\Behat\Context\Setup;

use Behat\Behat\Context\Context;
use Doctrine\Common\Persistence\ObjectManager;
use Sylius\Bundle\CoreBundle\Test\Services\PaymentMethodNameToGatewayConverterInterface;
use Sylius\Component\Core\Test\Services\SharedStorageInterface;
use Sylius\Component\Payment\Model\PaymentMethodInterface;
use Sylius\Component\Payment\Repository\PaymentMethodRepositoryInterface;
use Sylius\Component\Resource\Factory\FactoryInterface;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 * @author Grzegorz Sadowski <grzegorz.sadowski@lakion.com>
 */
final class PaymentContext implements Context
{
    /**
     * @var SharedStorageInterface
     */
    private $sharedStorage;

    /**
     * @var PaymentMethodRepositoryInterface
     */
    private $paymentMethodRepository;

    /**
     * @var FactoryInterface
     */
    private $paymentMethodFactory;

    /**
     * @var PaymentMethodNameToGatewayConverterInterface
     */
    private $paymentMethodNameToGatewayConverter;

    /**
     * @var ObjectManager
     */
    private $objectManager;

    /**
     * @param SharedStorageInterface $sharedStorage
     * @param PaymentMethodRepositoryInterface $paymentMethodRepository
     * @param FactoryInterface $paymentMethodFactory
     * @param PaymentMethodNameToGatewayConverterInterface $paymentMethodNameToGatewayConverter
     * @param ObjectManager $objectManager
     */
    public function __construct(
        SharedStorageInterface $sharedStorage,
        PaymentMethodRepositoryInterface $paymentMethodRepository,
        FactoryInterface $paymentMethodFactory,
        PaymentMethodNameToGatewayConverterInterface $paymentMethodNameToGatewayConverter,
        ObjectManager $objectManager
    ) {
        $this->sharedStorage = $sharedStorage;
        $this->paymentMethodRepository = $paymentMethodRepository;
        $this->paymentMethodFactory = $paymentMethodFactory;
        $this->paymentMethodNameToGatewayConverter = $paymentMethodNameToGatewayConverter;
        $this->objectManager = $objectManager;
    }

    /**
     * @Given the store allows paying :paymentMethodName
     * @Given the store allows paying with :paymentMethodName
     */
    public function storeAllowsPaying($paymentMethodName)
    {
        $paymentMethod = $this->paymentMethodFactory->createNew();
        $paymentMethod->setCode('PM_'.$paymentMethodName);
        $paymentMethod->setName(ucfirst($paymentMethodName));
        $paymentMethod->setGateway($this->paymentMethodNameToGatewayConverter->convert($paymentMethodName));
        $paymentMethod->setDescription('Payment method');

        $channel = $this->sharedStorage->get('channel');
        $channel->addPaymentMethod($paymentMethod);

        $this->sharedStorage->set('payment_method', $paymentMethod);
        $this->paymentMethodRepository->add($paymentMethod);
    }

    /**
     * @Given the store has a payment method :paymentMethodName with a code :paymentMethodCode
     */
    public function theStoreHasAPaymentMethodWithACode($paymentMethodName, $paymentMethodCode)
    {
        $paymentMethod = $this->createPaymentMethodFromNameAndCode($paymentMethodName, $paymentMethodCode);

        $this->sharedStorage->set('payment_method', $paymentMethod);
        $this->paymentMethodRepository->add($paymentMethod);
    }

    /**
     * @Given the payment method :paymentMethod is disabled
     */
    public function theStoreHasAPaymentMethodDisabled(PaymentMethodInterface $paymentMethod)
    {
        $paymentMethod->disable();

        $this->objectManager->flush();
    }

    /**
     * @param string $name
     * @param string $code
     *
     * @return PaymentMethodInterface
     */
    private function createPaymentMethodFromNameAndCode($name, $code)
    {
        /** @var PaymentMethodInterface $paymentMethod */
        $paymentMethod = $this->paymentMethodFactory->createNew();
        $paymentMethod->setName($name);
        $paymentMethod->setCode($code);
        $paymentMethod->setGateway($this->paymentMethodNameToGatewayConverter->convert($name));

        return $paymentMethod;
    }
}


text:
[Typhoon](https://github.com/appsquickly/Typhoon) is a great tool, and iOS team in Rambler&Co loves it a lot. Besides actual contributing, we've developed some useful tools which cannot be included in the main project.

1. `RamblerInitialAssemblyCollector` - this class can be used for activating assemblies on startup instead of plist integration.
2. `RamblerTyphoonAssemblyTests` - A base test class used for `TyphoonAssembly` testing.

## Usage

To run the example project, clone the repo, and run `pod install` from the Example directory first.

#### AssemblyCollector

At first, make your assemblies conform the `RamblerInitialAssembly` protocol:

```objc
@interface ApplicationAssembly : TyphoonAssembly <RamblerInitialAssembly>

@end
```

Then, instead of adding this assembly in the `Info.plist` file, add the following code in the `AppDelegate`:

```objc
@implementation AppDelegate

- (NSArray *)initialAssemblies {
    RamblerInitialAssemblyCollector *collector = [RamblerInitialAssemblyCollector new];
    return [collector collectInitialAssemblyClasses];
}

@end
```

The `RamblerInitialAssemblyCollector` will find your assembly in the runtime and automatically activate it.

#### AssemblyTesting

Inherit your test from the `RamblerTyphoonAssemblyTests`:

```objc
@interface RamblerApplicationAssemblyTests : RamblerTyphoonAssemblyTests

@property (nonatomic, strong) RamblerApplicationAssembly *assembly;

@end
```

Write new tests: one per your assembly method. To describe the type of a test object use `RamblerTyphoonAssemblyTestsTypeDescriptor`. Don't forget that we don't verify blocks and primitive types: just only classes and protocols.

```objc
- (void)testThatAssemblyCreatesAppDelegateWithDependencies {
    // given
    Class expectedClass = [RamblerAppDelegate class];
    NSArray *expectedProtocols = @[
                                   @protocol(UIApplicationDelegate),
                                   @protocol(RamblerFooProtocol)
                                   ];
    RamblerTyphoonAssemblyTestsTypeDescriptor *resultTypeDescriptor =
        [RamblerTyphoonAssemblyTestsTypeDescriptor descriptorWithClass:expectedClass
                                                          andProtocols:expectedProtocols];
    NSArray *dependencies = @[
                              RamblerSelector(injectedString),
                              RamblerSelector(injectedPropertyWithProtocols)
                              ];

    // when
    id result = [self.assembly appDelegate];

    // then
    [self verifyTargetDependency:result
                  withDescriptor:resultTypeDescriptor
                    dependencies:dependencies];
}
```

You are testing the following things:
- The target object is created
- The result is of the required class and conforms to the required protocols
- The result has all of the listed dependencies
- Dependencies are of the right classes and conform to the required protocols

## Requirements

## Installation

RamblerTyphoonUtils is available through [CocoaPods](http://cocoapods.org). To use the `AssemblyCollector`:

```ruby
pod "RamblerTyphoonUtils/AssemblyCollector"
```

To use the `AssemblyTesting`:

```ruby
target 'ProjectNameTargetTests', :exclusive => true do
    pod "RamblerTyphoonUtils/AssemblyTesting"
end
```

**Warning:** do not include `AssemblyTesting` subspec in the main target!

## Authors

- Egor Tolstoy, e.tolstoy@rambler-co.ru
- Irina Dyagileva, i.dyagileva@rambler-co.ru
- Andrey Rezanov, a.rezanov@rambler-co.ru
- Andrey Zarembo-Godzyatsky, a.zarembo-godzyatsky@rambler-co.ru

## License

RamblerTyphoonUtils is available under the MIT license. See the LICENSE file for more info.


text:
package edu.umd.cs.findbugs;

import java.util.HashSet;
import java.util.Set;

/**
 * A delegating bug reporter which counts reported bug instances, missing
 * classes, and serious analysis errors.
 */
public class ErrorCountingBugReporter extends DelegatingBugReporter {
    private int bugCount;

    private HashSet<String> errors = new HashSet<String>();

    private Set<String> missingClassSet = new HashSet<String>();

    public ErrorCountingBugReporter(BugReporter realBugReporter) {
        super(realBugReporter);
        this.bugCount = 0;

        // Add an observer to record when bugs make it through
        // all priority and filter criteria, so our bug count is
        // accurate.
        realBugReporter.addObserver(new BugReporterObserver() {
            public void reportBug(BugInstance bugInstance) {
                ++bugCount;
            }
        });
    }

    public int getBugCount() {
        return bugCount;
    }

    public int getMissingClassCount() {
        return missingClassSet.size();
    }

    public int getErrorCount() {
        return errors.size();
    }

    @Override
    public void logError(String message) {
        if (errors.add(message))
          super.logError(message);
    }

    @Override
    public void reportMissingClass(ClassNotFoundException ex) {
        String missing = AbstractBugReporter.getMissingClassName(ex);
        if (missing == null || missing.startsWith("[") || missing.equals("java.lang.Synthetic")) {
            return;
        }
        if (missingClassSet.add(missing)) {
            super.reportMissingClass(ex);
        }
    }
}


text:
static void emit_pdf_color(SkColor4f color, SkWStream* result) {
    SkASSERT(color.fA == 1);  // We handle alpha elsewhere.
    SkPDFUtils::AppendColorComponentF(color.fR, result);
    result->writeText(" ");
    SkPDFUtils::AppendColorComponentF(color.fG, result);
    result->writeText(" ");
    SkPDFUtils::AppendColorComponentF(color.fB, result);
    result->writeText(" ");
}

static SkRect rect_intersect(SkRect u, SkRect v) {
    if (u.isEmpty() || v.isEmpty()) { return {0, 0, 0, 0}; }
    return u.intersect(v) ? u : SkRect{0, 0, 0, 0};
}

// Test to see if the clipstack is a simple rect, If so, we can avoid all PathOps code
// and speed thing up.
static bool is_rect(const SkClipStack& clipStack, const SkRect& bounds, SkRect* dst) {
    SkRect currentClip = bounds;
    SkClipStack::Iter iter(clipStack, SkClipStack::Iter::kBottom_IterStart);
    while (const SkClipStack::Element* element = iter.next()) {
        SkRect elementRect{0, 0, 0, 0};
        switch (element->getDeviceSpaceType()) {
            case SkClipStack::Element::DeviceSpaceType::kEmpty:
                break;
            case SkClipStack::Element::DeviceSpaceType::kRect:
                elementRect = element->getDeviceSpaceRect();
                break;
            default:
                return false;
        }
        if (element->isReplaceOp()) {
            currentClip = rect_intersect(bounds, elementRect);
        } else if (element->getOp() == SkClipOp::kIntersect) {
            currentClip = rect_intersect(currentClip, elementRect);
        } else {
            return false;
        }
    }
    *dst = currentClip;
    return true;
}

// TODO: When there's no expanding clip ops, this function may not be necessary anymore.
static bool is_complex_clip(const SkClipStack& stack) {
    SkClipStack::Iter iter(stack, SkClipStack::Iter::kBottom_IterStart);
    while (const SkClipStack::Element* element = iter.next()) {
        if (element->isReplaceOp() ||
            (element->getOp() != SkClipOp::kDifference &&
             element->getOp() != SkClipOp::kIntersect)) {
            return true;
        }
    }
    return false;
}

template <typename F>
static void apply_clip(const SkClipStack& stack, const SkRect& outerBounds, F fn) {
    // assumes clipstack is not complex.
    constexpr SkRect kHuge{-30000, -30000, 30000, 30000};
    SkClipStack::Iter iter(stack, SkClipStack::Iter::kBottom_IterStart);
    SkRect bounds = outerBounds;
    while (const SkClipStack::Element* element = iter.next()) {
        SkPath operand;
        element->asDeviceSpacePath(&operand);
        SkPathOp op;
        switch (element->getOp()) {
            case SkClipOp::kDifference: op = kDifference_SkPathOp; break;
            case SkClipOp::kIntersect:  op = kIntersect_SkPathOp;  break;
            default: SkASSERT(false); return;
        }
        if (op == kDifference_SkPathOp  ||
            operand.isInverseFillType() ||
            !kHuge.contains(operand.getBounds()))
        {
            Op(SkPath::Rect(bounds), operand, op, &operand);
        }
        SkASSERT(!operand.isInverseFillType());
        fn(operand);
        if (!bounds.intersect(operand.getBounds())) {
            return; // return early;
        }
    }
}

static void append_clip_path(const SkPath& clipPath, SkWStream* wStream) {
    SkPDFUtils::EmitPath(clipPath, SkPaint::kFill_Style, wStream);
    SkPathFillType clipFill = clipPath.getFillType();
    NOT_IMPLEMENTED(clipFill == SkPathFillType::kInverseEvenOdd, false);
    NOT_IMPLEMENTED(clipFill == SkPathFillType::kInverseWinding, false);
    if (clipFill == SkPathFillType::kEvenOdd) {
        wStream->writeText("W* n\n");
    } else {
        wStream->writeText("W n\n");
    }
}

static void append_clip(const SkClipStack& clipStack,
                        const SkIRect& bounds,
                        SkWStream* wStream) {
    // The bounds are slightly outset to ensure this is correct in the
    // face of floating-point accuracy and possible SkRegion bitmap
    // approximations.
    SkRect outsetBounds = SkRect::Make(bounds.makeOutset(1, 1));

    SkRect clipStackRect;
    if (is_rect(clipStack, outsetBounds, &clipStackRect)) {
        SkPDFUtils::AppendRectangle(clipStackRect, wStream);
        wStream->writeText("W* n\n");
        return;
    }

    if (is_complex_clip(clipStack)) {
        SkPath clipPath;
        SkClipStack_AsPath(clipStack, &clipPath);
        if (Op(clipPath, SkPath::Rect(outsetBounds), kIntersect_SkPathOp, &clipPath)) {
            append_clip_path(clipPath, wStream);
        }
        // If Op() fails (pathological case; e.g. input values are
        // extremely large or NaN), emit no clip at all.
    } else {
        apply_clip(clipStack, outsetBounds, [wStream](const SkPath& path) {
            append_clip_path(path, wStream);
        });
    }
}

////////////////////////////////////////////////////////////////////////////////

void SkPDFGraphicStackState::updateClip(const SkClipStack* clipStack, const SkIRect& bounds) {
    uint32_t clipStackGenID = clipStack ? clipStack->getTopmostGenID()
                                        : SkClipStack::kWideOpenGenID;
    if (clipStackGenID == currentEntry()->fClipStackGenID) {
        return;
    }
    while (fStackDepth > 0) {
        this->pop();
        if (clipStackGenID == currentEntry()->fClipStackGenID) {
            return;
        }
    }
    SkASSERT(currentEntry()->fClipStackGenID == SkClipStack::kWideOpenGenID);
    if (clipStackGenID != SkClipStack::kWideOpenGenID) {
        SkASSERT(clipStack);
        this->push();

        currentEntry()->fClipStackGenID = clipStackGenID;
        append_clip(*clipStack, bounds, fContentStream);
    }
}

void SkPDFGraphicStackState::updateMatrix(const SkMatrix& matrix) {
    if (matrix == currentEntry()->fMatrix) {
        return;
    }

    if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
        SkASSERT(fStackDepth > 0);
        SkASSERT(fEntries[fStackDepth].fClipStackGenID ==
                 fEntries[fStackDepth -1].fClipStackGenID);
        this->pop();

        SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
    }
    if (matrix.getType() == SkMatrix::kIdentity_Mask) {
        return;
    }

    this->push();
    SkPDFUtils::AppendTransform(matrix, fContentStream);
    currentEntry()->fMatrix = matrix;
}

void SkPDFGraphicStackState::updateDrawingState(const SkPDFGraphicStackState::Entry& state) {
    // PDF treats a shader as a color, so we only set one or the other.
    if (state.fShaderIndex >= 0) {
        if (state.fShaderIndex != currentEntry()->fShaderIndex) {
            SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
            currentEntry()->fShaderIndex = state.fShaderIndex;
        }
    } else {
        if (state.fColor != currentEntry()->fColor ||
                currentEntry()->fShaderIndex >= 0) {
            emit_pdf_color(state.fColor, fContentStream);
            fContentStream->writeText("RG ");
            emit_pdf_color(state.fColor, fContentStream);
            fContentStream->writeText("rg\n");
            currentEntry()->fColor = state.fColor;
            currentEntry()->fShaderIndex = -1;
        }
    }

    if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
        SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
        currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
    }

    if (state.fTextScaleX) {
        if (state.fTextScaleX != currentEntry()->fTextScaleX) {
            SkScalar pdfScale = state.fTextScaleX * 100;
            SkPDFUtils::AppendScalar(pdfScale, fContentStream);
            fContentStream->writeText(" Tz\n");
            currentEntry()->fTextScaleX = state.fTextScaleX;
        }
    }
}

void SkPDFGraphicStackState::push() {
    SkASSERT(fStackDepth < kMaxStackDepth);
    fContentStream->writeText("q\n");
    ++fStackDepth;
    fEntries[fStackDepth] = fEntries[fStackDepth - 1];
}

void SkPDFGraphicStackState::pop() {
    SkASSERT(fStackDepth > 0);
    fContentStream->writeText("Q\n");
    fEntries[fStackDepth] = SkPDFGraphicStackState::Entry();
    --fStackDepth;
}

void SkPDFGraphicStackState::drainStack() {
    if (fContentStream) {
        while (fStackDepth) {
            this->pop();
        }
    }
    SkASSERT(fStackDepth == 0);
}