text:
package net.xpece.android.support.preference;

import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.cursoradapter.widget.SimpleCursorAdapter;
import androidx.appcompat.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import net.xpece.android.support.preference.plugins.XpSupportPreferencePlugins;

import java.lang.reflect.Field;
import java.util.ArrayList;

import static net.xpece.android.support.preference.Util.checkPreferenceNotNull;

/**
 * Created by Eugen on 07.12.2015.
 */
public class XpRingtonePreferenceDialogFragment extends XpPreferenceDialogFragment
        implements Runnable, AdapterView.OnItemSelectedListener {

    private static int RC_FALLBACK_RINGTONE_PICKER = 0xff00; // <0; 0xffff>

    private static String KEY_FALLBACK_RINGTONE_PICKER = "net.xpece.android.support.preference.FALLBACK_RINGTONE_PICKER";

    private static final int POS_UNKNOWN = -1;

    private static final int DELAY_MS_SELECTION_PLAYED = 300;

    private static final String SAVE_CLICKED_POS = "clicked_pos";

    private RingtoneManager mRingtoneManager;
    private int mType;

    private Cursor mCursor;
    private Handler mHandler;

    private int mUnknownPos = POS_UNKNOWN;

    /**
     * The position in the list of the 'Silent' item.
     */
    private int mSilentPos = POS_UNKNOWN;

    /**
     * The position in the list of the 'Default' item.
     */
    private int mDefaultRingtonePos = POS_UNKNOWN;

    /**
     * The position in the list of the last clicked item.
     */
    int mClickedPos = POS_UNKNOWN;

    /**
     * The position in the list of the ringtone to sample.
     */
    private int mSampleRingtonePos = POS_UNKNOWN;

    /**
     * Whether this list has the 'Silent' item.
     */
    private boolean mHasSilentItem;

    /**
     * The Uri to place a checkmark next to.
     */
    private Uri mExistingUri;

    /**
     * The number of static items in the list.
     */
    private final ArrayList<XpHeaderViewListAdapter.FixedViewInfo> mStaticItems = new ArrayList<>();

    /**
     * Whether this list has the 'Default' item.
     */
    private boolean mHasDefaultItem;

    /**
     * The Uri to play when the 'Default' item is clicked.
     */
    private Uri mUriForDefaultItem;

    private Ringtone mUnknownRingtone;

    /**
     * A Ringtone for the default ringtone. In most cases, the RingtoneManager
     * will stop the previous ringtone. However, the RingtoneManager doesn't
     * manage the default ringtone for us, so we should stop this one manually.
     */
    private Ringtone mDefaultRingtone;

    /**
     * The ringtone that's currently playing, unless the currently playing one is the default
     * ringtone.
     */
    private Ringtone mCurrentRingtone;

    /**
     * Keep the currently playing ringtone around when changing orientation, so that it
     * can be stopped later, after the activity is recreated.
     */
    private static Ringtone sPlayingRingtone;

    private final DialogInterface.OnClickListener mRingtoneClickListener =
            new DialogInterface.OnClickListener() {

                /*
                 * On item clicked
                 */
                public void onClick(@NonNull DialogInterface dialog, int which) {
                    // Save the position of most recently clicked item
                    mClickedPos = which;

                    // Play clip
                    playRingtone(which, 0);
                }

            };

    private boolean mActivityCreated = false;

    @NonNull
    public static XpRingtonePreferenceDialogFragment newInstance(@NonNull String key) {
        XpRingtonePreferenceDialogFragment fragment = new XpRingtonePreferenceDialogFragment();
        Bundle b = new Bundle(1);
        b.putString(ARG_KEY, key);
        fragment.setArguments(b);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mHandler = new Handler();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        mActivityCreated = true;

        loadRingtoneManager(savedInstanceState);

        if (getDialog() instanceof DummyAlertDialog) {
            // Reinstall the real dialog now if we don't have custom view.
            // The resulting layout inflater will be discarded. First call result is preserved.
            // Fragment-Dialog listeners are attached in super.onActivityCreated. Do this before.
            getDialog().dismiss();
            onGetLayoutInflater(savedInstanceState);
        }

        super.onActivityCreated(savedInstanceState);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        if (mActivityCreated) {
            return super.onCreateDialog(savedInstanceState);
        } else {
            // Dummy. Will be replaced with real dialog in onActivityCreated.
            // LayoutInflater from the dialog builder will remain cached in this fragment.
            return new DummyAlertDialog(getContext());
        }
    }

    private void loadRingtoneManager(@Nullable Bundle savedInstanceState) {
        // Give the Activity so it can do managed queries
        mRingtoneManager = new RingtoneManagerCompat(getActivity());

        final boolean fallbackRingtonePicker;
        if (savedInstanceState != null) {
            mClickedPos = savedInstanceState.getInt(SAVE_CLICKED_POS, POS_UNKNOWN);
            fallbackRingtonePicker = savedInstanceState.getBoolean(KEY_FALLBACK_RINGTONE_PICKER);
        } else {
            fallbackRingtonePicker = false;
        }

        if (fallbackRingtonePicker) {
            setShowsDialog(false);
        } else {
            RingtonePreference preference = requireRingtonePreference();

            /*
             * Get whether to show the 'Default' item, and the URI to play when the
             * default is clicked
             */
            mHasDefaultItem = preference.getShowDefault();
            mUriForDefaultItem = RingtoneManager.getDefaultUri(preference.getRingtoneType());

            // Get whether to show the 'Silent' item
            mHasSilentItem = preference.getShowSilent();

            // Get the types of ringtones to show
            mType = preference.getRingtoneType();
            if (mType != -1) {
                mRingtoneManager.setType(mType);
            }

            // Get the URI whose list item should have a checkmark
            mExistingUri = preference.onRestoreRingtone();

            try {
                mCursor = mRingtoneManager.getCursor();

                // Check if cursor is valid.
                mCursor.getColumnNames();
            } catch (IllegalStateException ex) {
                // We throw this when there's an error with reflective method lookup.
                recover(preference, ex);
            } catch (IllegalArgumentException ex) {
                recover(preference, ex);
            } catch (Exception ex) {
                // You know what, fallback to system picker on any error. Example:
                // https://github.com/consp1racy/android-support-preference/issues/117
                recover(preference, ex);
            }
        }
    }

    private void recover(final @NonNull RingtonePreference preference, final @NonNull Throwable ex) {
        XpSupportPreferencePlugins.onError(ex, "RingtoneManager returned unexpected cursor.");

        mCursor = null;
        setShowsDialog(false);

        // Alternatively try starting system picker.
        Intent i = preference.buildRingtonePickerIntent();
        try {
            startActivityForResult(i, RC_FALLBACK_RINGTONE_PICKER);
        } catch (ActivityNotFoundException ex2) {
            onRingtonePickerNotFound(RC_FALLBACK_RINGTONE_PICKER);
        }
    }

    /**
     * Called when there's no ringtone picker available in the system.
     * Let the user know (using e.g. a Toast).
     * Just dismisses this fragment by default.
     *
     * @param requestCode You can use this code to launch another activity instead of dismissing
     *                    this fragment. The result must contain
     *                    {@link RingtoneManager#EXTRA_RINGTONE_PICKED_URI} extra.
     */
    public void onRingtonePickerNotFound(final int requestCode) {
        dismiss();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_FALLBACK_RINGTONE_PICKER) {
            if (resultCode == Activity.RESULT_OK) {
                requireRingtonePreference().onActivityResult(data);
            }
            dismiss();
        }
    }

    private void onOnPrepareDialogBuilder(@NonNull AlertDialog.Builder builder) {
        super.onPrepareDialogBuilder(builder);

        RingtonePreference preference = requireRingtonePreference();

        // The volume keys will control the stream that we are choosing a ringtone for
        getActivity().setVolumeControlStream(mRingtoneManager.inferStreamType());

        CharSequence title = preference.getNonEmptyDialogTitle();
        builder.setTitle(title);

        final Context context = builder.getContext();
        TypedArray a = context.obtainStyledAttributes(null, R.styleable.AlertDialog, R.attr.alertDialogStyle, 0);
        int singleChoiceItemLayout = a.getResourceId(R.styleable.AlertDialog_singleChoiceItemLayout, 0);
        a.recycle();

        final LayoutInflater inflater = LayoutInflater.from(context);
        final boolean isDefault = RingtoneManager.isDefault(mExistingUri);
        if (mHasDefaultItem /*|| isDefault*/) {
            mDefaultRingtonePos = addDefaultRingtoneItem(inflater, singleChoiceItemLayout);

            if (mClickedPos == POS_UNKNOWN && isDefault) {
                mClickedPos = mDefaultRingtonePos;
            }
        }

        final boolean isSilent = mExistingUri == null;
        if (mHasSilentItem /*|| isSilent*/) {
            mSilentPos = addSilentItem(inflater, singleChoiceItemLayout);

            // The 'Silent' item should use a null Uri
            if (mClickedPos == POS_UNKNOWN && isSilent) {
                mClickedPos = mSilentPos;
            }
        }

        if (mClickedPos == POS_UNKNOWN) {
            try {
            mClickedPos = getListPosition(mRingtoneManager.getRingtonePosition(mExistingUri));
            } catch (NumberFormatException e) {
                // This can happen on Android Q Beta 6 if the Uri doesn't end with a number.
                // https://github.com/consp1racy/android-support-preference/issues/120
                // https://issuetracker.google.com/issues/139935440
                final String message = "Couldn't resolve ringtone position: " + mExistingUri;
                XpSupportPreferencePlugins.onError(e, message);
            }
        }

        // If we still don't have selected item, but we're not silent, show the 'Unknown' item.
        if (mClickedPos == POS_UNKNOWN && mExistingUri != null) {
            final String ringtoneTitle;
            final SafeRingtone ringtone = SafeRingtone.obtain(context, mExistingUri);
            try {
                // We may not be able to list external ringtones
                // but we may be able to show selected external ringtone title.
                if (ringtone.canGetTitle()) {
                    ringtoneTitle = ringtone.getTitle();
                } else {
                    ringtoneTitle = null;
                }
            } finally {
                ringtone.stop();
            }
            if (ringtoneTitle == null) {
                mUnknownPos = addUnknownItem(inflater, singleChoiceItemLayout);
            } else {
                mUnknownPos = addStaticItem(inflater, singleChoiceItemLayout, ringtoneTitle);
            }
            mClickedPos = mUnknownPos;
        }

        SimpleCursorAdapter ringtoneAdapter = new SimpleCursorAdapter(context, singleChoiceItemLayout, mCursor,
                new String[]{MediaStore.Audio.Media.TITLE}, new int[]{android.R.id.text1});

        XpHeaderViewListAdapter adapter = new XpHeaderViewListAdapter(mStaticItems, null, ringtoneAdapter);

        // Put a checkmark next to an item.
        builder.setSingleChoiceItems(adapter, mClickedPos, mRingtoneClickListener);

        builder.setOnItemSelectedListener(this);
    }

    @Override
    protected void onPrepareDialogBuilder(@NonNull AlertDialog.Builder builder) {
        try {
            onOnPrepareDialogBuilder(builder);
        } catch (Throwable e) {
            recover(getRingtonePreference(), e);
        }
    }

    /**
     * Adds a static item to the top of the list. A static item is one that is not from the
     * RingtoneManager.
     *
     * @param text Text for the item.
     * @return The position of the inserted item.
     */
    private int addStaticItem(@NonNull LayoutInflater inflater, @LayoutRes int layout, CharSequence text) {
        TextView textView = (TextView) inflater.inflate(layout, null, false);
        textView.setText(text);

        XpHeaderViewListAdapter.FixedViewInfo item = new XpHeaderViewListAdapter.FixedViewInfo();
        item.view = textView;
        item.isSelectable = true;

        mStaticItems.add(item);
        return mStaticItems.size() - 1;
    }

    private int addDefaultRingtoneItem(@NonNull LayoutInflater inflater, @LayoutRes int layout) {
        switch (mType) {
            case RingtoneManager.TYPE_NOTIFICATION:
                return addStaticItem(inflater, layout, RingtonePreference.getNotificationSoundDefaultString(getContext()));
            case RingtoneManager.TYPE_ALARM:
                return addStaticItem(inflater, layout, RingtonePreference.getAlarmSoundDefaultString(getContext()));
            default:
                return addStaticItem(inflater, layout, RingtonePreference.getRingtoneDefaultString(getContext()));
        }
    }

    private int addSilentItem(@NonNull LayoutInflater inflater, @LayoutRes int layout) {
        return addStaticItem(inflater, layout, RingtonePreference.getRingtoneSilentString(getContext()));
    }

    private int addUnknownItem(@NonNull LayoutInflater inflater, @LayoutRes int layout) {
        return addStaticItem(inflater, layout, RingtonePreference.getRingtoneUnknownString(getContext()));
    }

    private int getListPosition(int ringtoneManagerPos) {
        // If the manager position is -1 (for not found), return that
        if (ringtoneManagerPos < 0) return POS_UNKNOWN;

        return ringtoneManagerPos + mStaticItems.size();
    }

    @Override
    public void onItemSelected(@NonNull AdapterView<?> parent, @NonNull View view, int position, long id) {
        playRingtone(position, DELAY_MS_SELECTION_PLAYED);
    }

    @Override
    public void onNothingSelected(@NonNull AdapterView<?> parent) {
        // No-op.
    }

    @Override
    public void onStart() {
        if (!getShowsDialog() && getDialog() != null) {
            try {
                // Don't show the dialog if we failed during onPrepareDialogBuilder.
                final Field f = DialogFragment.class.getDeclaredField("mDialog");
                f.setAccessible(true);
                f.set(this, null);
            } catch (IllegalAccessException ignore) {
            } catch (NoSuchFieldException ignore) {
            }
        }

        super.onStart();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (!getActivity().isChangingConfigurations()) {
            stopAnyPlayingRingtone();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (!getActivity().isChangingConfigurations()) {
            stopAnyPlayingRingtone();
        } else {
            saveAnyPlayingRingtone();
        }
    }

    @Override
    public void onSaveInstanceState(final @NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(SAVE_CLICKED_POS, mClickedPos);
        outState.putBoolean(KEY_FALLBACK_RINGTONE_PICKER, !getShowsDialog());
    }

    @Nullable
    public RingtonePreference getRingtonePreference() {
        return (RingtonePreference) getPreference();
    }

    @NonNull
    protected RingtonePreference requireRingtonePreference() {
        return checkPreferenceNotNull(getRingtonePreference(), RingtonePreference.class, this);
    }

    @Override
    public void onDialogClosed(boolean positiveResult) {
        // Stop playing the previous ringtone
        if (sPlayingRingtone == null) {
            mRingtoneManager.stopPreviousRingtone();
        }

        // The volume keys will control the default stream
        if (getActivity() != null) {
            getActivity().setVolumeControlStream(AudioManager.USE_DEFAULT_STREAM_TYPE);
        }

        if (positiveResult) {
            Uri uri;
            if (mClickedPos == mDefaultRingtonePos) {
                // Set it to the default Uri that they originally gave us
                uri = mUriForDefaultItem;
            } else if (mClickedPos == mSilentPos) {
                // A null Uri is for the 'Silent' item
                uri = null;
            } else if (mClickedPos == mUnknownPos) {
                // 'Unknown' was shown because it was persisted before showing the picker.
                // There's no change to persist, return immediately.
                return;
            } else {
                uri = mRingtoneManager.getRingtoneUri(getRingtoneManagerPosition(mClickedPos));
            }

            requireRingtonePreference().saveRingtone(uri);
        }
    }

    void playRingtone(int position, int delayMs) {
        mHandler.removeCallbacks(this);
        mSampleRingtonePos = position;
        mHandler.postDelayed(this, delayMs);
    }

    @NonNull
    private <T> T checkNotNull(final @Nullable T thing, final @NonNull String name) {
        if (thing == null) throw new IllegalStateException(name + " was null.");
        return thing;
    }

    public void run() {
        stopAnyPlayingRingtone();
        if (mSampleRingtonePos == mSilentPos) {
            return;
        }

//        final int oldSampleRingtonePos = mSampleRingtonePos;
        try {
            Ringtone ringtone = null;
            if (mSampleRingtonePos == mDefaultRingtonePos) {
                if (mDefaultRingtone == null) {
                    try {
                        checkNotNull(mUriForDefaultItem, "mUriForDefaultItem");
                        mDefaultRingtone = RingtoneManager.getRingtone(getContext(), mUriForDefaultItem);
                    } catch (SecurityException | IllegalStateException ex) {
                        XpSupportPreferencePlugins.onError(ex, "Failed to create default Ringtone from " + mUriForDefaultItem + ".");
                    }
                }
                /*
                 * Stream type of mDefaultRingtone is not set explicitly here.
                 * It should be set in accordance with mRingtoneManager of this Activity.
                 */
                if (mDefaultRingtone != null) {
                    mDefaultRingtone.setStreamType(mRingtoneManager.inferStreamType());
                }
                ringtone = mDefaultRingtone;
                mCurrentRingtone = null;
            } else if (mSampleRingtonePos == mUnknownPos) {
                if (mUnknownRingtone == null) {
                    try {
                        checkNotNull(mExistingUri, "mExistingUri");
                        mUnknownRingtone = RingtoneManager.getRingtone(getContext(), mExistingUri);
                    } catch (SecurityException | IllegalStateException ex) {
                        XpSupportPreferencePlugins.onError(ex, "Failed to create unknown Ringtone from " + mExistingUri + ".");
                    }
                }
                if (mUnknownRingtone != null) {
                    mUnknownRingtone.setStreamType(mRingtoneManager.inferStreamType());
                }
                ringtone = mUnknownRingtone;
                mCurrentRingtone = null;
            } else {
                final int position = getRingtoneManagerPosition(mSampleRingtonePos);
                try {
                    ringtone = mRingtoneManager.getRingtone(position);
                } catch (SecurityException ex) {
                    XpSupportPreferencePlugins.onError(ex, "Failed to create selected Ringtone from " + mRingtoneManager.getRingtoneUri(position) + ".");
                }
                mCurrentRingtone = ringtone;
            }

            if (ringtone != null) {
                try {
                    ringtone.play();
                } catch (NullPointerException ex) {
                    XpSupportPreferencePlugins.onError(ex, "RingtoneManager produced a Ringtone with null Uri.");
                    // https://github.com/consp1racy/android-support-preference/issues/105
                    // RingtoneManager can produce Ringtones with null Uri. Attempts to play fail.
                    mCurrentRingtone = null;
                    ringtone.stop();
                }
            }
        } catch (SecurityException ex) {
            // Don't play the inaccessible default ringtone.
            XpSupportPreferencePlugins.onError(ex, "Failed to play Ringtone.");
//            mSampleRingtonePos = oldSampleRingtonePos;
        }
    }

    private void saveAnyPlayingRingtone() {
        if (mDefaultRingtone != null && mDefaultRingtone.isPlaying()) {
            sPlayingRingtone = mDefaultRingtone;
        } else if (mUnknownRingtone != null && mUnknownRingtone.isPlaying()) {
            sPlayingRingtone = mUnknownRingtone;
        } else if (mCurrentRingtone != null && mCurrentRingtone.isPlaying()) {
            sPlayingRingtone = mCurrentRingtone;
        }
    }

    private void stopAnyPlayingRingtone() {
        if (sPlayingRingtone != null && sPlayingRingtone.isPlaying()) {
            sPlayingRingtone.stop();
        }
        sPlayingRingtone = null;

        if (mDefaultRingtone != null && mDefaultRingtone.isPlaying()) {
            mDefaultRingtone.stop();
        }

        if (mUnknownRingtone != null && mUnknownRingtone.isPlaying()) {
            mUnknownRingtone.stop();
        }

        if (mRingtoneManager != null) {
            mRingtoneManager.stopPreviousRingtone();
        }
    }

    private int getRingtoneManagerPosition(int listPos) {
        return listPos - mStaticItems.size();
    }

    private static class DummyAlertDialog extends AlertDialog {
        DummyAlertDialog(@NonNull Context context) {
            super(context);
        }
    }
}


text:
class User
  include Mongoid::Document
  include Mongoid::Search

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  ## Database authenticatable
  field :email,              type: String, default: ""
  field :encrypted_password, type: String, default: ""

  ## Recoverable
  field :reset_password_token,   type: String
  field :reset_password_sent_at, type: Time

  ## Rememberable
  field :remember_created_at, type: Time

  ## Trackable
  field :sign_in_count,      type: Integer, default: 0
  field :current_sign_in_at, type: Time
  field :last_sign_in_at,    type: Time
  field :current_sign_in_ip, type: String
  field :last_sign_in_ip,    type: String

  ## Confirmable
  # field :confirmation_token,   type: String
  # field :confirmed_at,         type: Time
  # field :confirmation_sent_at, type: Time
  # field :unconfirmed_email,    type: String # Only if using reconfirmable

  ## Lockable
  # field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts
  # field :unlock_token,    type: String # Only if unlock strategy is :email or :both
  # field :locked_at,       type: Time

  embeds_one :profile

  after_create do |document|
    document.create_profile
  end

  search_in :email, :profile => [:first_name, :last_name, :employee_id, :cell_phone, :address, :linkedIn_profile, :github_profile, :twitter_profile]

end

redpajama_set_name: RedPajamaGithub


text:
mojo::Remote<chrome::mojom::UtilWin> LaunchUtilWinServiceInstance();

#endif  // CHROME_BROWSER_WIN_UTIL_WIN_SERVICE_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<groupId>org.wikidata.wdtk</groupId>
	<artifactId>wdtk-parent</artifactId>
	<version>0.6.0-SNAPSHOT</version>
	<packaging>pom</packaging>

	<name>Wikidata Toolkit</name>
	<description>A Java-based library for working with Wikidata and Wikibase</description>
	<url>https://www.mediawiki.org/wiki/Wikidata_Toolkit</url>

	<modules>
		<module>wdtk-datamodel</module>
		<module>wdtk-dumpfiles</module>
		<module>wdtk-storage</module>
		<module>wdtk-wikibaseapi</module>
		<module>wdtk-util</module>
		<module>wdtk-testing</module>
		<module>wdtk-examples</module>
		<module>wdtk-distribution</module>
		<module>wdtk-rdf</module>
		<module>wdtk-client</module>
	</modules>

	<licenses>
		<license>
			<name>Apache License, Version 2.0</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
		</license>
	</licenses>

	<inceptionYear>2014</inceptionYear>

	<organization>
		<name>Wikidata Toolkit Developers</name>
	</organization>

	<developers>
		<developer>
			<id>markus</id>
			<name>Markus Kroetzsch</name>
			<email>markus@semantic-mediawiki.org</email>
		</developer>
		<developer>
			<id>julian</id>
			<name>Julian Mendez</name>
			<email>julian.mendez@tu-dresden.de</email>
		</developer>
		<developer>
			<id>fer-rum</id>
			<name>Fredo Erxleben</name>
			<email>fredo.erxleben@tu-dresden.de</email>
		</developer>
		<developer>
			<id>michael</id>
			<name>Michael Günther</name>
			<email>guenthermi50@yahoo.de</email>
		</developer>
	</developers>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<apacheCommonsCompressVersion>1.9</apacheCommonsCompressVersion>
		<apacheCommonsLangVersion>3.3.2</apacheCommonsLangVersion>
		<apacheHttpVersion>4.3.3</apacheHttpVersion>
		<commonsCliVersion>1.2</commonsCliVersion>
		<ini4JVersion>0.5.2</ini4JVersion>
		<jacksonVersion>2.5.0</jacksonVersion>
		<junitVersion>4.12</junitVersion>
		<mockitoVersion>1.10.19</mockitoVersion>
		<sesameVersion>2.7.14</sesameVersion>
		<slf4jVersion>1.7.10</slf4jVersion>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junitVersion}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-core</artifactId>
			<version>${mockitoVersion}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4jVersion}</version>
		</dependency>
		<dependency>

			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>${apacheCommonsLangVersion}</version>
		</dependency>
	</dependencies>

	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.codehaus.mojo</groupId>
					<artifactId>license-maven-plugin</artifactId>
					<version>1.6</version>
					<configuration />
					<executions>
						<execution>
							<id>first</id>
							<goals>
								<goal>update-file-header</goal>
								<goal>update-project-license</goal>
							</goals>
							<phase>process-sources</phase>
							<configuration>
								<licenseName>apache_v2</licenseName>
								<roots>
									<root>src/main/java</root>
									<root>src/test/java</root>
								</roots>
							</configuration>
						</execution>
					</executions>
				</plugin>
				<plugin>

					<groupId>org.eclipse.m2e</groupId>
					<artifactId>lifecycle-mapping</artifactId>
					<version>1.0.0</version>
					<configuration>
						<lifecycleMappingMetadata>
							<pluginExecutions>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>org.codehaus.mojo</groupId>
										<artifactId>license-maven-plugin</artifactId>
										<versionRange>[1.2,)</versionRange>
										<goals>
											<goal>update-project-license</goal>
											<goal>update-file-header</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<ignore />
									</action>
								</pluginExecution>
							</pluginExecutions>
						</lifecycleMappingMetadata>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
		<plugins>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>license-maven-plugin</artifactId>
			</plugin>
			<plugin>

				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
			<plugin>

				<groupId>org.eluder.coveralls</groupId>
				<artifactId>coveralls-maven-plugin</artifactId>
				<version>2.1.0</version>
			</plugin>
			<plugin>

				<groupId>org.codehaus.mojo</groupId>
				<artifactId>cobertura-maven-plugin</artifactId>
				<version>2.7</version>
				<configuration>
					<format>xml</format>

					<maxmem>256m</maxmem>

					<aggregate>true</aggregate>
				</configuration>
			</plugin>
			<plugin>

				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.9.1</version>
				<configuration>
					<bottom><![CDATA[Copyright © {inceptionYear}–{currentYear} {organizationName}. Generated from source code published under the Apache License 2.0. For more information, see the Wikidata Toolkit homepage]]></bottom>
				</configuration>
			</plugin>
			<plugin>

				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-scm-publish-plugin</artifactId>
				<version>1.1</version>
				<configuration>
					<checkoutDirectory>${project.build.directory}/scmpublish</checkoutDirectory>
					<checkinComment>Publishing javadoc for ${project.artifactId}:${project.version}</checkinComment>
					<content>${project.reporting.outputDirectory}/apidocs</content>
					<pubScmUrl>scm:git:https://github.com/Wikidata/Wikidata-Toolkit.git</pubScmUrl>
					<scmBranch>gh-pages</scmBranch>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<profiles>
		<profile>
			<id>sign</id>
			<build>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-source-plugin</artifactId>
						<version>2.2.1</version>
						<executions>
							<execution>
								<id>sources-jars</id>
								<goals>
									<goal>jar-no-fork</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-javadoc-plugin</artifactId>
						<version>2.9.1</version>
						<executions>
							<execution>
								<id>javadoc-jars</id>
								<goals>
									<goal>jar</goal>
								</goals>
							</execution>
							<execution>
								<id>aggregate-javadoc-jar</id>
								<goals>
									<goal>aggregate-jar</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
					<plugin>
							<groupId>org.apache.maven.plugins</groupId>
							<artifactId>maven-gpg-plugin</artifactId>
							<version>1.5</version>
							<executions>
									<execution>
											<id>sign-artifacts</id>
											<phase>verify</phase>
											<goals>
													<goal>sign</goal>
											</goals>
									</execution>
							</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
	</profiles>

	<scm>
		<url>https://github.com/Wikidata/Wikidata-Toolkit.git</url>
		<connection>scm:git:https://github.com/Wikidata/Wikidata-Toolkit.git</connection>
		<developerConnection>scm:git:https://github.com/Wikidata/Wikidata-Toolkit.git</developerConnection>
	</scm>

</project>


text:
package com.capitalone.dashboard.datafactory.jira.sdk.util;

import java.io.IOException;
import java.net.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.capitalone.dashboard.datafactory.jira.sdk.config.ApiPropertiesSupplier;

/**
 * This class retains the ability to gather user and application system meta-data when
 * and where needed.  This can be used to either inform a given application's actions
 * on a given system, or to send an application tracking packet as a header to
 * Jira for performance monitoring purposes.  This is intended to be used only for application monitoring
 * purposes.
 *
 * @author KFK884
 */
public class SystemInfo {
	/**
	 * Houses the concatenated String for the returned Jira API transaction header
	 */
	protected String systemInfoMsg;
	/**
	 * Houses the user name of a given system using this library
	 */
	protected String userName;
	/**
	 * Houses the Java main class name using this library
	 */
	protected String mainClass;

	/**
	 * Initialized class for the logging mechanism for this class
	 */
	private static final Log log = LogFactory.getLog(ApiPropertiesSupplier.class);

	/**
	 * Default constructor for SystemInfo class
	 */
	public SystemInfo() {
		systemInfoMsg = "";
		userName = "";
		mainClass = "";
	}

    /**
    * This method search into Thread Stack Trace and get the bottom entry of
    * Stack, which would be the main class name of a given application using this
    * library.  It also pulls the user name who is running this program based on
    * their individual system account name.  Other meta-data will also be gathered
    * this method and added to the header.
    *
     * @return : systemInfoMsg A string concatenation of local application system and
     * user meta-data to be added to a given transaction header.
    */
    public String generateApplicationUseHeader() {
    	systemInfoMsg = "";

    	this.setUserName();
    	this.setClassName();

        systemInfoMsg = "SYSTEM INFO HEADER FOR JIRA API TRANSACTION: " + getUserName() + "; " + getClassName();
        log.info("USER-AGENT-HDR:  [" + systemInfoMsg + "]");
        return systemInfoMsg;
    }

    /**
     * Sets the local value of a user name based on system settings
     */
    private void setUserName() {
    	userName = "User Name of System: " + System.getProperty("user.name");
    }

    /**
     * Manually provide a given application's user name (not required for use of this
     * class).  Useful if the user name will be a non-expiring account or system
     * account.
     */
    public void setUserName(String userName) {
    	this.userName = userName;
    }

    /**
     * Sets the local value of the main class of a given application using this library
     */
    private void setClassName() {
    	mainClass = System.getProperty("java.class.path");
    	mainClass = mainClass.replaceAll(" ", "%20");
    	mainClass = mainClass.replaceAll(";", ",");
    	mainClass = mainClass.replaceAll("[^a-zA-Z0-9/\\\\s_%,]+", "_");
        mainClass = "Main Application Jar: " + mainClass;
    }

    /**
     * Manually provide a given application's main class name (not required for use of
     * this class).  Useful if the application which is leveraging this library is using
     * Java EE beans or non-standard Java main method/class structure.
     */
    public void setClassName(String mainClass) {
    	this.mainClass = mainClass;
    }

    /**
     * Retrieves the currently set user name for the system and application using this
     * Java library
     *
     * @return userName String user name
     */
    public String getUserName() {
    	return this.userName;
    }

    /**
     * Retrieves the currently set main class name for this Java application using
     * the Jira Client library
     *
     * @return mainClass String main class name of the Java application
     */
    public String getClassName() {
    	return this.mainClass;
    }

    /**
     * Retrieves the containing Jar URL and name that is using this connector package at
     * runtime.
     *
     * @author Nirav Thaker
     * @link http://blog.nirav.name/2008/03/how-to-find-which-jar-file-contains.html?showComment=1204706820000
     *
     * @return The Jar URL and name as a string of the currently containing Jar at runtime
     */
    protected String getJarURL() {
        URL clsUrl = getClass().getResource(getClass().getSimpleName() + ".class");

        if (clsUrl != null) {
            try {
                URLConnection conn = clsUrl.openConnection();
                if (conn instanceof JarURLConnection) {
                    JarURLConnection connection = (JarURLConnection) conn;
                    return connection.getJarFileURL().toString();
                }
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return "No Jar or class name retrieved";
    }

    /**
	 * Method returns code source of given class. This is URL of classpath
	 * folder, zip or jar file. If code source is unknown, returns a string
	 * indicating that nothing was retrieved.
	 *
	 * @author Andrei Solntsev
	 * @link http://asolntsev.blogspot.com/2008/03/how-to-find-which-jar-file-
	 *       contains.html
	 *
	 * @param clazz
	 *            Will only take the SystemInfo class as a parameter, for
	 *            security purposes
	 * @return A class directory: For example,
	 *         "file:/C:/jdev10/jdev/mywork/classes/" or
	 *         "file:/C:/works/projects/classes12.zip"
	 */
    protected String getCodeSource(Class<SystemInfo> clazz) {
	    if (clazz == null || clazz.getProtectionDomain() == null || clazz.getProtectionDomain().getCodeSource() == null || clazz.getProtectionDomain().getCodeSource().getLocation() == null) {
	       // This typically happens for system classloader
	       // (java.lang.* etc. classes)
	       return "No Jar or class name retrieved";
	    }

	    return clazz.getProtectionDomain().getCodeSource().getLocation().toString();
    }
}


text:
<!DOCTYPE html>

        <title>Mailboxing - iPhone/iPad game</title>
        <link href="css/screen.css" rel="stylesheet" type="text/css" />
        <meta charset="utf-8">
        <meta property="og:type" content="game" />
        <meta property="og:url" content="http://www.mailboxing.com" />
        <meta property="fb:app_id" content="109592955824633" />
        <meta property="og:image" content="images/car2.png" />
        <meta property="og:site_name" content="Mailboxing" />
        <meta property="og:description" content="The most corrupted post-Soviet city has finally waken up from its never-ending winter darkness. While some of the Russian grannies are making her name known by trying to become a mega pop-star band by singing mellow tones in the Eurovision Song Festival, other senior-ladies prefer more aggressive melodies – smashing their neighbors mailboxes in the iPhone/iPad game Mailboxing!"
        />
        <meta name="keywords" content="Mailboxing, postman, mailbox, crash, smash, hit, mailman, mail, boxing, bat, driving, racing, box" />
        <meta name="description" content="The most corrupted post-Soviet city has finally waken up from its never-ending winter darkness. While some of the Russian grannies are making her name known by trying to become a mega pop-star band by singing mellow tones in the Eurovision Song Festival, other senior-ladies prefer more aggressive melodies – smashing their neighbors mailboxes in the iPhone/iPad game Mailboxing!"
        />

 Tweet

Tweet Tweet

Looky, look what the

is saying:

Incognito

"It's a matter of time before the Kremlin ban this game."

148apps.com

"I think Mailboxing is a fun little game for all ages. Younger kids are sure to get a kick out of it, just as long as they don't get any crazy ideas about batting down mailboxes in real life."

Central App Review

"Mailboxing is in a sort of 3D setting, so buildings, cars, and other objects look like they are coming up at you. This is one of the things that makes this game worth downloading and fun to play."

theportablegamer.com

"Some games may go a little overboard (think GTA and the Gangstar titles) but Mailboxing puts just enough comic mischief in to be suitable to all players."

Follow Us

Stay Informed

                    <form id="signup" action="/index.php" method="get">

                                <input type="text" name="email" id="email" placeholder="Enter your e-mail" />

                            <input type="submit" class="submit" name="submit" value="Sign Up" alt="Go" />

                    </form>

                        2012 Asketic Labs.


text: this is a exercise of algrithm


text:
package org.unitime.timetable.gwt.client.solver.suggestions;

import java.util.List;

import org.unitime.timetable.gwt.client.aria.AriaButton;
import org.unitime.timetable.gwt.client.page.UniTimeNotifications;
import org.unitime.timetable.gwt.client.solver.SolverCookie;
import org.unitime.timetable.gwt.client.widgets.FilterBox.Chip;
import org.unitime.timetable.gwt.client.widgets.SimpleForm;
import org.unitime.timetable.gwt.client.widgets.UniTimeHeaderPanel;
import org.unitime.timetable.gwt.client.widgets.UniTimeTable.MouseClickListener;
import org.unitime.timetable.gwt.client.widgets.UniTimeTable.TableEvent;
import org.unitime.timetable.gwt.command.client.GwtRpcService;
import org.unitime.timetable.gwt.command.client.GwtRpcServiceAsync;
import org.unitime.timetable.gwt.resources.GwtMessages;
import org.unitime.timetable.gwt.shared.SuggestionsInterface.ComputeSuggestionsRequest;
import org.unitime.timetable.gwt.shared.SuggestionsInterface.SelectedAssignment;
import org.unitime.timetable.gwt.shared.SuggestionsInterface.SelectedAssignmentsRequest;
import org.unitime.timetable.gwt.shared.SuggestionsInterface.Suggestion;
import org.unitime.timetable.gwt.shared.SuggestionsInterface.Suggestions;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * @author Tomas Muller
 */
public class SuggestionsWidget extends SimpleForm {
	protected static final GwtMessages MESSAGES = GWT.create(GwtMessages.class);

	private SuggestionsPageContext iContext;
	private UniTimeHeaderPanel iHeader, iFooter;
	private ComputeSuggestionsRequest iRequest;
	private SuggestionsTable iTable;
	private int iHeaderRow = 0, iFooterRow = 0;
	protected static GwtRpcServiceAsync RPC = GWT.create(GwtRpcService.class);
	private boolean iSuggestionsComputed = false;
	private SuggestionsFilter iFilter = null;
	private AriaButton iApply = null;

	public SuggestionsWidget(SuggestionsPageContext context) {
		super(3);
		iContext = context;
		iHeader = new UniTimeHeaderPanel(MESSAGES.headerSuggestions());
		iHeader.setCollapsible(SolverCookie.getInstance().isShowSuggestions());
		iHeader.addCollapsibleHandler(new ValueChangeHandler<Boolean>() {
			@Override
			public void onValueChange(ValueChangeEvent<Boolean> event) {
				SolverCookie.getInstance().setShowSuggestions(event.getValue());
				if (event.getValue()) {
					showSuggestions();
				} else {
					hideSuggestions();
				}
			}
		});
		iFooter = new UniTimeHeaderPanel();
		iFooter.addButton("deeper", MESSAGES.buttonSearchDeeper(), new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				iFilter.removeChip(new Chip("depth", null), false);
				iFilter.addChip(new Chip("depth", "D" + (iRequest.getDepth() + 1)), false);
				iRequest.setDepth(iRequest.getDepth() + 1);
				computeSuggestions();
			}
		});
		iFooter.addButton("longer", MESSAGES.buttonSearchLonger(), new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				iFilter.removeChip(new Chip("timeout", null), false);
				iFilter.addChip(new Chip("timeout", "T" + (2 * iRequest.getTimeLimit() / 1000)), false);
				iRequest.setTimeLimit(2 * iRequest.getTimeLimit());
				computeSuggestions();
			}
		});
		removeStyleName("unitime-NotPrintableBottomLine");
		iApply = new AriaButton(MESSAGES.buttonSearch());
		iApply.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				computeSuggestions();
			}
		});
	}

	public void onSelection(Suggestion suggestion) {}

	public void clearMessage() {
		iHeader.clearMessage();
		iFooter.clearMessage();
	}

	public void setInfoMessage(String message) {
		iHeader.clearMessage();
		iFooter.setMessage(message);
	}

	public void showLoading() {
		iHeader.showLoading();
		iFooter.clearMessage();
	}

	public void setRequest(SelectedAssignmentsRequest request) {
		setSelection(request.getAssignments(), request.getClassId());
	}

	public void setSelection(List<SelectedAssignment> assignments, Long classId) {
		clearMessage();
		if (iFilter == null) {
			iFilter = new SuggestionsFilter();
			iFilter.setValue(SolverCookie.getInstance().getSuggestionsFilter());
		}
		iFilter.setClassId(classId);
		clear();
		iSuggestionsComputed = false;
		if (iTable == null) {
			iTable = new SuggestionsTable(iContext.getProperties(), true);
			iTable.setVisible(false);
			iTable.addMouseClickListener(new MouseClickListener<Suggestion>() {
				@Override
				public void onMouseClick(TableEvent<Suggestion> event) {
					if (event.getData() != null) onSelection(event.getData());
				}
			});
		} else {
			iTable.setVisible(false);
		}
		iHeaderRow = addHeaderRow(iHeader);
		int filterRow = addRow(MESSAGES.propFilter(), iFilter, 1);
		setWidget(filterRow, 2, iApply);
		addRow(iTable);
		iFooter.setEnabled("longer", false);
		iFooter.setEnabled("deeper", false);
		iFooterRow = addBottomRow(iFooter);
		getFlexCellFormatter().removeStyleName(iFooterRow, 0, "unitime-TopLine");
		iRequest = new ComputeSuggestionsRequest(classId, assignments);
		if (SolverCookie.getInstance().isShowSuggestions()) {
			showSuggestions();
		} else {
			hideSuggestions();
		}
	}

	protected void hideSuggestions() {
		for (int i = iHeaderRow + 1; i <= iFooterRow; i++)
			getRowFormatter().setVisible(i, false);
	}

	protected void showSuggestions() {
		for (int i = iHeaderRow + 1; i <= iFooterRow; i++)
			getRowFormatter().setVisible(i, true);
		if (!iSuggestionsComputed)
			computeSuggestions();
	}

	protected void computeSuggestions() {
		iSuggestionsComputed = true;
		iTable.setVisible(false);
		iApply.setEnabled(false);
		showLoading();
		Chip depth = iFilter.getChip("depth");
		if (depth != null)
			iRequest.setDepth(Integer.parseInt(depth.getValue().startsWith("D") || depth.getValue().startsWith("d") ? depth.getValue().substring(1) : depth.getValue()));
		Chip results = iFilter.getChip("results");
		if (results != null)
			iRequest.setLimit(Integer.parseInt(results.getValue().startsWith("R") || results.getValue().startsWith("r") ? results.getValue().substring(1) : results.getValue()));
		Chip timeout = iFilter.getChip("timeout");
		if (timeout != null)
			iRequest.setTimeLimit(1000 * Integer.parseInt(timeout.getValue().startsWith("T") || timeout.getValue().startsWith("t") ? timeout.getValue().substring(1) : timeout.getValue()));
		iRequest.setSameRoom(iFilter.hasChip(new Chip("flag", "Same Room")));
		iRequest.setSameTime(iFilter.hasChip(new Chip("flag", "Same Time")));
		iRequest.setAllowBreakHard(iFilter.hasChip(new Chip("flag", "Allow Break Hard")));
		iRequest.setPlacements(iFilter.hasChip(new Chip("mode", "Placements")));
		iRequest.setFilter(iFilter.getValue());
		iFooter.setEnabled("longer", false);
		iFooter.setEnabled("deeper", false);
		RPC.execute(iRequest, new AsyncCallback<Suggestions>() {

			@Override
			public void onFailure(Throwable caught) {
				iHeader.setErrorMessage(MESSAGES.failedToComputeSuggestions(caught.getMessage()));
				UniTimeNotifications.error(MESSAGES.failedToComputeSuggestions(caught.getMessage()), caught);
				iApply.setEnabled(true);
			}

			@Override
			public void onSuccess(Suggestions result) {
				iTable.setValue(result.getSuggestions());
				iTable.setVisible(true);
				iApply.setEnabled(true);
				iFooter.setEnabled("longer", result.isTimeoutReached());
				iFooter.setEnabled("deeper", true);
				if (result.size() == 0) {
					if (result.isTimeoutReached())
						setInfoMessage(MESSAGES.suggestionsNoteTimeoutNoResults(result.getTimeLimit() / 1000, result.getNrCombinationsConsidered(), result.getDepth()));
					else
						setInfoMessage(MESSAGES.suggestionsNoteNoTimeoutNoResults(result.getNrCombinationsConsidered(), result.getDepth()));
				} else if (result.size() < result.getNrSolutions()) {
					if (result.isTimeoutReached())
						setInfoMessage(MESSAGES.suggestionsNoteTimeoutNResults(result.getTimeLimit() / 1000, result.getNrCombinationsConsidered(), result.getDepth(), result.getSuggestions().size(), result.getNrSolutions()));
					else
						setInfoMessage(MESSAGES.suggestionsNoteNoTimeoutNResults(result.getNrCombinationsConsidered(), result.getDepth(), result.getSuggestions().size(), result.getNrSolutions()));
				} else {
					if (result.isTimeoutReached())
						setInfoMessage(MESSAGES.suggestionsNoteTimeoutAllResults(result.getTimeLimit() / 1000, result.getNrCombinationsConsidered(), result.getDepth(), result.getSuggestions().size()));
					else
						setInfoMessage(MESSAGES.suggestionsNoteNoTimeoutAllResults(result.getNrCombinationsConsidered(), result.getDepth(), result.getSuggestions().size()));
				}
			}
		});
	}
}


text:
package biz.enef.svgjs

import scala.scalajs.js

trait Container extends Parent {

}


text:
package cn.edu.sjtu.songyuke.mental.ir.arithmetic;

import cn.edu.sjtu.songyuke.mental.ir.data.Data;
import cn.edu.sjtu.songyuke.mental.ir.data.DataValue;
import cn.edu.sjtu.songyuke.mental.translator.MIPSMachine;

/**
 * Created by Songyu on 16/4/28.
 */
public class CompareGreater extends Compare {
    public CompareGreater() {
        super();
    }
    public CompareGreater(DataValue lhs, DataValue rhs) {
        super(lhs, rhs);
    }
    public CompareGreater(Data lhs, Data rhs, DataValue res) {
        super(lhs, rhs, res);
    }
    @Override
    public String toMips(MIPSMachine mipsMachine) {
        return this.toMips(mipsMachine, "sgt");
    }
    @Override
    public String toMips() {
        return this.toMips("sgt");
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Hl7.Fhir.Model;
using Hl7.Fhir.Rest;

namespace MyFirstRead
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            // Choose your preferred FHIR server or add your own
            // More at http://wiki.hl7.org/index.php?title=Publicly_Available_FHIR_Servers_for_testing

            //var client = new FhirClient("http://test.fhir.org/r3/open");
            var client = new FhirClient("http://vonk.furore.com");
            //var client = new FhirClient("http://fhirtest.uhn.ca/baseDstu3");

            try
            {
                var obs = client.Read<Observation>("Observation/example");

                txtDisplay.Text = "Observation read, id: " + obs.Id;
            }
            catch (Exception err)
            {
                txtError.Lines = new string[] { "An error has occurred:", err.Message };
            }
        }
    }
}


text:
 /*
  *   Alterations to this file by Abdullatif Ismail
  *
  *   To the extent possible under law, the person who associated CC0
  *   with the alterations to this file has waived all copyright and
  *   related or neighboring rights to the alterations made to this file.
  *
  *   You should have received a copy of the CC0 legalcode along with
  *   this work.  If not, see
  *   <http://creativecommons.org/publicdomain/zero/1.0/>.
  */

#include <modules/graph2d/graph2dmodule.h>

#include <modules/graph2d/datastructures/graph2ddata.h>
#include <modules/graph2d/processors/dataframecollector.h>
#include <modules/graph2d/processors/hdf5pathselectionint.h>
#include <modules/graph2d/processors/hdf5pathselectionintvector.h>
#include <modules/graph2d/processors/hdf5pathselectionallchildren.h>
#include <modules/graph2d/processors/hdf5topoint.h>
#include <modules/graph2d/processors/hdf5tofunction.h>
#include <modules/graph2d/processors/functionoperationunary.h>
#include <modules/graph2d/processors/functionoperationnary.h>
#include <modules/graph2d/processors/functiontodataframe.h>
#include <modules/graph2d/processors/lineplotprocessor.h>

namespace inviwo {

graph2dModule::graph2dModule(InviwoApplication* app) : InviwoModule(app, "graph2d") {

    // Processors.
    registerProcessor<DataFrameCollector>();
    registerProcessor<HDF5PathSelectionInt>();
    registerProcessor<HDF5PathSelectionIntVector>();
    registerProcessor<HDF5PathSelectionAllChildren>();
    registerProcessor<HDF5ToPoint>();
    registerProcessor<HDF5ToFunction>();
    registerProcessor<FunctionOperationUnary>();
    registerProcessor<FunctionOperationNary>();
    registerProcessor<FunctionToDataFrame>();
    registerProcessor<LinePlotProcessor>();

    // Ports.
    registerPort<DataOutport<Point>>();
    registerPort<DataInport<Point>>();
    registerPort<DataOutport<Function>>();
    registerPort<DataInport<Function>>();
}

} // namespace


text:
package org.apache.flink.python.util;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.DiscardingSink;
import org.apache.flink.streaming.api.graph.StreamGraph;

import org.junit.Test;

import java.lang.reflect.InvocationTargetException;
import java.util.Collections;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
 * A test class to test PythonConfigUtil getting executionEnvironment correctly.
 */
public class PythonConfigUtilTest {

	@Test
	public void testGetEnvironmentConfig() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
		StreamExecutionEnvironment executionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment();
		Configuration envConfig = PythonConfigUtil.getEnvConfigWithDependencies(executionEnvironment);
		assertNotNull(envConfig);
	}

	@Test
	public void testJobName() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
		String jobName = "MyTestJob";
		Configuration config = new Configuration();
		config.set(PipelineOptions.NAME, jobName);
		StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(config);

		env.fromCollection(Collections.singletonList("test")).addSink(new DiscardingSink<>());
		StreamGraph streamGraph = PythonConfigUtil.generateStreamGraphWithDependencies(env, true);
		assertEquals(jobName, streamGraph.getJobName());
	}
}


text:
function [ColourConstantImage, luminance] = ColourConstancyGreyWorld(InputImage, ScaleFactor)
%ColourConstancyGreyWrold  applies the grey world algorithm to the input.
%   Explanation http://en.wikipedia.org/wiki/Color_normalization#Grey_world
%
% inputs
%   InputImage   the input image.
%   ScaleFactor  the scale factor, default is average intensity value.
%
% outputs
%   ColourConstantImage  the colour constant image in range of [0, 1].
%   luminance            the estimated luminance of the scene.
%
% Examples
%   im = imread('peppers.png');
%   imout = ColourConstancyGreyWorld(im);
%   figure; imshow(uint8(imout .* 255));
%
% See also: ColourConstancy
%

InputImage = double(InputImage);

luminance = mean(mean(InputImage));
luminance = reshape(luminance, 1, 3);

if nargin < 2
  ScaleFactor = mean(luminance);
end

k = ScaleFactor ./ luminance;

ColourConstantImage = MatChansMulK(InputImage, k);

end


text:
<?php
/**
 * Created by PhpStorm.
 * User: 觐松
 * Date: 2016/3/23
 * Time: 14:03
 */

namespace backend\models\search;

use yii\data\ActiveDataProvider;
use common\models\Video as VideoModel;

class Video extends VideoModel
{
    public function rules()
    {
        return [
            [['name', 'url'], 'string'],
        ];
    }

    public function search($params)
    {
        $this->load($params);
        $query = VideoModel::find();
        $query->andFilterWhere(['like', 'name', $this->name]);
        $query->andFilterWhere(['like', 'url', $this->url]);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => \Yii::$app->params['pageSize'],
            ],
        ]);
        return $dataProvider;
    }
}


text:
namespace dialog::editor
{
	class COptions : public CEditor
	{
	public:
		COptions(_In_ CWnd* pWnd);
		~COptions();
		bool NeedPropRefresh() const noexcept;

	private:
		_Check_return_ ULONG HandleChange(UINT nID) override;

		void OnOK() override;

		bool m_bNeedPropRefresh{};
	};

	static std::wstring CLASS = L"COptions";

	COptions::COptions(_In_ CWnd* pWnd) : CEditor(pWnd, IDS_SETOPTS, NULL, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL)
	{
		TRACE_CONSTRUCTOR(CLASS);
		EnableScroll();

		output::DebugPrintEx(
			output::dbgLevel::Generic, CLASS, L"COptions(", L"Building option sheet - adding fields\n");

		for (auto& regKey : registry::RegKeys)
		{
			if (!regKey || !regKey->uiOptionsPrompt) continue;

			if (registry::regOptionType::check == regKey->ulRegOptType)
			{
				AddPane(viewpane::CheckPane::Create(
					regKey->uiOptionsPrompt, regKey->uiOptionsPrompt, 0 != regKey->ulCurDWORD, false));
			}
			else if (registry::regOptionType::string == regKey->ulRegOptType)
			{
				AddPane(viewpane::TextPane::CreateSingleLinePane(
					regKey->uiOptionsPrompt, regKey->uiOptionsPrompt, regKey->szCurSTRING, false));
			}
			else if (registry::regOptionType::stringHex == regKey->ulRegOptType)
			{
				AddPane(
					viewpane::TextPane::CreateSingleLinePane(regKey->uiOptionsPrompt, regKey->uiOptionsPrompt, false));
				SetHex(regKey->uiOptionsPrompt, regKey->ulCurDWORD);
			}
			else if (registry::regOptionType::stringDec == regKey->ulRegOptType)
			{
				AddPane(
					viewpane::TextPane::CreateSingleLinePane(regKey->uiOptionsPrompt, regKey->uiOptionsPrompt, false));
				SetDecimal(regKey->uiOptionsPrompt, regKey->ulCurDWORD);
			}
		}
	}

	COptions::~COptions() { TRACE_DESTRUCTOR(CLASS); }

	void COptions::OnOK()
	{
		// need to grab this FIRST
		registry::debugFileName = GetStringW(registry::debugFileName.uiOptionsPrompt);

		if (GetHex(registry::debugTag.uiOptionsPrompt) != registry::debugTag)
		{
			registry::debugTag = GetHex(registry::debugTag.uiOptionsPrompt);
			output::outputVersion(output::dbgLevel::VersionBanner, nullptr);
		}

		output::SetDebugOutputToFile(GetCheck(registry::debugToFile.uiOptionsPrompt));

		// Remaining options require no special handling - loop through them
		for (auto& regKey : registry::RegKeys)
		{
			if (!regKey || !regKey->uiOptionsPrompt) continue;

			if (registry::regOptionType::check == regKey->ulRegOptType)
			{
				if (regKey->bRefresh && regKey->ulCurDWORD != static_cast<ULONG>(GetCheck(regKey->uiOptionsPrompt)))
				{
					m_bNeedPropRefresh = true;
				}

				regKey->ulCurDWORD = GetCheck(regKey->uiOptionsPrompt);
			}
			else if (registry::regOptionType::stringHex == regKey->ulRegOptType)
			{
				regKey->ulCurDWORD = GetHex(regKey->uiOptionsPrompt);
			}
			else if (registry::regOptionType::stringDec == regKey->ulRegOptType)
			{
				regKey->ulCurDWORD = GetDecimal(regKey->uiOptionsPrompt);
			}
		}

		// Commit our values to the registry
		registry::WriteToRegistry();

		CEditor::OnOK();
	}

	_Check_return_ ULONG COptions::HandleChange(const UINT nID) { return CEditor::HandleChange(nID); }

	bool COptions::NeedPropRefresh() const noexcept { return m_bNeedPropRefresh; }

	bool DisplayOptionsDlg(_In_ CWnd* lpParentWnd)
	{
		COptions MyOptions(lpParentWnd);
		MyOptions.DoModal();

		mapistub::ForceOutlookMAPI(registry::forceOutlookMAPI);
		mapistub::ForceSystemMAPI(registry::forceSystemMAPI);
		return MyOptions.NeedPropRefresh();
	}
} // namespace dialog::editor


text:
require 'test_helper'

class CountdownTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
////////////////////////////////////////////////////////////////////////////
//  GameState.hpp -                                                       //
//    Main Controller of the Game. This is where the game logic is        //
//    updated, and the scene hierarchy is maintained.                     //
//                                                                        //
//    This is a singleton defined as GAMESTATE                            //
//                                                                        //
////////////////////////////////////////////////////////////////////////////
#ifndef __GAME_STATE_H__
#define __GAME_STATE_H__

#include "Game.hpp"

class Spatial;
class GameObject;
class GameUpdateThread;
class thread;

class GameState
{

  public:
    GameState();
    ~GameState();

    // Called on startup, take care of creating threads
    bool Init();
    void Shutdown();

    // Wait until all updater threads have terminated.
    void JoinAll();

    // Call to update all objects. (For single thread mode)
    void Update();

    // List of GameObjects, each represents a visual object.
    // (Tripod or planet)
    sh_ptr<GameObject> * akGameObjects;

  private:

    // Update threads
    std::vector<GameUpdateThread*> akUpdaters;
    std::vector<thread*> akThreads;

};

// define singleton
extern GameState GAMESTATE;

#endif // __GAME_STATE_H__


text:
<?php

namespace Naucon\HtmlBuilder;

/**
 * Abtract Html Table Row Class
 *
 * @abstract
 * @package    HtmlBuilder
 * @author     Sven Sanzenbacher
 */
abstract class HtmlTableRowAbstract extends HtmlElementUniversalAbstract
{
    /**
     * @return      bool                    html element attribute align (left, center, right)
     */
    public function getAlign()
    {
        return $this->getAttribute('align');
    }

    /**
     * @param       bool        $align      html element attribute align (left, center, right, justify, char)
     * @return      HtmlTableRowAbstract
     */
    public function setAlign($align)
    {
        switch ($align)
        {
            case 'left':
                $this->setAttribute('align', 'left');
                break;
            case 'center':
                $this->setAttribute('align', 'center');
                break;
            case 'right':
                $this->setAttribute('align', 'right');
                break;
            case 'justify':
                $this->setAttribute('align', 'justify');
                break;
            case 'char':
                $this->setAttribute('align', 'char');
                break;
            case null:
            default:
                $this->setAttribute('align', null);
                break;
        }
        return $this;
    }

    /**
     * @return      bool                    html element attribute valign (top, middle, bottom, baseline)
     */
    public function getValign()
    {
        return $this->getAttribute('valign');
    }

    /**
     * @param       bool        $align      html element attribute valign (top, middle, bottom, baseline)
     * @return      HtmlTableRowAbstract
     */
    public function setValign($align)
    {
        switch ($align)
        {
            case 'top':
                $this->setAttribute('valign', 'top');
                break;
            case 'middle':
                $this->setAttribute('valign', 'middle');
                break;
            case 'bottom':
                $this->setAttribute('valign', 'bottom');
                break;
            case 'baseline':
                $this->setAttribute('valign', 'baseline');
                break;
            case null:
            default:
                $this->setAttribute('valign', null);
                break;
        }
        return $this;
    }
}


text:
<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Top Rated Products Widget.
 *
 * Gets and displays top rated products in an unordered list.
 *
 * @author   WooThemes
 * @category Widgets
 * @package  WooCommerce/Widgets
 * @version  3.0.0
 * @extends  WC_Widget
 */
class WC_Widget_Top_Rated_Products extends WC_Widget {

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->widget_cssclass    = 'woocommerce widget_top_rated_products';
		$this->widget_description = __( 'Display a list of your top rated products on your site.', 'woocommerce' );
		$this->widget_id          = 'woocommerce_top_rated_products';
		$this->widget_name        = __( 'WooCommerce top rated products', 'woocommerce' );
		$this->settings           = array(
			'title'  => array(
				'type'  => 'text',
				'std'   => __( 'Top rated products', 'woocommerce' ),
				'label' => __( 'Title', 'woocommerce' ),
			),
			'number' => array(
				'type'  => 'number',
				'step'  => 1,
				'min'   => 1,
				'max'   => '',
				'std'   => 5,
				'label' => __( 'Number of products to show', 'woocommerce' ),
			),
		);

		parent::__construct();
	}

	/**
	 * Output widget.
	 *
	 * @see WP_Widget
	 *
	 * @param array $args
	 * @param array $instance
	 */
	public function widget( $args, $instance ) {

		if ( $this->get_cached_widget( $args ) ) {
			return;
		}

		ob_start();

		$number = ! empty( $instance['number'] ) ? absint( $instance['number'] ) : $this->settings['number']['std'];

		$query_args = array(
			'posts_per_page' => $number,
			'no_found_rows'  => 1,
			'post_status'    => 'publish',
			'post_type'      => 'product',
			'meta_key'       => '_wc_average_rating',
			'orderby'        => 'meta_value_num',
			'order'          => 'DESC',
			'meta_query'     => WC()->query->get_meta_query(),
			'tax_query'      => WC()->query->get_tax_query(),
		);

		$r = new WP_Query( $query_args );

		if ( $r->have_posts() ) {

			$this->widget_start( $args, $instance );

			echo apply_filters( 'woocommerce_before_widget_product_list', '
' );

			while ( $r->have_posts() ) {
				$r->the_post();
				wc_get_template( 'content-widget-product.php', array( 'show_rating' => true ) );
			}

			echo apply_filters( 'woocommerce_after_widget_product_list', '
' );

			$this->widget_end( $args );
		}

		wp_reset_postdata();

		$content = ob_get_clean();

		echo $content;

		$this->cache_widget( $args, $content );
	}
}


text:
package dom.doctor;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.annotations.Column;
import javax.jdo.annotations.PersistenceCapable;

import org.apache.isis.applib.annotation.CollectionLayout;
import org.apache.isis.applib.annotation.DomainObject;
import org.apache.isis.applib.annotation.Editing;
import org.apache.isis.applib.annotation.MemberOrder;
import org.apache.isis.applib.annotation.Property;
import org.apache.isis.applib.annotation.RenderType;
import org.apache.isis.applib.services.i18n.TranslatableString;

import dom.agendadoctor.AgendaDoctor;
import dom.especialidad.EspecialidadEnum;
import dom.persona.Persona;

/**
 * Entidad Doctor la cual representa a cualquier persona que atienda en el
 * centro medico. Extiende de la clase Persona.
 *
 *
 * @author Adamantium
 * @since 01/06/2015
 * @version 1.0.0
 */
// Primera Estrategia: Una tabla por cada clase
// @PersistenceCapable(identityType = IdentityType.DATASTORE)
// @Inheritance(strategy = InheritanceStrategy.NEW_TABLE)
// Segunda Estrategia: Una tabla por cada clase, solo las subclases
@javax.jdo.annotations.Queries({
		@javax.jdo.annotations.Query(name = "traerTodos", language = "JDOQL", value = "SELECT "
				+ "FROM dom.doctor.Doctor "),

		@javax.jdo.annotations.Query(name = "traerPorEspecialidad", language = "JDOQL", value = "SELECT "
				+ "FROM dom.doctor.Doctor where especialidad == :especialidad"),
		@javax.jdo.annotations.Query(name = "traerActivosPorEspecialidad", language = "JDOQL", value = "SELECT "
				+ "FROM dom.doctor.Doctor where especialidad == :especialidad && estado== 'Activo'"),
		@javax.jdo.annotations.Query(name = "buscarNombre,Apellido,Id", language = "JDOQL", value = "SELECT "
				+ "FROM dom.doctor.Doctor "
				+ "WHERE documento == :parametro || nombre.indexOf(:parametro) == 0 "
				+ " && nombre.indexOf(:parametro) >= 0 || apellido.indexOf(:parametro) == 0 "
				+ " && apellido.indexOf(:parametro) >= 0 "),
		@javax.jdo.annotations.Query(name = "traerPorProvincia", language = "JDOQL", value = "SELECT "
				+ "FROM dom.doctor.Doctor where provincia == :provincia"),
		@javax.jdo.annotations.Query(name = "buscarDuplicados", language = "JDOQL", value = "SELECT "
				+ "FROM dom.doctor.Doctor " + " WHERE documento ==:documento"),
		@javax.jdo.annotations.Query(name = "traerActivos", language = "JDOQL", value = "SELECT "
				+ "FROM dom.doctor.Doctor where estado == 'Activo'"),
		@javax.jdo.annotations.Query(name = "traerDoctor", language = "JDOQL", value = "SELECT "
				+ "FROM dom.doctor.Doctor WHERE usuariovinculado == :usuariovinculado"),
		@javax.jdo.annotations.Query(name = "traerDoctorPorUsuario", language = "JDOQL", value = "SELECT "
				+ " FROM dom.doctor.Doctor WHERE usuariovinculado == :usuariovinculado"),

})
@DomainObject(autoCompleteRepository = DoctorServicio.class, autoCompleteAction = "buscarDoctor")
@PersistenceCapable
public class Doctor extends Persona {

	/**
	 * Representa en UI el nombre "Doctor" en carga/modificacion.
	 */
	/*----------------------------------------------------*/
	public TranslatableString title() {
		return TranslatableString.tr("{nombre}", "nombre",
				"Doctor: " + this.getApellido() + ", " + this.getNombre());
	}

	/**
	 * Obtiene el nombre del icono.
	 */
	/*----------------------------------------------------*/
	public String iconName() {
		return "doctor";
	}

	// {{ Matricula (property)
	private String matricula;

	/**
	 * Pemite obtener una matricula del Doctor
	 *
	 * @return matricula String
	 */
	@MemberOrder(sequence = "0")
	@Property(editing = Editing.DISABLED)
	@Column(allowsNull = "false")
	public String getMatricula() {
		return matricula;
	}

	/**
	 * Setea la Matricula que se va a crear.
	 *
	 * @param matricula
	 *            matricula
	 */
	/*----------------------------------------------------*/
	public void setMatricula(final String matricula) {
		this.matricula = matricula;
	}

	/**
	 * Valida la Matricula a la hora de modificar.
	 *
	 */
	/*----------------------------------------------------*/
	public String validateMatricula(String matr) {

		// if (matr.matches("[a-z,A-Z,0-9,ñ,Ñ]+") == false) {
		if (matr.matches("[0-9,.]+") == false) {
			return "Datos erroneos, vuelva a intentarlo";
		} else {
			return null;
		}
	}

	// {{ Especialidad (property)
	private EspecialidadEnum especialidad;

	/**
	 * Pemite obtener una especialidad del Doctor
	 *
	 * @return especialidad EspecialidadEnum
	 */
	@MemberOrder(sequence = "14")
	@Column(allowsNull = "false")
	public EspecialidadEnum getEspecialidad() {
		return especialidad;
	}

	/**
	 * Setea la Especialidad que se va a crear.
	 *
	 * @param especialidad
	 *            especialidad
	 */
	public void setEspecialidad(final EspecialidadEnum especialidad) {
		this.especialidad = especialidad;
	}

	// {{ ListaAgenda (property)
	private List<AgendaDoctor> listaAgenda = new ArrayList<AgendaDoctor>();

	@MemberOrder(sequence = "15")
	@Column(allowsNull = "false")
	// @Persistent(table = "lista_agenda", mappedBy = "doctor")
	// @Join(column = "doctor_id")
	@CollectionLayout(render = RenderType.EAGERLY)
	/**
	 * Pemite obtener una lista de agenda
	 *
	 * @return listaagenda List<Agenda>
	 */
	public List<AgendaDoctor> getListaAgenda() {
		return listaAgenda;
	}

	/**
	 * Setea la lista de agenda.
	 *
	 * @param List
	 *            <Agenda> listaAgenda listaAgenda
	 */
	public void setListaAgenda(final List<AgendaDoctor> listaAgenda) {
		this.listaAgenda = listaAgenda;
	}

	// }}

}


text:
extern const char *particleVS, *fogParticleVS;
extern const char *particleSpherePS, *particleDebugPS, *particleDensityPS, *particleFogPS;
extern const char *particleSurfacePS, *particleThicknessPS;
extern const char *mblurVS, *mblurGS, *particleSprayPS;
extern const char *passThruVS;
extern const char *depthBlurPS , *depthBlur2DPS, *depthBlurSymPS, *displaySurfacePS, *displaySurfaceNewPS, *displaySurfaceChromePS, *displaySurfaceSolidPS;
extern const char *textureRectPS, *dilatePS;


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /var/www/source/hca_draft/src/HealthCareAbroad/AdvertisementBundle/Entity/Advertisement.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

/var/www/source/hca_draft/src/HealthCareAbroad /

AdvertisementBundle /

Entity /

Advertisement.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

0.00%

0 / 1

0.00%

0 / 13

      <acronym title="Change Risk Anti-Patterns (CRAP) Index">CRAP</acronym>

0.00%

0 / 118

      Advertisement

0.00%

0 / 1

0.00%

0 / 13

      182

0.00%

0 / 118

       getType()

0.00%

0 / 1

      2

0.00%

0 / 4

       getTypeLabel()

0.00%

0 / 1

      2

0.00%

0 / 5

       getId()

0.00%

0 / 1

      2

0.00%

0 / 4

       setTitle($title)

0.00%

0 / 1

      2

0.00%

0 / 5

       getTitle()

0.00%

0 / 1

      2

0.00%

0 / 4

       setDescription($description)

0.00%

0 / 1

      2

0.00%

0 / 5

       getDescription()

0.00%

0 / 1

      2

0.00%

0 / 4

       setDateCreated($dateCreated)

0.00%

0 / 1

      2

0.00%

0 / 5

       getDateCreated()

0.00%

0 / 1

      2

0.00%

0 / 4

       setStatus($status)

0.00%

0 / 1

      2

0.00%

0 / 5

       getStatus()

0.00%

0 / 1

      2

0.00%

0 / 4

       setInstitution(\HealthCareAbroad\InstitutionBundle\Entity\Institution $institution = null)

0.00%

0 / 1

      2

0.00%

0 / 5

       getInstitution()

0.00%

0 / 1

      2

0.00%

0 / 4

1
	<?php

2
	namespace HealthCareAbroad\AdvertisementBundle\Entity;

3

4
	abstract class Advertisement

5
	{

6

7
	    /**

8
	     * @var bigint $id

9
	     */

10
	    private $id;

11

12
	    /**

13
	     * @var string $title

14
	     */

15
	    private $title;

16

17
	    /**

18
	     * @var text $description

19
	     */

20
	    private $description;

21

22
	    /**

23
	     * @var datetime $dateCreated

24
	     */

25
	    private $dateCreated;

26

27
	    /**

28
	     * @var integer $status

29
	     */

30
	    private $status;

31

32
	    /**

33
	     * @var HealthCareAbroad\InstitutionBundle\Entity\Institution

34
	     */

35
	    private $institution;

36

37
	    /**

38
	     * @var int

39
	     */

40
	    protected $type;

41

42
	    final public function getType()

43
	    {

44
	        return $this->type;

45
	    }

46

47
	    final public function getTypeLabel()

48
	    {

49
	        $r = AdvertisementTypes::getList();

50

51
	        return $r[$this->type];

52
	    }

53

54

55
	    /**

56
	     * Get id

57
	     *

58
	     * @return bigint

59
	     */

60
	    public function getId()

61
	    {

62
	        return $this->id;

63
	    }

64

65
	    /**

66
	     * Set title

67
	     *

68
	     * @param string $title

69
	     * @return Advertisement

70
	     */

71
	    public function setTitle($title)

72
	    {

73
	        $this->title = $title;

74
	        return $this;

75
	    }

76

77
	    /**

78
	     * Get title

79
	     *

80
	     * @return string

81
	     */

82
	    public function getTitle()

83
	    {

84
	        return $this->title;

85
	    }

86

87
	    /**

88
	     * Set description

89
	     *

90
	     * @param text $description

91
	     * @return Advertisement

92
	     */

93
	    public function setDescription($description)

94
	    {

95
	        $this->description = $description;

96
	        return $this;

97
	    }

98

99
	    /**

100
	     * Get description

101
	     *

102
	     * @return text

103
	     */

104
	    public function getDescription()

105
	    {

106
	        return $this->description;

107
	    }

108

109
	    /**

110
	     * Set dateCreated

111
	     *

112
	     * @param datetime $dateCreated

113
	     * @return Advertisement

114
	     */

115
	    public function setDateCreated($dateCreated)

116
	    {

117
	        $this->dateCreated = $dateCreated;

118
	        return $this;

119
	    }

120

121
	    /**

122
	     * Get dateCreated

123
	     *

124
	     * @return datetime

125
	     */

126
	    public function getDateCreated()

127
	    {

128
	        return $this->dateCreated;

129
	    }

130

131
	    /**

132
	     * Set status

133
	     *

134
	     * @param integer $status

135
	     * @return Advertisement

136
	     */

137
	    public function setStatus($status)

138
	    {

139
	        $this->status = $status;

140
	        return $this;

141
	    }

142

143
	    /**

144
	     * Get status

145
	     *

146
	     * @return integer

147
	     */

148
	    public function getStatus()

149
	    {

150
	        return $this->status;

151
	    }

152

153
	    /**

154
	     * Set institution

155
	     *

156
	     * @param HealthCareAbroad\InstitutionBundle\Entity\Institution $institution

157
	     * @return Advertisement

158
	     */

159
	    public function setInstitution(\HealthCareAbroad\InstitutionBundle\Entity\Institution $institution = null)

160
	    {

161
	        $this->institution = $institution;

162
	        return $this;

163
	    }

164

165
	    /**

166
	     * Get institution

167
	     *

168
	     * @return HealthCareAbroad\InstitutionBundle\Entity\Institution

169
	     */

170
	    public function getInstitution()

171
	    {

172
	        return $this->institution;

173
	    }

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 1.2.2 using PHP 5.3.10-1ubuntu3.2 and PHPUnit 3.7.1 at Tue Oct 9 16:19:45 PHT 2012.


text:
Badges

Easily highlight new or unread items by adding a <span class="badge"> to links, Bootstrap navs, and more.

    Inbox 42

{% highlight html %}
Inbox 42
{% endhighlight %}

Self collapsing

When there are no new or unread items, badges will simply collapse (via CSS's :empty selector) provided no content exists within.

Cross-browser compatibility

Badges won't self collapse in Internet Explorer 8 because it lacks support for the :empty selector.

Adapts to active nav states

Built-in styles are included for placing badges in active states in pill navigations.

Home 42

Profile

Messages 3

          42
          Home

Profile

          3
          Messages

    <button class="btn btn-primary" type="button">
      Messages 4
    </button>

{% highlight html %}

      42
      Home

  ...

{% endhighlight %}


text:
//  Copyright 2004 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.apache.tapestry.util;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.tapestry.Tapestry;

/**
 * A basic kind of janitor, an object that periodically invokes {@link ICleanable#executeCleanup()}
 * on a set of objects.
 *

 * The JanitorThread holds a weak reference to the objects it operates on.
 *
 * @author Howard Lewis Ship
 * @version $Id$
 * @since 1.0.5
 */

public class JanitorThread extends Thread
{
    /**
     * Default number of seconds between janitor runs, about 30 seconds.
     */

    public static final long DEFAULT_INTERVAL_MILLIS = 30 * 1024;

    private long interval = DEFAULT_INTERVAL_MILLIS;

    private boolean lockInterval = false;

    private static JanitorThread shared = null;

    /**
     * A {@link List}of {@link WeakReference}s to {@link ICleanable}instances.
     */

    private List references = new ArrayList();

    /**
     * Creates a new daemon Janitor.
     */

    public JanitorThread()
    {
        this(null);
    }

    /**
     * Creates new Janitor with the given name. The thread will have minimum priority and be a
     * daemon.
     */

    public JanitorThread(String name)
    {
        super(name);

        setDaemon(true);
        setPriority(MIN_PRIORITY);
    }

    /**
     * Returns a shared instance of JanitorThread. In most cases, the shared instance should be
     * used, rather than creating a new instance; the exception being when particular scheduling is
     * of concern. It is also bad policy to change the sleep interval on the shared janitor (though
     * nothing prevents this, either).
     */

    public synchronized static JanitorThread getSharedJanitorThread()
    {
        if (shared == null)
        {
            shared = new JanitorThread("Shared-JanitorThread");
            shared.lockInterval = true;

            shared.start();
        }

        return shared;
    }

    public long getInterval()
    {
        return interval;
    }

    /**
     * Updates the property, which may not take effect until the next time the thread finishes
     * sleeping.
     *
     * @param value
     *            the interval, in milliseconds, between sweeps.
     * @throws IllegalStateException
     *             always, if the receiver is the shared JanitorThread
     * @throws IllegalArgumentException
     *             if value is less than 1
     */

    public void setInterval(long value)
    {
        if (lockInterval)
            throw new IllegalStateException(Tapestry.getMessage("JanitorThread.interval-locked"));

        if (value < 1)
            throw new IllegalArgumentException(Tapestry
                    .getMessage("JanitorThread.illegal-interval"));

        interval = value;
    }

    /**
     * Adds a new cleanable object to the list of references. Care should be taken that objects are
     * not added multiple times; they will be cleaned too often.
     */

    public void add(ICleanable cleanable)
    {
        WeakReference reference = new WeakReference(cleanable);

        synchronized (references)
        {
            references.add(reference);
        }
    }

    /**
     * Runs through the list of targets and invokes {@link ICleanable#executeCleanup()}on each of
     * them. {@link WeakReference}s that have been invalidated are weeded out.
     */

    protected void sweep()
    {
        synchronized (references)
        {
            Iterator i = references.iterator();

            while (i.hasNext())
            {
                WeakReference ref = (WeakReference) i.next();

                ICleanable cleanable = (ICleanable) ref.get();

                if (cleanable == null)
                    i.remove();
                else
                    cleanable.executeCleanup();
            }
        }
    }

    /**
     * Waits for the next run, by sleeping for the desired period. Returns true if the sleep was
     * successful, or false if the thread was interrupted (and should shut down).
     */

    protected void waitForNextPass()
    {
        try
        {
            sleep(interval);
        }
        catch (InterruptedException ex)
        {
            interrupt();
        }
    }

    /**
     * Alternates between {@link #waitForNextPass()}and {@link #sweep()}.
     */

    public void run()
    {
        while (!isInterrupted())
        {
            waitForNextPass();

            sweep();
        }
    }

    public String toString()
    {
        StringBuffer buffer = new StringBuffer("JanitorThread@");
        buffer.append(Integer.toHexString(hashCode()));

        buffer.append("[interval=");
        buffer.append(interval);

        buffer.append(" count=");

        synchronized (references)
        {
            buffer.append(references.size());
        }

        buffer.append(']');

        return buffer.toString();
    }
}


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TVSPlayer {
    static class Settings {
        private static string library;
        private static bool autodownload;
        private static string cachelocation;
        private static string scanone;
        private static string scantwo;
        private static string scanthree;
        private static bool theme;
        private static DateTime lastCheck;
        private static int downloadSpeed;
        private static int uploadSpeed;
        private static bool stremedBefore;
        private static TorrentQuality downloadquality;
        private static TorrentQuality streamquality;
        private static bool useWinDefaultPlayer;
        private static bool performanceMode;
        private static bool updateOnStartup;
        private static int subtitleSize;

        public static string Library { get { return library; } set { library = value; SaveSettings(); } }
        public static bool AutoDownload { get { return autodownload; } set { autodownload = value; SaveSettings(); } }
        public static string DownloadCacheLocation { get { return cachelocation; } set { cachelocation = value; SaveSettings(); } }
        public static string FirstScanLocation { get { return scanone; } set { scanone = value; SaveSettings(); } }
        public static string SecondScanLocation { get { return scantwo; } set { scantwo = value; SaveSettings(); } }
        public static string ThirdScanLocation { get { return scanthree; } set { scanthree = value; SaveSettings(); } }
        public static bool Theme  { get { return theme; } set { theme = value; SaveSettings(); } }
        public static DateTime LastCheck { get { return lastCheck; } set { lastCheck = value; SaveSettings(); } }
        public static TorrentQuality DownloadQuality { get { return downloadquality; } set { downloadquality = value; SaveSettings(); } }
        public static TorrentQuality StreamQuality { get { return streamquality; } set { streamquality = value; SaveSettings(); } }
        public static int UploadSpeed { get { return uploadSpeed; } set { uploadSpeed = value; SaveSettings(); } }
        public static int DownloadSpeed { get { return downloadSpeed; } set { downloadSpeed = value; SaveSettings(); } }
        public static bool StreamedBefore { get { return stremedBefore; } set { stremedBefore = value; SaveSettings(); } }
        public static bool UseWinDefaultPlayer { get { return useWinDefaultPlayer; } set { useWinDefaultPlayer = value; SaveSettings(); } }
        public static bool PerformanceMode { get { return performanceMode; } set { performanceMode = value; SaveSettings(); } }
        public static bool UpdateOnStartup { get { return updateOnStartup; } set { updateOnStartup = value; SaveSettings(); } }
        public static int SubtitleSize { get { return subtitleSize; } set { subtitleSize = value; SaveSettings(); } }

        /// <summary>
        /// Saves Settings. Is called automatically whenever property value is changed
        /// </summary>
        public static void SaveSettings() {
            Type type = typeof(Settings);
            string filename = Helper.data + "Settings.tvsp";
            // Library = "test";
            // Test = Library;
            CreateDir();
            if (!File.Exists(filename)) {
                File.Create(filename).Dispose();
            }
            do {
                try {
                    FieldInfo[] properties = type.GetFields(BindingFlags.Static | BindingFlags.NonPublic);
                    object[,] a = new object[properties.Length, 2];
                    int i = 0;
                    foreach (FieldInfo field in properties) {
                        a[i, 0] = field.Name;
                        a[i, 1] = field.GetValue(null);
                        i++;
                    };
                    string json = JsonConvert.SerializeObject(a);
                    StreamWriter sw = new StreamWriter(filename);
                    sw.Write(json);
                    sw.Close();
                    return;
                } catch (IOException e) {
                    Thread.Sleep(10);
                }
            } while (true);
        }

        private static void CreateDir() {
            string filename = Helper.data + "Settings.tvsp";
            if (!Directory.Exists(Path.GetDirectoryName(filename))){
                Directory.CreateDirectory(Path.GetDirectoryName(filename));
            }
        }
        public static object GetDefault(Type type) {
            if (type.IsValueType) {
                return Activator.CreateInstance(type);
            }
            return null;
        }

        /// <summary>
        /// Loads settings with default value if new settings has been added. In case of enums edit code - might get "crashy" if you dont
        /// </summary>
        public static void Load() {
            Type type = typeof(Settings);
            string filename = Helper.data + "Settings.tvsp";
            CreateDir();
            if (!File.Exists(filename)) {
                File.Create(filename).Dispose();
            }
            do {
                try {
                    FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.NonPublic);
                    object[,] a;
                    StreamReader sr = new StreamReader(filename);
                    string json = sr.ReadToEnd();
                    sr.Close();
                    if (!String.IsNullOrEmpty(json)) {
                        JArray ja = JArray.Parse(json);
                        a = ja.ToObject<object[,]>();
                        if (a.GetLength(0) != fields.Length) { }
                        int i = 0;
                        foreach (FieldInfo field in fields) {
                            try {
                                if (field.Name == (a[i, 0] as string)) {
                                    try {
                                        field.SetValue(null, Convert.ChangeType(a[i, 1], field.FieldType));
                                    } catch (InvalidCastException e) {
                                        field.SetValue(null, (TorrentQuality)Enum.ToObject(typeof(TorrentQuality), Int32.Parse(a[i, 1].ToString())));
                                    }
                                }
                            } catch (IndexOutOfRangeException) {
                                field.SetValue(null, GetDefault(field.FieldType));
                            }
                            i++;
                        };
                    }
                    return;
                } catch (IOException e) {
                    Thread.Sleep(15);
                }
            } while (true);
        }
    }
}


text:
using System.Web.Http;

namespace _06dVersioning.Controllers
{
    public class VersionsV1Controller : ApiController
    {
        [HttpGet]
        public IHttpActionResult Get()
        {
            return Ok(ThingRepository.Current.Get());
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Windows;
using System.Windows.Input;

/// <summary>
/// MVVM uses commands instead of UI events
/// http://blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/
/// </summary>

public class CommandBase : ICommand
{
    readonly Action<object> execute;
    readonly Predicate<object> canExecute;

    public CommandBase(Action<object> executeDelegate, Predicate<object> canExecuteDelegate)
    {
        execute = executeDelegate;
        canExecute = canExecuteDelegate;
    }

    bool ICommand.CanExecute(object parameter)
    {
        return canExecute == null ? true : canExecute(parameter);
    }

    event EventHandler ICommand.CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    void ICommand.Execute(object parameter)
    {
        execute(parameter);
    }
}

/// <summary>
/// I like this implementation of ViewModelBase
/// http://codereview.stackexchange.com/questions/13823/improvements-to-a-viewmodelbase
///
/// </summary>
public abstract class ViewModelBase : INotifyPropertyChanged
{

    public bool IsInDesignMode
    {

        get
        {
#if NETFX_CORE
                return Windows.ApplicationModel.DesignMode.DesignModeEnabled;
#elif SILVERLIGHT // includes WINDOWS_PHONE
            return System.ComponentModel.DesignerProperties.IsInDesignTool;
#else //WPF
            return System.ComponentModel.DesignerProperties.GetIsInDesignMode(new DependencyObject());
#endif
        }

    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName)
    {
        var propertyChanged = this.PropertyChanged;

        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    /// <summary>
    /// Encapsulates the notion of setting the value of a backing field within a property.
    ///     Instead of explicitly calling RaisePropertyChanged, use SetProperty.
    /// NOTE: The notify event is only raised if the property is indeed different. If you need the
    ///         event to be raised without the property being different, consider WTF,
    ///         then call RaisePropertyChanged directly.
    /// </summary>
    /// <typeparam name="T">The viewmodel _instance.  Example: this.SetProperty</typeparam>
    /// <param name="backingField"></param>
    /// <param name="Value">Example: 'value'</param>
    /// <param name="propertyExpression">Example: () => this.PropertyName</param>
    /// <returns>true implies backingField was changed, false implies backingField was not changed</returns>
    protected bool SetProperty<T>(ref T backingField, T Value, Expression<Func<T>> propertyExpression)
    {
        var changed = !EqualityComparer<T>.Default.Equals(backingField, Value);

        if (changed)
        {
            backingField = Value;
            this.RaisePropertyChanged(ExtractPropertyName(propertyExpression));
        }

        return changed;
    }

    private static string ExtractPropertyName<T>(Expression<Func<T>> propertyExpression)
    {
        var memberExp = propertyExpression.Body as MemberExpression;

        if (memberExp == null)
        {
            throw new ArgumentException("Expression must be a MemberExpression.", "propertyExpression");
        }

        return memberExp.Member.Name;
    }
}


text:
(function(){
    "use strict";

    angular.module('app.controllers').controller('LoosedataCtrl', function($scope, $state, DialogService){

        $scope.save = function(){
            //
            $scope.vm.deleteData();
            $state.go($scope.toState.name);
            DialogService.hide();
        };

        $scope.hide = function(){
        	DialogService.hide();
        };

    });

})();


text:
/* Sasikanth Avancha, Dhiraj Kalamkar (Intel Corp.)
******************************************************************************/

typedef MLParams *(*ParseFunc)(NodeParameter* np);
typedef MLNode *(*CreateFunc)(MLParams* p, MLEngine* e);

typedef struct TypeList_{
  std::string typeName;
  ParseFunc parse;
  CreateFunc create;
} TypeList;

extern TypeList nodeTypes[];
extern const int numTypes;


text:
describe('Unit: Constants', function () {

    let constants;

    beforeEach(function () {
        // instantiate the app module
        angular.mock.module('app');

        // mock the directive
        angular.mock.inject((AppSettings) => {
            constants = AppSettings;
        });
    });

    it('should exist', function () {
        expect(constants).toBeDefined();
    });

    it('should have an application name', function () {
        expect(constants.appTitle).toEqual('Filtering Matches Application');
    });

});


text:
from flask_wtf import Form
from wtforms import PasswordField, StringField,SubmitField,FloatField,DateField,DateTimeField,TextAreaField, FileField
from wtforms.validators import DataRequired, InputRequired,NumberRange
# coding=utf-8

class CourseForm(Form):
    coursename = StringField('名称')
    credit = FloatField('学分')
    location = StringField('地点')
    start_time = DateField('开始时间')
    course_introduction = TextAreaField('课程介绍')
    course_outline = TextAreaField("课程大纲")
    low_member = FloatField('团队下限',validators=[NumberRange(1,10)])
    high_member = FloatField('团队上限',validators=[NumberRange(1,20)])
    submit = SubmitField('提交')

class TaskForm(Form):
    taskname = StringField('名称')
    starttime = DateTimeField('开始时间')
    endtime = DateTimeField('结束时间')
    subnum = FloatField('可提交次数',validators=[NumberRange(1,10)])
    content = TextAreaField('内容')
    weight = FloatField('作业权重',validators=[NumberRange(1,3)])
    submit = SubmitField('提交')

class FileForm(Form):
    file = FileField('图片上传', validators=[DataRequired('请选择文件')])
    submit = SubmitField('上传')

class TaskScoreForm(Form):
    task_score=FloatField('分数',validators=[NumberRange(1,100)])
    content=StringField('批改意见')
    submit = SubmitField('提交')

class RejectReasonForm(Form):
    content = TextAreaField('内容',validators=[DataRequired('请填写理由')])
    submit = SubmitField('提交')