text:
const helpers = require('../helpers');
const SetMinMax = require('../generated_pages/numbers/set-min-max-block.page.js');
const TestMinMax = require('../generated_pages/numbers/test-min-max-block.page.js');
const SummaryPage = require('../generated_pages/numbers/summary.page');

const IntroductionPage = require('../generated_pages/introduction/introduction.page');
const IntroInterstitialPage = require('../generated_pages/introduction/general-business-information-completed.page');
const IntroConfirmationPage = require('../generated_pages/introduction/confirmation.page');
const IntroThankYouPagePage = require('../base_pages/thank-you.page');

const NIRadioPage = require('../generated_pages/theme_northernireland/radio.page');
const NISummaryPage = require('../generated_pages/theme_northernireland/summary.page');
const NIThankYouPage = require('../base_pages/thank-you.page');
const NIViewSubmissionPage = require('../base_pages/thank-you.page');

const SocialRadioPage = require('../generated_pages/theme_social/radio.page');
const SocialSummaryPage = require('../generated_pages/theme_social/summary.page');
const SocialThankYouPage = require('../base_pages/thank-you.page');
const SocialViewSubmissionPage = require('../base_pages/thank-you.page');

const FeedbackForm = require('../base_pages/feedback-form');

describe('SaveSignOut', function() {

  const collectionId = helpers.getRandomString(10);

  it('Given I am completing a survey, when I select save and complete later, then I am redirected to sign out page and my session is cleared', function() {
    return helpers.openQuestionnaire('test_numbers.json', { userId: 'test_user', collectionId: collectionId }).then(() => {
        return browser
          .setValue(SetMinMax.setMinimum(), '10')
          .setValue(SetMinMax.setMaximum(), '1020')
          .click(SetMinMax.submit())
          .click(TestMinMax.saveSignOut())
          .getUrl().should.eventually.contain('localhost')
          .back()
          .getSource().should.eventually.contain('Your session has expired');
      });
  });

  it('Given I have started a questionnaire, when I return to the questionnaire, then I am returned to the page I was on and can then complete the survey', function() {
    return helpers.openQuestionnaire('test_numbers.json', { userId: 'test_user', collectionId: collectionId }).then(() => {
        return browser
          .getUrl().should.eventually.contain(TestMinMax.pageName)
          .setValue(TestMinMax.testRange(), '10')
          .setValue(TestMinMax.testMin(), '123')
          .setValue(TestMinMax.testMax(), '1000')
          .setValue(TestMinMax.testPercent(), '100')
          .click(TestMinMax.submit())
          .getUrl().should.eventually.contain(SummaryPage.pageName)
          .click(SummaryPage.submit())
          .getUrl().should.eventually.contain('thank-you');
      });
  });

  it('Given a logout url is set, when I navigate the questionnaire, then I see the correct sign out buttons', function() {
    return helpers.openQuestionnaire('test_introduction.json', { includeLogoutUrl: true }).then(() => {
        return browser
          .getUrl().should.eventually.contain(IntroductionPage.pageName)
          .getText(IntroductionPage.signOut()).should.eventually.contain('Sign out')
          .click(IntroductionPage.getStarted())

          .getUrl().should.eventually.contain(IntroInterstitialPage.pageName)
          .getText(IntroInterstitialPage.saveSignOut()).should.eventually.contain('Save and sign out')
          .click(IntroInterstitialPage.submit())

          .getUrl().should.eventually.contain(IntroConfirmationPage.pageName)
          .getText(IntroConfirmationPage.saveSignOut()).should.eventually.contain('Save and sign out')
          .click(IntroConfirmationPage.submit())

          .getUrl().should.eventually.contain(IntroThankYouPagePage.pageName)
          .getText(IntroThankYouPagePage.signOut()).should.eventually.contain('Sign out');
      });
  });

  it('Given a logout url is not set, when I navigate the questionnaire, then I see the correct sign out buttons', function() {
    return helpers.openQuestionnaire('test_introduction.json', { includeLogoutUrl: false }).then(() => {
        return browser
          .getUrl().should.eventually.contain(IntroductionPage.pageName)
          .isExisting(IntroductionPage.signOut()).should.eventually.be.false
          .click(IntroductionPage.getStarted())

          .getUrl().should.eventually.contain(IntroInterstitialPage.pageName)
          .getText(IntroInterstitialPage.saveSignOut()).should.eventually.contain('Save and complete later')
          .click(IntroInterstitialPage.submit())

          .getUrl().should.eventually.contain(IntroConfirmationPage.pageName)
          .getText(IntroConfirmationPage.saveSignOut()).should.eventually.contain('Save and complete later')
          .click(IntroConfirmationPage.submit())

          .getUrl().should.eventually.contain(IntroThankYouPagePage.pageName)
          .isExisting(IntroductionPage.signOut()).should.eventually.be.false;
      });
  });

  it('Given I am on a northern ireland themed survey, when I navigate the questionnaire, then I see the correct sign out buttons', function() {
    return helpers.openQuestionnaire('test_theme_northernireland.json', { includeLogoutUrl: true }).then(() => {
        return browser
          .getUrl().should.eventually.contain(NIRadioPage.pageName)
          .getText(NIRadioPage.saveSignOut()).should.eventually.contain('Save and sign out')
          .click(NIRadioPage.submit())
          .getUrl().should.eventually.contain(NISummaryPage.pageName)
          .getText(NISummaryPage.saveSignOut()).should.eventually.contain('Save and sign out')
          .click(NISummaryPage.submit())
          .getUrl().should.eventually.contain(NIThankYouPage.pageName)
          .getText(NIThankYouPage.signOut()).should.eventually.contain('Sign out')
          .click(NIThankYouPage.viewSubmitted())
          .getUrl().should.eventually.contain('view-submission')
          .getText(NIViewSubmissionPage.signOut()).should.eventually.contain('Sign out');
      });
  });

  it('Given I am on a social themed survey, when I navigate the questionnaire, then I see the correct sign out buttons', function() {
    return helpers.openQuestionnaire('test_theme_social.json', { includeLogoutUrl: false } ).then(() => {
        return browser
          .getUrl().should.eventually.contain(SocialRadioPage.pageName)
          .getText(SocialRadioPage.saveSignOut()).should.eventually.contain('Save and complete later')
          .click(SocialRadioPage.submit())
          .getUrl().should.eventually.contain(SocialSummaryPage.pageName)
          .getText(SocialSummaryPage.saveSignOut()).should.eventually.contain('Save and complete later')
          .click(SocialSummaryPage.submit())
          .getUrl().should.eventually.contain(SocialThankYouPage.pageName)
          .isExisting(SocialThankYouPage.signOut()).should.eventually.be.false
          .click(SocialThankYouPage.viewSubmitted())
          .getUrl().should.eventually.contain('view-submission')
          .isExisting(SocialViewSubmissionPage.signOut()).should.eventually.be.false;
      });
  });

  it('Given a logout url is set, when I load the feedback page, then I see the sign out button', function() {
    return helpers.openQuestionnaire('test_numbers.json', { includeLogoutUrl: true }).then(() => {
        return browser
          .url(FeedbackForm.url())
          .getUrl().should.eventually.contain('feedback')
          .isExisting(FeedbackForm.signOut()).should.eventually.be.true
          .getText(FeedbackForm.signOut()).should.eventually.contain('Sign out');
      });
  });

  it('Given a logout url is not set, when I load the feedback page, then there should be no sign out button', function() {
    return helpers.openQuestionnaire('test_numbers.json', { includeLogoutUrl: false }).then(() => {
        return browser
          .url(FeedbackForm.url())
          .getUrl().should.eventually.contain('feedback')
          .isExisting(FeedbackForm.signOut()).should.eventually.be.false;
      });
  });

  it('Given a logout url is set and I load the feedback page, when I sign out, then I should be on the account service logged out page', function() {
    return helpers.openQuestionnaire('test_numbers.json', { includeLogoutUrl: true }).then(() => {
        return browser
          .url(FeedbackForm.url())
          .getUrl().should.eventually.contain('feedback')
          .isExisting(FeedbackForm.signOut()).should.eventually.be.true
          .click(FeedbackForm.signOut())
          .getUrl().should.eventually.contain('http://localhost:8000');
      });
  });

});


text:
package com.hazelcast.client.impl.protocol.task;

import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.codec.ClientDeployClassesCodec;
import com.hazelcast.cluster.Member;
import com.hazelcast.core.MemberLeftException;
import com.hazelcast.instance.impl.Node;
import com.hazelcast.internal.nio.Connection;
import com.hazelcast.internal.usercodedeployment.UserCodeDeploymentService;
import com.hazelcast.internal.usercodedeployment.impl.operation.DeployClassesOperation;
import com.hazelcast.security.permission.ActionConstants;
import com.hazelcast.security.permission.UserCodeDeploymentPermission;
import com.hazelcast.spi.impl.operationservice.Operation;

import java.security.Permission;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/**
 * Message task handling user code deployment from client to cluster
 */
public class DeployClassesMessageTask extends AbstractMultiTargetMessageTask<List<Map.Entry<String, byte[]>>>
        implements Supplier<Operation> {

    public DeployClassesMessageTask(ClientMessage clientMessage, Node node, Connection connection) {
        super(clientMessage, node, connection);
    }

    @Override
    public Operation get() {
        return new DeployClassesOperation(parameters);
    }

    @Override
    protected Supplier<Operation> createOperationSupplier() {
        return this;
    }

    @Override
    protected Object reduce(Map<Member, Object> map) throws Throwable {
        for (Object result : map.values()) {
            if (result instanceof Throwable && !(result instanceof MemberLeftException)) {
                throw (Throwable) result;
            }
        }
        return null;
    }

    @Override
    public Collection<Member> getTargets() {
        return nodeEngine.getClusterService().getMembers();
    }

    @Override
    protected List<Map.Entry<String, byte[]>> decodeClientMessage(ClientMessage clientMessage) {
        return ClientDeployClassesCodec.decodeRequest(clientMessage);
    }

    @Override
    protected ClientMessage encodeResponse(Object response) {
        return ClientDeployClassesCodec.encodeResponse();
    }

    @Override
    public String getServiceName() {
        return UserCodeDeploymentService.SERVICE_NAME;
    }

    @Override
    public String getDistributedObjectName() {
        return null;
    }

    @Override
    public String getMethodName() {
        return null;
    }

    @Override
    public Permission getRequiredPermission() {
        return new UserCodeDeploymentPermission(ActionConstants.ACTION_USER_CODE_DEPLOY);
    }

    @Override
    public Object[] getParameters() {
        return null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.androidpn.server.xmpp.auth;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.androidpn.server.service.ServiceLocator;
import org.androidpn.server.service.UserNotFoundException;
import org.androidpn.server.xmpp.UnauthenticatedException;
import org.androidpn.server.xmpp.XmppServer;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * This class is to provide the methods associated with user authentication.
 *
 * @author Sehwan Noh (devnoh@gmail.com)
 */
public class AuthManager {

    private static final Log log = LogFactory.getLog(AuthManager.class);

    private static final Object DIGEST_LOCK = new Object();

    private static MessageDigest digest;

    static {
        try {
            digest = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            log.error("Internal server error", e);
        }
    }

    /**
     * Returns the user's password.
     *
     * @param username the username
     * @return the user's password
     * @throws UserNotFoundException if the your was not found
     */
    public static String getPassword(String username)
            throws UserNotFoundException {
        return ServiceLocator.getUserService().getUserByUsername(username)
                .getPassword();
    }

    /**
     * Authenticates a user with a username and plain text password, and
     * returns an AuthToken.
     *
     * @param username the username
     * @param password the password
     * @return an AuthToken
     * @throws UnauthenticatedException if the username and password do not match
     */
    public static AuthToken authenticate(String username, String password)
            throws UnauthenticatedException {
        if (username == null || password == null) {
            throw new UnauthenticatedException();
        }
        username = username.trim().toLowerCase();
        if (username.contains("@")) {
            int index = username.indexOf("@");
            String domain = username.substring(index + 1);
            if (domain.equals(XmppServer.getInstance().getServerName())) {
                username = username.substring(0, index);
            } else {
                throw new UnauthenticatedException();
            }
        }
        try {
            if (!password.equals(getPassword(username))) {
                throw new UnauthenticatedException();
            }
        } catch (UserNotFoundException unfe) {
            throw new UnauthenticatedException();
        }
        return new AuthToken(username);
    }

    /**
     * Authenticates a user with a username, token, and digest, and returns
     * an AuthToken.
     *
     * @param username the username
     * @param token the token
     * @param digest the digest
     * @return an AuthToken
     * @throws UnauthenticatedException if the username and password do not match
     */
    public static AuthToken authenticate(String username, String token,
            String digest) throws UnauthenticatedException {
        if (username == null || token == null || digest == null) {
            throw new UnauthenticatedException();
        }
        username = username.trim().toLowerCase();
        if (username.contains("@")) {
            int index = username.indexOf("@");
            String domain = username.substring(index + 1);
            if (domain.equals(XmppServer.getInstance().getServerName())) {
                username = username.substring(0, index);
            } else {
                throw new UnauthenticatedException();
            }
        }
        try {
            String password = getPassword(username);
            String anticipatedDigest = createDigest(token, password);
            if (!digest.equalsIgnoreCase(anticipatedDigest)) {
                throw new UnauthenticatedException();
            }
        } catch (UserNotFoundException unfe) {
            throw new UnauthenticatedException();
        }
        return new AuthToken(username);
    }

    /**
     * Returns true if plain text password authentication is supported according to JEP-0078.
     *
     * @return true if plain text password authentication is supported
     */
    public static boolean isPlainSupported() {
        return true;
    }

    /**
     * Returns true if digest authentication is supported according to JEP-0078.
     *
     * @return true if digest authentication is supported
     */
    public static boolean isDigestSupported() {
        return true;
    }

    private static String createDigest(String token, String password) {
        synchronized (DIGEST_LOCK) {
            digest.update(token.getBytes());
            return Hex.encodeHexString(digest.digest(password.getBytes()));
        }
    }

}


text:
package io.sarl.lang.util;

import java.util.Collection;
import java.util.Comparator;
import java.util.TreeSet;

/** Represent a set of objects which is not thread-safe.
 *
 * @param <T> the type of the objects in the set.
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 * @since 0.12
 */
class NoConcurrentTreeSet<T> extends TreeSet<T> implements ConcurrentSet<T> {

	private static final long serialVersionUID = -2543691730298074996L;

    /**
     * Constructs a new, empty set that orders its elements according to
     * their {@linkplain Comparable natural ordering}.
     */
    NoConcurrentTreeSet() {
        super();
    }

    /**
     * Constructs a new, empty set that orders its elements according to
     * the specified comparator.
     *
     * @param comparator the comparator that will be used to order this set.
     *        If {@code null}, the {@linkplain Comparable natural
     *        ordering} of the elements will be used.
     */
    NoConcurrentTreeSet(Comparator<? super T> comparator) {
        super(comparator);
    }

    /**
     * Constructs a new set containing the elements in the specified
     * collection, that orders its elements according to their
     * {@linkplain Comparable natural ordering}.
     *
     * @param source the elements that will comprise the new set
     * @throws ClassCastException if the elements in {@code c} are
     *         not {@link Comparable}, or are not mutually comparable
     * @throws NullPointerException if the specified collection or any
     *         of its elements are null
     */
    NoConcurrentTreeSet(Collection<? extends T> source) {
        super(source);
    }

}


text:
package id.bizdir.ui.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;

import id.bizdir.R;
import id.bizdir.util.Const;
import id.bizdir.util.Helpers;
import uk.co.senab.photoview.PhotoView;

public class ImageViewerActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_viewer);
        Helpers.setLockOrientation(ImageViewerActivity.this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getDataFromPreviousPage();
        //setTitle(mTitle);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            Helpers.setMainActionBar(actionBar);
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    private void getDataFromPreviousPage() {
        Intent intent = this.getIntent();
        String urlAddress = intent.getStringExtra(Const.URL_ADDRESS);
        if (!TextUtils.isEmpty(urlAddress)) {
            setImageView(urlAddress);
        }
    }

    private void setImageView(String imageUrl) {
        final PhotoView photoView = (PhotoView) findViewById(R.id.iv_photo);
        final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
        final TextView textNoData = (TextView) findViewById(R.id.textNoData);
        textNoData.setVisibility(View.GONE);
        Glide.with(this)
                .load(imageUrl)
                .clone()
                .crossFade()
                .into(new GlideDrawableImageViewTarget(photoView) {
                    @Override
                    public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
                        super.onResourceReady(drawable, anim);
                        progressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        progressBar.setVisibility(View.GONE);
                        photoView.setVisibility(View.GONE);
                        textNoData.setVisibility(View.VISIBLE);
                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_home, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            case R.id.action_home:
                Intent intent = new Intent(ImageViewerActivity.this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

}


text:
import requests
import bs4
import json
import re

def _comment( story , index = 0):

    path = "http://www.hs.fi/ajax/keskustelut/" + story + "?startIndex=" + str(index) + "&order=a"

    r = requests.get( path )
    text = r.text.strip()

    ## no more comments left
    if text == '':
        return False

    html = bs4.BeautifulSoup( text )

    ret = []

    comments = html.find_all('div', class_='comment-text')
    comments_meta = html.find_all('div', class_= 'meta')

    for i, c in enumerate( comments ):
        comment = {}

        comment['story'] = story

        meta = comments_meta[ i ]

        ## comment id
        comment['id'] = meta['id'].replace('comment-meta', '')

        ## author name
        comment['author'] = meta.find('a' , class_='author' ).text

        ## samaa mielta score
        scores = c.find_all('div', class_='comment-btn-container')[0]
        scores = scores.find_all('span', class_='rating-value')
        comment['agreement_yes'] = int( scores[0].text[1:-1] )
        comment['agreement_no'] = int( scores[1].text[1:-1] )

        ## hyvin argumentoitu score
        scores = c.find_all('div', class_='comment-btn-container')[1]
        scores = scores.find_all('span', class_='rating-value')
        comment['argument_yes'] = int( scores[0].text[1:-1] )
        comment['argument_no'] = int( scores[1].text[1:-1] )

        ## comment text
        c.find( class_ = 'comment-text-links').decompose() ## remove non-comment stuff
        comments = c.find_all('p')
        comment['text'] = '\n'.join( map( lambda x: x.text , comments ) )

        ret.append( comment )

    return ret

def comment( story ):

    comments = []

    current = _comment( story )

    while current:

        comments += current

        current = _comment( story , len( comments ) + 1 )

    return comments

## http://www.hs.fi/ajax/keskustelut/1296808743968/a1305922917503?startIndex=3&order=a
## http://www.hs.fi/ajax/keskustelut/1296808474403/a1305922917503?startIndex=0&order=a

def collect_for_stories():

    collected = []

    data = []

    r = requests.get( 'http://www.hs.fi/uutiset/?ref=hs-navi-osastot' )
    html = bs4.BeautifulSoup( r.text )

    for link in html.find_all( 'a' , class_='article-link'):

        path1 = '1296808743968' ## link['data-department-id']
        path2 = link['data-article-id']

        if path2 not in collected:

            data += comment( path1 + '/a' + path2 )

            collected.append( path2 )

    print data

    return data

if __name__ == '__main__':

    collect_for_stories()


text:
% Saves the MATPOWER cases data into tabular data
%
% Usage:
% Run this in the MATPOWER directory containing the cases and specify which
% cases to save in the 'cases' cell array below.
%
% Remarks:
% The MATPOWER format is a slightly different than the IEEE formats
% (http://www.ee.washington.edu/research/pstca/formats/pti.txt). MATPOWER
% contains fields not included in the PTI data; it also does not use some
% fields present in PTI (MATPOWER's caseformat.m).

clear all
%cases = {'case9.m', 'case30.m', 'case118.m'};
cases = {'case9.m', 'case30.m', 'case118.m', ...
    'case57.m', 'case300.m', 'case1354pegase.m', 'case2869pegase.m', ...
    'case2736sp.m', 'case2737sop.m', 'case2383wp.m', 'case2746wop.m', 'case2746wop.m', ...
    'case3012wp.m', 'case3120sp.m', 'case3375wp.m', 'case9241pegase.m'}
%cases = {'case1354pegase.m'};
for i=1:length(cases)
    [~,name]=fileparts(cases{i});
    fprintf('converting %s\n', cases{i});
    f=str2func(name);
    mpc=f();

    %if size(mpc.bus,2)~=13
    %   msg = sprintf('truncating bus info to only 13 columns for %s', cases{i});
    %   warning(msg)
    %   mpc.bus = mpc.bus(:,1:13);
    %end
    dlmwrite([name, '.bus'], mpc.bus, 'delimiter', '\t', 'precision', '%.8f');
    dlmwrite([name, '.branch'], mpc.branch, 'delimiter', '\t', 'precision', '%.8f');
    dlmwrite([name, '.gen'], mpc.gen, 'delimiter', '\t', 'precision', '%.8f');
    dlmwrite([name, '.gencost'], mpc.gencost, 'delimiter', '\t', 'precision', '%.8f');
end


text:
package com.gersion.superlock.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gersion.superlock.R;

public class TitleView extends RelativeLayout {

    private ImageView mBack;
    private TextView mTitle;
    private ImageView mIvSearch;
    private TextView mRightText;
    private ImageView mIvAdd;

    public TitleView(Context context) {
        super(context);
        initView(context);
    }

    public TitleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private void initView(Context context) {
        View.inflate(context, R.layout.view_title, this);
        mBack = (ImageView) findViewById(R.id.back);
        mTitle = (TextView) findViewById(R.id.title);
        mIvSearch = (ImageView) findViewById(R.id.iv_search);
        mIvAdd = (ImageView) findViewById(R.id.iv_add);
        mRightText = (TextView) findViewById(R.id.right_text);
        mIvAdd.setRotation(45);
    }

    public ImageView getBack() {
        return mBack;
    }

    public ImageView getRightImg() {
        return mIvSearch;
    }

    public TextView getTitle() {
        return mTitle;
    }

    public TextView getRightText() {
        return mRightText;
    }

    public void setOnBackListener(OnClickListener listener) {
        if (mBack != null) {
            mBack.setOnClickListener(listener);
        }
    }

    public void setOnSearchListener(OnClickListener listener) {
        if (mIvSearch != null) {
            mIvSearch.setOnClickListener(listener);
        }
    }

    public void setOnAddListener(OnClickListener listener) {
        if (mIvAdd != null) {
            mIvAdd.setOnClickListener(listener);
        }
    }

    public TitleView setRightTextVisiable(boolean visiable) {
        if (mRightText != null) {
            mRightText.setVisibility(visiable?VISIBLE:GONE);
        }
        return this;
    }

    public TitleView setTitleText(String text) {
        mTitle.setText(text);
        return this;
    }

    public TitleView setRightText(String text) {
        if (mRightText != null) {
            mRightText.setText(text);
        }
        return this;
    }

    public void setRightTextListener(OnClickListener listener) {
        if (mRightText != null) {
            mRightText.setOnClickListener(listener);
        }
    }

    public TitleView setSearchVisiable(boolean visiable) {
        if (mIvSearch != null) {
            mIvSearch.setVisibility(visiable?VISIBLE:GONE);
            return this;
        }
        return this;
    }

    public TitleView setAddVisiable(boolean visiable) {
        if (mIvAdd != null) {
            mIvAdd.setVisibility(visiable?VISIBLE:GONE);
        }
        return this;
    }

    public TitleView setBackVisiable(boolean visiable) {
        if (mBack != null) {
            mBack.setVisibility(visiable?VISIBLE:GONE);
        }
        return this;
    }
}


text:
package eu.qualimaster.monitoring.volumePrediction;

import java.util.TimerTask;

import org.apache.log4j.LogManager;

/**
 * Preliminary timer task for updating the prediction models.
 *
 * @author Holger Eichelberger
 */
public class ModelUpdateTask extends TimerTask {

    @Override
    public void run() {
        try {
            VolumePredictionManager.updatePredictors();
        } catch (Throwable t) {
            LogManager.getLogger(getClass()).error(
                    "While updating source volume prediction models: "
                            + t.getMessage(), t);
        }
    }

}


text:
require_relative "../helper"

module Arel
  module Visitors
    class TestDot < Arel::Test
      def setup
        @visitor = Visitors::Dot.new
      end

      # functions
      [
        Nodes::Sum,
        Nodes::Exists,
        Nodes::Max,
        Nodes::Min,
        Nodes::Avg,
      ].each do |klass|
        define_method("test_#{klass.name.gsub('::', '_')}") do
          op = klass.new(:a, "z")
          @visitor.accept op, Collectors::PlainString.new
        end
      end

      def test_named_function
        func = Nodes::NamedFunction.new "omg", "omg"
        @visitor.accept func, Collectors::PlainString.new
      end

      # unary ops
      [
        Arel::Nodes::Not,
        Arel::Nodes::Group,
        Arel::Nodes::On,
        Arel::Nodes::Grouping,
        Arel::Nodes::Offset,
        Arel::Nodes::Ordering,
        Arel::Nodes::UnqualifiedColumn,
        Arel::Nodes::Top,
        Arel::Nodes::Limit,
      ].each do |klass|
        define_method("test_#{klass.name.gsub('::', '_')}") do
          op = klass.new(:a)
          @visitor.accept op, Collectors::PlainString.new
        end
      end

      # binary ops
      [
        Arel::Nodes::Assignment,
        Arel::Nodes::Between,
        Arel::Nodes::DoesNotMatch,
        Arel::Nodes::Equality,
        Arel::Nodes::GreaterThan,
        Arel::Nodes::GreaterThanOrEqual,
        Arel::Nodes::In,
        Arel::Nodes::LessThan,
        Arel::Nodes::LessThanOrEqual,
        Arel::Nodes::Matches,
        Arel::Nodes::NotEqual,
        Arel::Nodes::NotIn,
        Arel::Nodes::Or,
        Arel::Nodes::TableAlias,
        Arel::Nodes::Values,
        Arel::Nodes::As,
        Arel::Nodes::DeleteStatement,
        Arel::Nodes::JoinSource,
        Arel::Nodes::Casted,
      ].each do |klass|
        define_method("test_#{klass.name.gsub('::', '_')}") do
          binary = klass.new(:a, :b)
          @visitor.accept binary, Collectors::PlainString.new
        end
      end

      def test_Arel_Nodes_BindParam
        node = Arel::Nodes::BindParam.new(1)
        collector = Collectors::PlainString.new
        assert_match '[label="<f0>Arel::Nodes::BindParam"]', @visitor.accept(node, collector).value
      end
    end
  end
end


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.IoT.TimeSeriesInsights
{
    /// <summary> Time series model settings including model name, Time Series ID properties and default type ID. </summary>
    public partial class TimeSeriesModelSettings
    {
        /// <summary> Initializes a new instance of TimeSeriesModelSettings. </summary>
        internal TimeSeriesModelSettings()
        {
            TimeSeriesIdProperties = new ChangeTrackingList<TimeSeriesIdProperty>();
        }

        /// <summary> Initializes a new instance of TimeSeriesModelSettings. </summary>
        /// <param name="name"> Time series model display name which is shown in the UX. Examples: "Temperature Sensors", "MyDevices". </param>
        /// <param name="timeSeriesIdProperties"> Time series ID properties defined during environment creation. </param>
        /// <param name="defaultTypeId"> Default type ID of the model that new time series instances will automatically belong to. </param>
        internal TimeSeriesModelSettings(string name, IReadOnlyList<TimeSeriesIdProperty> timeSeriesIdProperties, string defaultTypeId)
        {
            Name = name;
            TimeSeriesIdProperties = timeSeriesIdProperties;
            DefaultTypeId = defaultTypeId;
        }

        /// <summary> Time series model display name which is shown in the UX. Examples: "Temperature Sensors", "MyDevices". </summary>
        public string Name { get; }
        /// <summary> Time series ID properties defined during environment creation. </summary>
        public IReadOnlyList<TimeSeriesIdProperty> TimeSeriesIdProperties { get; }
        /// <summary> Default type ID of the model that new time series instances will automatically belong to. </summary>
        public string DefaultTypeId { get; }
    }
}


text:
using System.Collections.Generic;
using System.Reactive;
using System.Threading.Tasks;
using GitHub.Models;
using ReactiveUI;

namespace GitHub.ViewModels.Documents
{
    /// <summary>
    /// View model for displaying a pull request in a document window.
    /// </summary>
    public interface IPullRequestPageViewModel : IPullRequestViewModelBase
    {
        /// <summary>
        /// Gets the number of commits in the pull request.
        /// </summary>
        int CommitCount { get; }

        /// <summary>
        /// Gets the pull request's timeline.
        /// </summary>
        IReadOnlyList<IViewModel> Timeline { get; }

        /// <summary>
        /// Gets a command that will open a commit in Team Explorer.
        /// </summary>
        ReactiveCommand<string, Unit> ShowCommit { get; }

        /// <summary>
        /// Initializes the view model with data.
        /// </summary>
        /// <param name="repository">The repository to which the pull request belongs.</param>
        /// <param name="localRepository">The local repository.</param>
        /// <param name="currentUser">The currently logged in user.</param>
        /// <param name="model">The pull request model.</param>
        Task InitializeAsync(
            RemoteRepositoryModel repository,
            LocalRepositoryModel localRepository,
            ActorModel currentUser,
            PullRequestDetailModel model);
    }
}


text:
package org.digimead.digi.ctrl.lib.base

import org.digimead.RobotEsTrick
import org.digimead.digi.ctrl.lib.DActivity
import org.digimead.digi.ctrl.lib.log.ConsoleLogger
import org.digimead.digi.ctrl.lib.log.Logging
import org.scalatest.BeforeAndAfter
import org.scalatest.FunSuite

import android.os.Bundle

class AppComponentTestOnPrepareEnvironment_j1 extends FunSuite with BeforeAndAfter with RobotEsTrick {
  lazy val roboClassHandler = RobotEsTrick.classHandler
  lazy val roboClassLoader = RobotEsTrick.classLoader
  lazy val roboDelegateLoadingClasses = RobotEsTrick.delegateLoadingClasses
  lazy val roboConfig = RobotEsTrick.config

  before {
    roboSetup
  }

  test("check environment version") {
    val activity = new android.app.Activity with DActivity {
      override def onCreate(b: Bundle) =
        super.onCreate(b: Bundle)
      val dispatcher = null
    }
    Logging.addLogger(ConsoleLogger)
    //activity.onCreate(null)
    val nativeManifest = <manifest>
                           <build>
                             <name>digiControl</name>
                             <vendor>org.digimead</vendor>
                             <version>0.0.1-20120314.122628</version>
                           </build>
                           <application>
                             <name>bridge</name>
                             <version>0.0.1.1</version>
                             <project>http://github.com/ezh/android-DigiControl</project>
                             <description>helper of the higher ground</description>
                             <license>Proprietary</license>
                             <origin>Copyright © 2011-2012 Alexey B. Aksenov/Ezh. All rights reserved.</origin>
                           </application>
                         </manifest>
    val nativeManifestInstalled = <manifest>
                                    <build>
                                      <name>digiControl</name>
                                      <vendor>org.digimead</vendor>
                                      <version>0.0.1-20120314.122629</version>
                                    </build>
                                    <application>
                                      <name>bridge</name>
                                      <version>0.0.1.1</version>
                                      <project>http://github.com/ezh/android-DigiControl</project>
                                      <description>helper of the higher ground</description>
                                      <license>Proprietary</license>
                                      <origin>Copyright © 2011-2012 Alexey B. Aksenov/Ezh. All rights reserved.</origin>
                                    </application>
                                  </manifest>
    //AppComponent.Inner.checkEnvironmentVersion(Some(nativeManifest), Some(nativeManifestInstalled)) should be(true)
    Logging.flush
  }
}


text:
//
//  MLNavigationController.m
//  MLMyLottery
//
//  Created by tarena on 16/4/20.
//  Copyright © 2016年 tarena. All rights reserved.
//

#import "MLNavigationController.h"

@interface MLNavigationController ()

@end

@implementation MLNavigationController

-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    viewController.hidesBottomBarWhenPushed = YES;
    [super pushViewController:viewController animated:animated];
}

+(void)initialize
{//第一次使用本类,或者子类的时候调用,加判断确保只调用一次,
    if (self == [MLNavigationController class]) {
        [self setupNaviBar];
        [self setupBarButton];

    }
}

+(void)setupNaviBar
{
    UINavigationBar *bar = [UINavigationBar appearance];
    //NSLog(@"%@",[UIDevice currentDevice].systemVersion);
    [bar setBackgroundImage:[UIImage imageNamed:@"NavBar64"] forBarMetrics:UIBarMetricsDefault];

    NSDictionary *dict = @{NSForegroundColorAttributeName : [UIColor whiteColor],NSFontAttributeName : [UIFont systemFontOfSize:18]};
    [bar setTitleTextAttributes:dict];
    [bar setTintColor:[UIColor whiteColor]];
}

+(void)setupBarButton
{
    UIBarButtonItem *barButton = [UIBarButtonItem appearance];
    [barButton setBackgroundImage:[UIImage imageNamed:@"NavButton"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [barButton setBackgroundImage:[UIImage imageNamed:@"NavButtonPressed"] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];

    [barButton setBackButtonBackgroundImage:[UIImage imageNamed:@"NavBackButton"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

    [barButton setBackButtonBackgroundImage:[UIImage imageNamed:@"NavBackButtonPressed"] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
}
- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
namespace JoinRpg.Data.Interfaces;

public class ProjectWithUpdateDateDto
{
    public int ProjectId { get; set; }
    public string ProjectName { get; set; }
    public DateTime LastUpdated { get; set; }
}


text:
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Monkey HTTP Server
 *  ==================
 *  Copyright 2001-2017 Eduardo Silva <eduardo@monkey.io>
 *
 *  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.
 */

#include <unistd.h>
#include <fcntl.h>
#include <sys/epoll.h>

#ifdef MK_HAVE_EVENTFD
#include <sys/eventfd.h>
#endif

#ifdef MK_HAVE_TIMERFD_CREATE
#include <sys/timerfd.h>
#endif

#include <time.h>

#include <mk_core/mk_event.h>
#include <mk_core/mk_memory.h>
#include <mk_core/mk_utils.h>

/* For old systems */
#ifndef EPOLLRDHUP
#define EPOLLRDHUP  0x2000
#endif

static inline int _mk_event_init()
{
    return 0;
}

static inline void *_mk_event_loop_create(int size)
{
    int efd;
    struct mk_event_ctx *ctx;

    /* Main event context */
    ctx = mk_mem_alloc_z(sizeof(struct mk_event_ctx));
    if (!ctx) {
        return NULL;
    }

    /* Create the epoll instance */
 #ifdef EPOLL_CLOEXEC
    efd = epoll_create1(EPOLL_CLOEXEC);
 #else
    efd = epoll_create(1);
    if (efd > 0) {
        if (fcntl(efd, F_SETFD, FD_CLOEXEC) == -1) {
            perror("fcntl");
        }
    }
 #endif

    if (efd == -1) {
        mk_libc_error("epoll_create");
        mk_mem_free(ctx);
        return NULL;
    }
    ctx->efd = efd;

    /* Allocate space for events queue */
    ctx->events = mk_mem_alloc_z(sizeof(struct epoll_event) * size);
    if (!ctx->events) {
        close(ctx->efd);
        mk_mem_free(ctx);
        return NULL;
    }
    ctx->queue_size = size;
    return ctx;
}

/* Close handlers and memory */
static inline void _mk_event_loop_destroy(struct mk_event_ctx *ctx)
{
    close(ctx->efd);
    mk_mem_free(ctx->events);
    mk_mem_free(ctx);
}

/*
 * It register certain events for the file descriptor in question, if
 * the file descriptor have not been registered, create a new entry.
 */
static inline int _mk_event_add(struct mk_event_ctx *ctx, int fd,
                                int type, uint32_t events, void *data)
{
    int op;
    int ret;
    struct mk_event *event;
    struct epoll_event ep_event;

    mk_bug(ctx == NULL);
    mk_bug(data == NULL);

    /* Verify the FD status and desired operation */
    event = (struct mk_event *) data;
    if (event->mask == MK_EVENT_EMPTY) {
        op = EPOLL_CTL_ADD;
        event->fd   = fd;
        event->status = MK_EVENT_REGISTERED;
        event->type = type;

    }
    else {
        op = EPOLL_CTL_MOD;
        if (type != MK_EVENT_UNMODIFIED) {
            event->type = type;
        }
    }
    ep_event.events = EPOLLERR | EPOLLHUP | EPOLLRDHUP;
    ep_event.data.ptr = data;

    if (events & MK_EVENT_READ) {
        ep_event.events |= EPOLLIN;
    }
    if (events & MK_EVENT_WRITE) {
        ep_event.events |= EPOLLOUT;
    }

    ret = epoll_ctl(ctx->efd, op, fd, &ep_event);
    if (ret < 0) {
        mk_libc_error("epoll_ctl");
        return -1;
    }

    event->mask = events;
    event->priority = MK_EVENT_PRIORITY_DEFAULT;
    mk_list_entry_init(&event->_priority_head);

    return ret;
}

/* Delete an event */
static inline int _mk_event_del(struct mk_event_ctx *ctx, struct mk_event *event)
{
    int ret;

    mk_bug(ctx == NULL);
    mk_bug(event == NULL);

    if (!MK_EVENT_IS_REGISTERED(event)) {
        return 0;
    }

    ret = epoll_ctl(ctx->efd, EPOLL_CTL_DEL, event->fd, NULL);

    MK_TRACE("[FD %i] Epoll, remove from QUEUE_FD=%i, ret=%i",
             event->fd, ctx->efd, ret);

    if (ret < 0) {
#ifdef MK_HAVE_TRACE
        mk_libc_warn("epoll_ctl");
#endif
    }

    /* Remove from priority queue */
    if (!mk_list_entry_is_orphan(&event->_priority_head)) {
        mk_list_del(&event->_priority_head);
    }

    MK_EVENT_NEW(event);

    return ret;
}

#ifdef MK_HAVE_TIMERFD_CREATE
/* Register a timeout file descriptor */
static inline int _mk_event_timeout_create(struct mk_event_ctx *ctx,
                                           time_t sec, long nsec, void *data)
{
    int ret;
    int timer_fd;
    struct itimerspec its;
    struct timespec now;
    struct mk_event *event;

    mk_bug(data == NULL);

    memset(&its, '\0', sizeof(struct itimerspec));

    if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) {
        mk_libc_error("clock_gettime");
        return -1;
	}

    /* expiration interval */
    its.it_interval.tv_sec  = sec;
    its.it_interval.tv_nsec = nsec;

    /*
     * initial expiration: note that we don't use nanoseconds in the timer,
     * feel free to send a Pull Request if you need it.
     */
    its.it_value.tv_sec  = now.tv_sec + sec;
    its.it_value.tv_nsec = 0;

    timer_fd = timerfd_create(CLOCK_MONOTONIC, 0);
    if (timer_fd == -1) {
        mk_libc_error("timerfd");
        return -1;
    }

    ret = timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &its, NULL);
    if (ret < 0) {
        mk_libc_error("timerfd_settime");
        close(timer_fd);
        return -1;
    }

    event = data;
    event->fd   = timer_fd;
    event->type = MK_EVENT_NOTIFICATION;
    event->mask = MK_EVENT_EMPTY;

    /* register the timer into the epoll queue */
    ret = _mk_event_add(ctx, timer_fd,
                        MK_EVENT_NOTIFICATION, MK_EVENT_READ, data);
    if (ret != 0) {
        close(timer_fd);
        return ret;
    }

    return timer_fd;
}
#else /* MK_HAVE_TIMERFD_CREATE */

struct fd_timer {
    int fd;
    time_t sec;
    long   nsec;
};

/*
 * Timeout worker, it writes a byte every certain amount of seconds, it finish
 * once the other end of the pipe closes the fd[0].
 */
void _timeout_worker(void *arg)
{
    int ret;
    uint64_t val = 1;
    struct fd_timer *timer;
    struct timespec t_spec;

    timer = (struct fd_timer *) arg;
    t_spec.tv_sec  = timer->sec;
    t_spec.tv_nsec = timer->nsec;

    while (1) {
        /* sleep for a while */
        nanosleep(&t_spec, NULL);

        /* send notification */
        ret = write(timer->fd, &val, sizeof(uint64_t));
        if (ret == -1) {
            perror("write");
            break;
        }
    }

    close(timer->fd);
    free(timer);
}

/*
 * This routine creates a timer, since timerfd_create(2) is not available (as
 * Monkey could be be compiled in a very old Linux system), we implement a similar
 * function through a thread and a pipe(2).
 */
static inline int _mk_event_timeout_create(struct mk_event_ctx *ctx,
                                           time_t sec, long nsec, void *data)
{
    int ret;
    int fd[2];
    struct mk_event *event;
    struct fd_timer *timer;
    pthread_t tid;

    mk_bug(data == NULL);

    timer = mk_mem_alloc(sizeof(struct fd_timer));
    if (!timer) {
        return -1;
    }

    ret = pipe(fd);
    if (ret < 0) {
        mk_mem_free(timer);
        mk_libc_error("pipe");
        return ret;
    }

    event = (struct mk_event *) data;
    event->fd = fd[0];
    event->type = MK_EVENT_NOTIFICATION;
    event->mask = MK_EVENT_EMPTY;

    _mk_event_add(ctx, fd[0], MK_EVENT_NOTIFICATION, MK_EVENT_READ, data);
    event->mask = MK_EVENT_READ;

    /* Compose the timer context, this is released inside the worker thread */
    timer->fd   = fd[1];
    timer->sec  = sec;
    timer->nsec = nsec;

    /* Now the dirty workaround, create a thread */
    ret = mk_utils_worker_spawn(_timeout_worker, timer, &tid);
    if (ret < 0) {
        close(fd[0]);
        close(fd[1]);
        mk_mem_free(timer);
        return -1;
    }

    return fd[0];
}
#endif /* MK_HAVE_TIMERFD_CREATE */

static inline int _mk_event_timeout_destroy(struct mk_event_ctx *ctx, void *data)
{
    struct mk_event *event;

    if (data == NULL) {
        return 0;
    }

    event = (struct mk_event *) data;
    _mk_event_del(ctx, event);
    close(event->fd);
    return 0;
}

static inline int _mk_event_channel_create(struct mk_event_ctx *ctx,
                                           int *r_fd, int *w_fd, void *data)
{
    int ret;
    int fd[2];
    struct mk_event *event;

    mk_bug(data == NULL);

    ret = pipe(fd);
    if (ret < 0) {
        mk_libc_error("pipe");
        return ret;
    }

    event = data;
    event->fd = fd[0];
    event->type = MK_EVENT_NOTIFICATION;
    event->mask = MK_EVENT_EMPTY;

    ret = _mk_event_add(ctx, fd[0],
                        MK_EVENT_NOTIFICATION, MK_EVENT_READ, event);
    if (ret != 0) {
        close(fd[0]);
        close(fd[1]);
        return ret;
    }

    *r_fd = fd[0];
    *w_fd = fd[1];

    return 0;
}

static inline int _mk_event_channel_destroy(struct mk_event_ctx *ctx,
                                            int r_fd, int w_fd, void *data)
{
    struct mk_event *event;
    int ret;

    event = (struct mk_event *)data;
    if (event->fd != r_fd) {
        return -1;
    }

    ret = _mk_event_del(ctx, event);
    if (ret != 0) {
        return ret;
    }

    close(r_fd);
    close(w_fd);

    return 0;
}

static inline int _mk_event_inject(struct mk_event_loop *loop,
                                   struct mk_event *event,
                                   int mask,
                                   int prevent_duplication)
{
    int                  index;
    struct mk_event_ctx *ctx;

    ctx = loop->data;

    if (prevent_duplication) {
        for (index = 0 ; index < loop->n_events ; index++) {
            if (ctx->events[index].data.ptr == event) {
                return 0;
            }
        }
    }

    event->mask = mask;

    ctx->events[loop->n_events].data.ptr = event;

    loop->n_events++;

    return 0;
}

static inline int _mk_event_wait_2(struct mk_event_loop *loop, int timeout)
{
    struct mk_event_ctx *ctx = loop->data;
    int ret = 0;

    while(1) {
        ret = epoll_wait(ctx->efd, ctx->events, ctx->queue_size, timeout);
        if (ret >= 0) {
            break;
        }
        else if(ret < 0 && errno != EINTR) {
            mk_libc_error("epoll_wait");
            break;
        }
        /* retry when errno is EINTR */
    }
    loop->n_events = ret;
    return ret;
}

static inline char *_mk_event_backend()
{
    return "epoll";
}


text:
package com.ethangk.tournamentmanager;

import android.app.DialogFragment;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.DialogInterface;

/**
 * Warning Fragment to prompt the user whether to continue returning to the home page
 */
public class WarningFragment extends DialogFragment {

    /* The activity that creates an instance of this dialog fragment must
     * implement this interface in order to receive event callbacks. */
    public interface WarningDialogListener {
        public void onWarningPositiveClick(DialogFragment dialog);
    }

    WarningDialogListener listener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            listener = (WarningDialogListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement WarningDialogListener");
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        builder.setTitle("Return to the home page?")
                .setMessage("All results will be deleted")
                .setPositiveButton(R.string.accept_warning, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        listener.onWarningPositiveClick(WarningFragment.this);
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User cancelled the dialog
                    }
                });
        // Create the AlertDialog object and return it
        return builder.create();
    }
}


text:
from unittest import TestCase
import json

import responses
import requests

from odata.tests import Service, Product, ColorSelection

class TestEnums(TestCase):

    def test_insert_value(self):

        def request_callback(request):
            content = json.loads(request.body)
            content['ProductID'] = 1
            self.assertIn('ColorSelection', content)
            self.assertEqual(content.get('ColorSelection'), 'Black')
            headers = {}
            return requests.codes.ok, headers, json.dumps(content)

        with responses.RequestsMock() as rsps:
            rsps.add_callback(rsps.POST,
                              Product.__odata_url__(),
                              callback=request_callback,
                              content_type='application/json')

            new_product = Product()
            new_product.name = 'Test Product'
            new_product.color_selection = ColorSelection.Black
            Service.save(new_product)

    def test_read_value(self):
        test_product_values = dict(
            ProductID=1,
            ProductName='Test Product',
            Category='',
            ColorSelection='Red',
            Price=0.0,
        )
        with responses.RequestsMock() as rsps:
            rsps.add(rsps.GET, Product.__odata_url__(),
                     content_type='application/json',
                     json=dict(value=[test_product_values]))

            product = Service.query(Product).get(1)

        self.assertIsInstance(product.color_selection, ColorSelection)
        self.assertEqual(product.color_selection, ColorSelection.Red)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.Windows.Controls
{
    public enum ClickMode
    {
        Release,
        Press,
        //Hover,
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="css/style.css" rel="stylesheet" type="text/css">

LA sfortuna gira.....

Chi sarà lo sfortunato vincitore?


text:
layout: post
title: Deep throat porn with a sexy babe
titleinfo: pornvd
desc: Watch Deep throat porn with a sexy babe. Pornhub is the ultimate xxx porn and sex site.
---

Deep throat porn with a sexy babe

Watch Deep throat porn with a sexy babe. Pornhub is the ultimate xxx porn and sex site.


text:
namespace NathanAlden.Proxy.HttpClient
{
    public enum GetRequestLineResult
    {
        Success,
        InvalidRequestLine
    }
}


text:
package org.hyalinedto.core.proxy;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.hyalinedto.core.ClassRepository;

public class InMemoryClassRepository implements ClassRepository<String, Class<?>>{

	private Map<String, Class<?>> repo = new HashMap<String, Class<?>>();

	@Override
	public int size() {
		return repo.size();
	}

	@Override
	public boolean isEmpty() {
		return repo.isEmpty();
	}

	@Override
	public boolean containsKey(Object key) {
		return repo.containsKey(key);
	}

	@Override
	public boolean containsValue(Object value) {
		return repo.containsValue(value);
	}

	@Override
	public Class<?> get(Object key) {
		return repo.get(key);
	}

	@Override
	public Class<?> put(String key, Class<?> value) {
		return repo.put(key, value);
	}

	@Override
	public Class<?> remove(Object key) {
		return repo.remove(key);
	}

	@Override
	public void putAll(Map<? extends String, ? extends Class<?>> m) {
		repo.putAll(m);
	}

	@Override
	public void clear() {
		repo.clear();
	}

	@Override
	public Set<String> keySet() {
		return repo.keySet();
	}

	@Override
	public Collection<Class<?>> values() {
		return repo.values();
	}

	@Override
	public Set<java.util.Map.Entry<String, Class<?>>> entrySet() {
		return repo.entrySet();
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<SAXEvents>
  <startDocument/>
  <startElement>
    <namespaceURI/>
    <localName>foo</localName>
    <qualifiedName>foo</qualifiedName>
    <attributes/>
  </startElement>
  <resolveEntity>
    <name>ent</name>
    <baseURI>eduni/xml-1.1</baseURI>
    <systemID>003.ent</systemID>
  </resolveEntity>
  <fatalError>external general entity has later version number</fatalError>
  <endDocument/>
</SAXEvents>


text:
import java.util.Scanner;

import jsjf.LinkedQueue;
import jsjf.QueueADT;

/**
 * Codes.java<br>
 * Mar 25, 2015
 * @author Tim Miller
 */
public class Codes
{
	/**
	 * Encode and decode a message using a key of values stored in
	 * a queue.
	 */
	public static void main(String[] args)
	{
		Scanner scan = new Scanner(System.in);
		String again;
		do
		{
			int[] key;
			int keysize;
			Integer keyValue;
			String encoded = "", decoded = "", message = "";

			System.out.println("Please enter a message: ");
			message = scan.nextLine();
			System.out.println("Please enter the length of the key");
			keysize = scan.nextInt();
			key = new int[keysize];
			for (int index = 0; index < keysize; index++)
			{
				System.out.println("Please enter key index " + (index + 1)
						+ ": ");
				key[index] = scan.nextInt();
			}
			System.out.println("\nOriginal Message: \n" + message + "\n");
			final QueueADT<Integer> encodingQueue = new LinkedQueue<Integer>();
			final QueueADT<Integer> decodingQueue = new LinkedQueue<Integer>();
			// load key queues
			for (final int element : key)
			{
				encodingQueue.enqueue(element);
				decodingQueue.enqueue(element);
			}

			// encode message
			for (int index = 0; index < message.length(); index++)
			{
				keyValue = encodingQueue.dequeue();
				encoded += (char) (message.charAt(index) + keyValue);
				encodingQueue.enqueue(keyValue);
			}
			System.out.println("Encoded Message:\n" + encoded + "\n");

			// decode message
			for (int index = 0; index < encoded.length(); index++)
			{
				keyValue = decodingQueue.dequeue();
				decoded += (char) (encoded.charAt(index) - keyValue);
				decodingQueue.enqueue(keyValue);
			}
			System.out.println("Decoded Message:\n" + decoded);

			scan = new Scanner(System.in);
			System.out
					.println("Go again? (Enter 'Y' to run again, enter any other character to exit)");
			again = scan.nextLine();
		}
		while (again.equalsIgnoreCase("Y"));
		scan.close();
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<import resource="classpath:workflow-engine-application-context.xml" />
<import resource="classpath:workflow-engine-configuration.xml" />

<bean id="webConsoleAuthenticationProvider" class="ee.telekom.workflow.example.security.DummyAuthenticationProvider" />
<bean id="configuration" class="org.apache.commons.configuration.PropertiesConfiguration">
  <constructor-arg value="application.properties" />
</bean>

</beans>


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Erysiphe communis f. gueldenstaedtii Bunkina

### Remarks
null


text:
using System;
using Microsoft.CodeAnalysis.Editor.Implementation.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.EditorUtilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure
{
    [UseExportProvider]
    public class AbstractStructureTaggerProviderTests
    {
        private static void TextContainsRegionOrUsing(string input, bool expected, string language)
        {
            var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
            var buffer = EditorFactory.CreateBuffer(exportProvider, input.Split(new string[] { Environment.NewLine }, StringSplitOptions.None));
            var textSnapshot = buffer.CurrentSnapshot;

            var actual = AbstractStructureTaggerProvider.ContainsRegionOrImport(textSnapshot, collapseRegions: true, collapseImports: true, language);
            Assert.Equal(expected, actual);
        }

        [Fact]
        public void UsingDirective()
        {
            var input = @"
using System;
";

            TextContainsRegionOrUsing(input, true, LanguageNames.CSharp);
        }

        [Fact]
        public void UsingDirectiveInNamespace()
        {
            var input = @"
namespace Goo
{
    using System;
}
";

            TextContainsRegionOrUsing(input, true, LanguageNames.CSharp);
        }

        [Fact]
        public void UsingStaticDirective()
        {
            var input = @"
using static System;
";

            TextContainsRegionOrUsing(input, true, LanguageNames.CSharp);
        }

        [Fact]
        public void UsingAliasDirective()
        {
            var input = @"
using A = System;
";

            TextContainsRegionOrUsing(input, true, LanguageNames.CSharp);
        }

        [Fact]
        public void ExternAlias()
        {
            var input = @"
extern alias Goo;
";

            TextContainsRegionOrUsing(input, true, LanguageNames.CSharp);
        }

        [Fact]
        public void ImportsStatement()
        {
            var input = @"
Imports System
";

            TextContainsRegionOrUsing(input, true, LanguageNames.VisualBasic);
        }

        [Fact]
        public void ImportsAliasStatement()
        {
            var input = @"
Imports A = System
";

            TextContainsRegionOrUsing(input, true, LanguageNames.VisualBasic);
        }

        [Fact]
        public void CSharpRegion1()
        {
            var input = @"
    #region
";

            TextContainsRegionOrUsing(input, true, LanguageNames.CSharp);
        }

        [Fact]
        public void CSharpRegion()
        {
            var input = @"
    #region Goo
";

            TextContainsRegionOrUsing(input, true, LanguageNames.CSharp);
        }

        [Fact]
        public void VisualBasicRegion()
        {
            var input = @"
#Region Goo
";

            TextContainsRegionOrUsing(input, true, LanguageNames.VisualBasic);
        }
    }
}


text:
package com.vaadin.tests.widgetset.client;

import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Panel;
import com.vaadin.client.ComponentConnector;
import com.vaadin.client.ConnectorHierarchyChangeEvent;
import com.vaadin.client.WidgetUtil;
import com.vaadin.client.ui.AbstractComponentContainerConnector;
import com.vaadin.client.ui.VVerticalLayout;
import com.vaadin.shared.ui.Connect;
import com.vaadin.shared.ui.orderedlayout.VerticalLayoutState;
import com.vaadin.tests.components.customlayout.OverflowAutoFix;

@SuppressWarnings("deprecation")
@Connect(OverflowAutoFix.RunOverflowFix.class)
public class RunOverflowFixConnector extends
        AbstractComponentContainerConnector {

    private static final String CONTENT1 = "Overflow:
Fix1 (scroll): Both scrollbars should be shown
Fix2 (visible): no scrollbars should be shown";
    private static final String CONTENT2 = "OverflowX:
Fix1 (hidden): Horizontal scrollbar should be hidden, vertical shown
Fix2 (scroll): Both scrollbars should be shown";
    private static final String CONTENT3 = "OverflowY:
Fix1 (hidden): Vertical scrollbar should be hidden, horizontal shown
Fix2 (auto): Both scrollbars should be shown";
    private static final String BACKGROUND = "#ddd";

    @Override
    public void init() {
        super.init();

        final Panel overflow = createScrollPanel(CONTENT1);
        overflow.addStyleName("first-scrollbar");
        final Panel overflowX = createScrollPanel(CONTENT2);
        overflowX.addStyleName("second-scrollbar");
        final Panel overflowY = createScrollPanel(CONTENT3);
        overflowY.addStyleName("third-scrollbar");

        Button runFix = new Button("Click to runWebkitOverflowAutoFix",
                new ClickHandler() {
                    @Override
                    public void onClick(ClickEvent event) {
                        overflow.getElement().getStyle()
                                .setOverflow(Style.Overflow.SCROLL);
                        WidgetUtil.runWebkitOverflowAutoFix(overflow
                                .getElement());

                        overflowX.getElement().getStyle()
                                .setOverflowX(Style.Overflow.HIDDEN);
                        WidgetUtil.runWebkitOverflowAutoFix(overflowX
                                .getElement());

                        overflowY.getElement().getStyle()
                                .setOverflowY(Style.Overflow.HIDDEN);
                        WidgetUtil.runWebkitOverflowAutoFix(overflowY
                                .getElement());
                    }
                });
        runFix.addStyleName("run-button-one");
        getWidget().add(runFix);

        Button runFix2 = new Button("Click to runWebkitOverflowAutoFix 2",
                new ClickHandler() {
                    @Override
                    public void onClick(ClickEvent event) {
                        overflow.getElement().getStyle()
                                .setOverflow(Style.Overflow.VISIBLE);
                        WidgetUtil.runWebkitOverflowAutoFix(overflow
                                .getElement());

                        overflowX.getElement().getStyle()
                                .setOverflowX(Style.Overflow.SCROLL);
                        WidgetUtil.runWebkitOverflowAutoFix(overflowX
                                .getElement());

                        overflowY.getElement().getStyle()
                                .setOverflowY(Style.Overflow.AUTO);
                        WidgetUtil.runWebkitOverflowAutoFix(overflowY
                                .getElement());
                    }
                });
        runFix2.addStyleName("run-button-two");
        getWidget().add(runFix2);

        addSpacer(10);
        getWidget().add(overflow);
        addSpacer(60);
        getWidget().add(overflowX);
        addSpacer(60);
        getWidget().add(overflowY);
    }

    private void addSpacer(double height) {
        Element spacer = DOM.createDiv();
        spacer.getStyle().setHeight(height, Unit.PX);
        spacer.getStyle().setWidth(10, Unit.PX);
        getWidget().getElement().appendChild(spacer);
    }

    private Panel createScrollPanel(String info) {
        FlowPanel outer = new FlowPanel();
        outer.setPixelSize(300, 200);
        getWidget().add(outer);

        HTML inner = new HTML(info);
        inner.setPixelSize(350, 250);
        inner.getElement().getStyle().setBackgroundColor(BACKGROUND);
        // for some reason theme sets size to 0
        inner.getElement().getStyle().setFontSize(12, Style.Unit.PX);
        outer.add(inner);

        return outer;
    }

    @Override
    public VVerticalLayout getWidget() {
        return (VVerticalLayout) super.getWidget();
    }

    @Override
    public VerticalLayoutState getState() {
        return (VerticalLayoutState) super.getState();
    }

    @Override
    public void updateCaption(ComponentConnector connector) {
    }

    @Override
    public void onConnectorHierarchyChange(
            ConnectorHierarchyChangeEvent connectorHierarchyChangeEvent) {
    }
}


text:
<!DOCTYPE html>

  <title>Polling Tasks</title>

{{ counter }}

    <input type="checkbox" v-model="task.completed" v-bind:true-value="1" v-bind:false-value="0" v-on:change="updateTask(task)">{{ task.title }}: {{ task.description }}

  <form action="http://polling.local/create" method="post" accept-charset="utf-8" v-on:submit.prevent="submitForm">
    <input type="text" v-model="newTask.title" name="title" value="" placeholder="Title">
    <input type="text" v-model="newTask.description" name="description" value="" placeholder="Description">

      <input type="checkbox" id="completed" v-model="newTask.completed" name="completed" v-bind:true-value="1" v-bind:false-value="0">Completed

    <input type="submit" name="submit" value="Create Task">
  </form>


text:
package demo.lonly.stp.core;

import demo.lonly.stp.util.RequestUtil;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.ESLoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 远程接口调用分词服务实现
 * Created by Lonly on 2016/7/21.
 */
public class RemoteSegmenter implements ISegmenter {

    private ESLogger logger = ESLoggerFactory.getLogger("RemoteSegmenter");

    private String tag_url;
    private List<String> words = new ArrayList<String>();

    public RemoteSegmenter(String url) {
        this.tag_url = url;
    }

    @Override
    public List<String> segment(String target) {
        // Clean the word token
        this.words.clear();
        // Get the new word token of target
        URL url = null;
        try {
            url = new URL(this.tag_url.trim() + "?content="
                    + URLEncoder.encode(target.trim(), "UTF-8"));
        } catch (MalformedURLException | UnsupportedEncodingException e) {
            logger.error(e.getMessage());
        }
        String res = RequestUtil.doRequest(url);
        makeToken(res);
        return this.words;
    }

    private void makeToken(String str) {
        try {
            // Get Json-array as it encoded before
            List<String> jaTemp = Arrays.asList(str.replaceAll("\"", "").replace("\n", "").split(" "));
            if (jaTemp.size() > 0) {
                jaTemp.forEach(item -> {
                    this.words.add(item);
                });
            } else {
                logger.info("No string input", jaTemp);
            }

        } catch (Exception e) {
            logger.error("Exception", e, e);
            throw new RuntimeException("Exception");
        }
    }
}


text:
var profile = require('../../../lib/util/profile');

exports.getMockedProfile = function () {
  var newProfile = new profile.Profile();

  newProfile.addSubscription(new profile.Subscription({
    id: 'c9cbd920-c00c-427c-852b-8aaf38badaeb',
    name: 'Azure SDK Powershell Test',
    user: {
      name: 'user@domain.example',
      type: 'user'
    },
    tenantId: '72f988bf-86f1-41af-91ab-2d7cd011db47',
    registeredProviders: ['website'],
    _eventsCount: '1',
    isDefault: true
  }, newProfile.environments['AzureCloud']));

  return newProfile;
};

exports.setEnvironment = function() {
  process.env['AZURE_STORAGE_CONNECTION_STRING'] = 'DefaultEndpointsProtocol=https;AccountName=xplat;AccountKey=null';
};

exports.scopes = [[function (nock) {
var result =
nock('http://xplat.blob.core.windows.net:443')
  .get('/?comp=properties&restype=service')
  .reply(200, "<?xml version=\"1.0\" encoding=\"utf-8\"?><StorageServiceProperties><Logging><Version>1.0</Version><Read>true</Read><Write>true</Write><Delete>false</Delete><RetentionPolicy><Enabled>true</Enabled><Days>10</Days></RetentionPolicy></Logging><HourMetrics><Version>1.0</Version><Enabled>true</Enabled><IncludeAPIs>true</IncludeAPIs><RetentionPolicy><Enabled>true</Enabled><Days>10</Days></RetentionPolicy></HourMetrics><MinuteMetrics><Version>1.0</Version><Enabled>false</Enabled><RetentionPolicy><Enabled>false</Enabled></RetentionPolicy></MinuteMetrics><Cors /><DefaultServiceVersion>2015-04-05</DefaultServiceVersion></StorageServiceProperties>", { 'transfer-encoding': 'chunked',
  'content-type': 'application/xml',
  server: 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0',
  'x-ms-request-id': '1f72ee02-0001-0029-7ad2-bfe045000000',
  'x-ms-version': '2015-04-05',
  date: 'Mon, 06 Jun 2016 09:03:27 GMT',
  connection: 'close' });
 return result; },
function (nock) {
var result =
nock('https://xplat.blob.core.windows.net:443')
  .get('/?comp=properties&restype=service')
  .reply(200, "<?xml version=\"1.0\" encoding=\"utf-8\"?><StorageServiceProperties><Logging><Version>1.0</Version><Read>true</Read><Write>true</Write><Delete>false</Delete><RetentionPolicy><Enabled>true</Enabled><Days>10</Days></RetentionPolicy></Logging><HourMetrics><Version>1.0</Version><Enabled>true</Enabled><IncludeAPIs>true</IncludeAPIs><RetentionPolicy><Enabled>true</Enabled><Days>10</Days></RetentionPolicy></HourMetrics><MinuteMetrics><Version>1.0</Version><Enabled>false</Enabled><RetentionPolicy><Enabled>false</Enabled></RetentionPolicy></MinuteMetrics><Cors /><DefaultServiceVersion>2015-04-05</DefaultServiceVersion></StorageServiceProperties>", { 'transfer-encoding': 'chunked',
  'content-type': 'application/xml',
  server: 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0',
  'x-ms-request-id': '1f72ee02-0001-0029-7ad2-bfe045000000',
  'x-ms-version': '2015-04-05',
  date: 'Mon, 06 Jun 2016 09:03:27 GMT',
  connection: 'close' });
 return result; },
function (nock) {
var result =
nock('http://xplat.table.core.windows.net:443')
  .get('/?comp=properties&restype=service')
  .reply(200, "<?xml version=\"1.0\" encoding=\"utf-8\"?><StorageServiceProperties><Logging><Version>1.0</Version><Read>true</Read><Write>false</Write><Delete>true</Delete><RetentionPolicy><Enabled>false</Enabled></RetentionPolicy></Logging><HourMetrics><Version>1.0</Version><Enabled>true</Enabled><IncludeAPIs>false</IncludeAPIs><RetentionPolicy><Enabled>false</Enabled></RetentionPolicy></HourMetrics><MinuteMetrics><Version>1.0</Version><Enabled>false</Enabled><RetentionPolicy><Enabled>false</Enabled></RetentionPolicy></MinuteMetrics><Cors /></StorageServiceProperties>", { 'transfer-encoding': 'chunked',
  'content-type': 'application/xml',
  server: 'Windows-Azure-Table/1.0 Microsoft-HTTPAPI/2.0',
  'x-ms-request-id': '541305da-0002-0046-07d2-bf4891000000',
  'x-ms-version': '2015-04-05',
  date: 'Mon, 06 Jun 2016 09:03:28 GMT',
  connection: 'close' });
 return result; },
function (nock) {
var result =
nock('https://xplat.table.core.windows.net:443')
  .get('/?comp=properties&restype=service')
  .reply(200, "<?xml version=\"1.0\" encoding=\"utf-8\"?><StorageServiceProperties><Logging><Version>1.0</Version><Read>true</Read><Write>false</Write><Delete>true</Delete><RetentionPolicy><Enabled>false</Enabled></RetentionPolicy></Logging><HourMetrics><Version>1.0</Version><Enabled>true</Enabled><IncludeAPIs>false</IncludeAPIs><RetentionPolicy><Enabled>false</Enabled></RetentionPolicy></HourMetrics><MinuteMetrics><Version>1.0</Version><Enabled>false</Enabled><RetentionPolicy><Enabled>false</Enabled></RetentionPolicy></MinuteMetrics><Cors /></StorageServiceProperties>", { 'transfer-encoding': 'chunked',
  'content-type': 'application/xml',
  server: 'Windows-Azure-Table/1.0 Microsoft-HTTPAPI/2.0',
  'x-ms-request-id': '541305da-0002-0046-07d2-bf4891000000',
  'x-ms-version': '2015-04-05',
  date: 'Mon, 06 Jun 2016 09:03:28 GMT',
  connection: 'close' });
 return result; },
function (nock) {
var result =
nock('http://xplat.queue.core.windows.net:443')
  .get('/?comp=properties&restype=service')
  .reply(200, "<?xml version=\"1.0\" encoding=\"utf-8\"?><StorageServiceProperties><Logging><Version>1.0</Version><Read>false</Read><Write>true</Write><Delete>true</Delete><RetentionPolicy><Enabled>true</Enabled><Days>5</Days></RetentionPolicy></Logging><HourMetrics><Version>1.0</Version><Enabled>false</Enabled><RetentionPolicy><Enabled>false</Enabled></RetentionPolicy></HourMetrics><MinuteMetrics><Version>1.0</Version><Enabled>false</Enabled><RetentionPolicy><Enabled>true</Enabled><Days>10</Days></RetentionPolicy></MinuteMetrics><Cors /></StorageServiceProperties>", { 'cache-control': 'no-cache',
  'transfer-encoding': 'chunked',
  'content-type': 'application/xml',
  server: 'Windows-Azure-Queue/1.0 Microsoft-HTTPAPI/2.0',
  'x-ms-request-id': 'b944e450-0003-004b-23d2-bfa79d000000',
  'x-ms-version': '2015-04-05',
  date: 'Mon, 06 Jun 2016 09:03:28 GMT',
  connection: 'close' });
 return result; },
function (nock) {
var result =
nock('https://xplat.queue.core.windows.net:443')
  .get('/?comp=properties&restype=service')
  .reply(200, "<?xml version=\"1.0\" encoding=\"utf-8\"?><StorageServiceProperties><Logging><Version>1.0</Version><Read>false</Read><Write>true</Write><Delete>true</Delete><RetentionPolicy><Enabled>true</Enabled><Days>5</Days></RetentionPolicy></Logging><HourMetrics><Version>1.0</Version><Enabled>false</Enabled><RetentionPolicy><Enabled>false</Enabled></RetentionPolicy></HourMetrics><MinuteMetrics><Version>1.0</Version><Enabled>false</Enabled><RetentionPolicy><Enabled>true</Enabled><Days>10</Days></RetentionPolicy></MinuteMetrics><Cors /></StorageServiceProperties>", { 'cache-control': 'no-cache',
  'transfer-encoding': 'chunked',
  'content-type': 'application/xml',
  server: 'Windows-Azure-Queue/1.0 Microsoft-HTTPAPI/2.0',
  'x-ms-request-id': 'b944e450-0003-004b-23d2-bfa79d000000',
  'x-ms-version': '2015-04-05',
  date: 'Mon, 06 Jun 2016 09:03:28 GMT',
  connection: 'close' });
 return result; }]];


text:
using namespace Annwvyn;

class Demo0 : public AbstractLevel
{
public:

	Demo0() : AbstractLevel(),
		os(NULL),
		lboundingBox(NULL),
		rboundingBox(NULL),
		now(0),
		last(0)
	{}

	virtual void load()
	{
		AnnEngine* GameEngine = AnnEngine::Instance();
		os = new ObjectSpawner(GameEngine);
		os->setEntityName("Ball.mesh");
		os->setSpawnPoint(AnnVect3(0.1f, 0.55f, 10.3f));
		AnnLightObject* l (GameEngine->addLight());
		l->setPosition(Ogre::Vector3(0,1,10));
		levelLighting.push_back(l);

		AnnLightObject* sun (GameEngine->addLight());
		sun->setType(Ogre::Light::LT_DIRECTIONAL);
		sun->setDirection(Ogre::Vector3(-1,1,1));
		sun->setDiffuseColour(Ogre::ColourValue(1,1,.85f));
		levelLighting.push_back(sun);

		GameEngine->setAmbiantLight(Ogre::ColourValue(.25f,.25f,.25f));

		GameEngine->setSkyDomeMaterial(true, "Sky/dome1");
		GameEngine->log("Demo0 level loaded");
		AnnGameObject* House = GameEngine->createGameObject("house.mesh");
		House->setPos(0.15f,-.65f,12);

		House->setUpPhysics();

		levelContent.push_back(House);

		AnnGameObject* BasePlane = GameEngine->createGameObject("Plane.mesh");
		BasePlane->setPos(0, -.60f, 11);
		BasePlane->setUpPhysics();

		levelContent.push_back(BasePlane);

		AnnGameObject* Table = GameEngine->createGameObject("Table.mesh");
		Table->setPos(0.15f,-.08f,10.5);
		Table->setUpBullet();

		levelContent.push_back(Table);

		GameEngine->getPlayer()->setPosition(Ogre::Vector3(0,1,10));
		GameEngine->getPlayer()->setOrientation(Ogre::Euler(Ogre::Real(M_PI)));
		GameEngine->resetPlayerPhysics();

		//GrabableObject* ball = (GrabableObject*) GameEngine->createGameObject("Ball.mesh", new GrabableObject);
		//levelContent.push_back(ball);

		//ball->setPos();

		lboundingBox = GameEngine->createGameObject("Box.mesh");
		rboundingBox = GameEngine->createGameObject("Box.mesh");

		Ogre::Vector3 size(0.25f,0.02f,0.15f);

		lboundingBox->setScale(size);
		rboundingBox->setScale(size);

		lboundingBox->setUpPhysics(0, boxShape, false);
		rboundingBox->setUpPhysics(0, boxShape, false);

		lboundingBox->Entity()->setVisible(false);
		rboundingBox->Entity()->setVisible(false);

		levelContent.push_back(lboundingBox);
		levelContent.push_back(rboundingBox);
	}

	virtual void unload()
	{
		os->reset();
		delete os;
		os = NULL;
		AbstractLevel::unload();
	}

	virtual void runLogic()
	{
		now = AnnEngine::Instance()->getTimeFromStartUp();

		if(now - last >= 1000)
		{
			last = now;
			os->spawn();
		}

		if(os->getList().size() >= 15)
			os->reset();

		HandObject* leftHand(LeapVisualizer::getHands()[0]);
		HandObject* rightHand(LeapVisualizer::getHands()[1]);
		lboundingBox->setPos(leftHand->pos());
		rboundingBox->setPos(rightHand->pos());

		lboundingBox->setOrientation(leftHand->getWristOrientation());
		rboundingBox->setOrientation(rightHand->getWristOrientation());

		if(!leftHand->isVisible()) lboundingBox->setPos(0,1000,0);
		if(!rightHand->isVisible()) rboundingBox->setPos(0,1000,0);
 	}

private:
	ObjectSpawner* os;
	AnnGameObject* lboundingBox;
	AnnGameObject* rboundingBox;
	double now, last;
};
#endif


text:
'use strict'
require('promise-polyfill')

const Code = require('code')
const Lab = require('lab')
const sinon = require('sinon')
require('sinon-as-promised')

const createApp = require('./fixtures/create-coworkers-app.js')

const coworkersTest = require('../index.js')

const lab = module.exports.lab = Lab.script()
const describe = lab.describe
const expect = Code.expect
const it = lab.it

describe('mockContext', function () {
  describe('allow for publish assertions via sinon', function () {
    it('should allow for sinon assertions for context.publish', function (done) {
      const app = createApp()
      coworkersTest(app)
        .send('publish-queue', {})
        .expectAck()
        .expect(function (err, context) {
          expect(err).to.not.exist()
          sinon.assert.calledOnce(context.publish)
          sinon.assert.calledOnce(context.publisherChannel.publish)
          sinon.assert.calledWith(context.publish,
            'exchange-name', 'routing.key', 'content', {})
          sinon.assert.calledWith(context.publisherChannel.publish,
            'exchange-name', 'routing.key', new Buffer('content'), {})
          done()
        })
    })
    it('should allow for sinon assertions for context.sendToQueue', function (done) {
      const app = createApp()
      coworkersTest(app)
        .send('send-queue', {})
        .expectAck()
        .expect(function (err, context) {
          expect(err).to.not.exist()
          sinon.assert.calledOnce(context.sendToQueue)
          sinon.assert.calledOnce(context.publisherChannel.sendToQueue)
          sinon.assert.calledWith(context.sendToQueue,
            'queue-name', 'content', {})
          sinon.assert.calledWith(context.publisherChannel.sendToQueue,
            'queue-name', new Buffer('content'), {})
          done()
        })
    })
  })
})


text:
require "spec_helper"

describe Mongoid::Copyable do

  describe "#clone" do

    let(:person) do
      Person.new(:title => "Sir")
    end

    before do
      person.new_record = false
      person.addresses << Address.new(:street => "Bond")
    end

    context "when versions exist" do

      let(:cloned) do
        person.clone
      end

      before do
        person[:versions] = [ { :number => 1 } ]
      end

      it "returns a new document" do
        cloned.should_not be_persisted
      end

      it "has an id" do
        cloned.id.should_not be_nil
      end

      it "has a different id from the original" do
        cloned.id.should_not == person.id
      end

      it "does not clone the versions" do
        cloned[:versions].should be_nil
      end

      it "unmemoizes the relations" do
        cloned.addresses.should_not be_eql(person.addresses)
      end

      it "returns a new instance" do
        cloned.should_not be_eql(person)
      end

      Mongoid::Copyable::COPYABLES.each do |name|

        it "dups #{name}" do
          cloned.instance_variable_get(name).should_not
            be_eql(person.instance_variable_get(name))
        end
      end
    end
  end

  describe "#dup" do

    let(:person) do
      Person.new(:title => "Sir")
    end

    before do
      person.new_record = false
      person.addresses << Address.new(:street => "Bond")
    end

    context "when versions exist" do

      let(:duped) do
        person.dup
      end

      before do
        person[:versions] = [ { :number => 1 } ]
      end

      it "returns a new document" do
        duped.should_not be_persisted
      end

      it "has an id" do
        duped.id.should_not be_nil
      end

      it "has a different id from the original" do
        duped.id.should_not == person.id
      end

      it "does not clone the versions" do
        duped[:versions].should be_nil
      end

      it "unmemoizes the relations" do
        duped.addresses.should_not be_eql(person.addresses)
      end

      it "returns a new instance" do
        duped.should_not be_eql(person)
      end

      Mongoid::Copyable::COPYABLES.each do |name|

        it "dups #{name}" do
          duped.instance_variable_get(name).should_not
            be_eql(person.instance_variable_get(name))
        end
      end
    end
  end
end


text:
<?php

namespace app\models\base;

use Yii;

/**
 * This is the base-model class for table "card".
 *
 * @property integer $card_id
 * @property string $card_set_id
 * @property integer $card_type_id
 * @property string $name
 * @property string $rarity
 * @property string $manacost
 * @property integer $converted_manacost
 * @property string $ability
 * @property string $color
 * @property string $created_at
 * @property string $updated_at
 *
 * @property CardType $cardType
 * @property CardSet $cardSet
 * @property UserHasCard[] $userHasCards
 * @property User[] $users
 */
class CardBase extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'card';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['card_id', 'card_set_id', 'card_type_id', 'name', 'rarity'], 'required'],
            [['card_id', 'card_type_id', 'converted_manacost'], 'integer'],
            [['ability'], 'string'],
            [['created_at', 'updated_at'], 'safe'],
            [['card_set_id', 'name', 'rarity', 'manacost', 'color'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'card_id' => 'Card ID',
            'card_set_id' => 'Card Set ID',
            'card_type_id' => 'Card Type ID',
            'name' => 'Name',
            'rarity' => 'Rarity',
            'manacost' => 'Manacost',
            'converted_manacost' => 'Converted Manacost',
            'ability' => 'Ability',
            'color' => 'Color',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCardType()
    {
        return $this->hasOne(\app\models\CardType::className(), ['card_type_id' => 'card_type_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCardSet()
    {
        return $this->hasOne(\app\models\CardSet::className(), ['card_set_id' => 'card_set_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUserHasCards()
    {
        return $this->hasMany(\app\models\UserHasCard::className(), ['card_id' => 'card_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUsers()
    {
        return $this->hasMany(\app\models\User::className(), ['user_id' => 'user_id'])->viaTable('user_has_card', ['card_id' => 'card_id']);
    }
}


text:
package ch.ethz.dalab.dissolve.classification

import ch.ethz.dalab.dissolve.optimization.SolverOptions
import org.apache.spark.rdd.RDD
import java.io.FileWriter
import ch.ethz.dalab.dissolve.regression.LabeledObject
import org.apache.spark.mllib.regression.LabeledPoint
import breeze.linalg._
import ch.ethz.dalab.dissolve.optimization.SolverUtils
import ch.ethz.dalab.dissolve.optimization.DissolveFunctions
import ch.ethz.dalab.dissolve.optimization.DBCFWSolverTuned
import scala.collection.mutable.HashMap
import org.apache.spark.rdd.PairRDDFunctions
import ch.ethz.dalab.dissolve.optimization.SSGSolver
import ch.ethz.dalab.dissolve.optimization.SSGSolver
import ch.ethz.dalab.dissolve.optimization.UseDBCFWSolver
import ch.ethz.dalab.dissolve.optimization.UseSSGSolver

case class MultiClassLabel(label: Double, numClasses: Int)

object MultiClassSVMWithDBCFW extends DissolveFunctions[Vector[Double], MultiClassLabel] {

  var labelToWeight = HashMap[MultiClassLabel, Double]()

  override def classWeights(label: MultiClassLabel): Double = {
    labelToWeight.get(label).getOrElse(1.0)
  }

  /**
   * Feature function
   *
   * Analogous to phi(y) in (2)
   * Returns y_i * x_i
   *
   */
  def featureFn(x: Vector[Double], y: MultiClassLabel): Vector[Double] = {
    assert(y.label.toInt < y.numClasses,
      "numClasses = %d. Found y_i.label = %d"
        .format(y.numClasses, y.label.toInt))

    val featureVector = Vector.zeros[Double](x.size * y.numClasses)
    val numDims = x.size

    // Populate the featureVector in blocks [<class-0 features> <class-1 features> ...].
    val startIdx = y.label.toInt * numDims
    val endIdx = startIdx + numDims

    featureVector(startIdx until endIdx) := x

    featureVector
  }

  /**
   * Loss function
   *
   * Returns 0 if yTruth == yPredict, 1 otherwise
   * Equivalent to max(0, 1 - y w^T x)
   */
  def lossFn(yTruth: MultiClassLabel, yPredict: MultiClassLabel): Double =
    if (yTruth.label == yPredict.label)
      0.0
    else
      1.0

  /**
   * Maximization Oracle
   *
   * Want: argmax L(y_i, y) - <w, psi_i(y)>
   * This returns the most violating (Loss-augmented) label.
   */
  override def oracleFn(model: StructSVMModel[Vector[Double], MultiClassLabel], xi: Vector[Double], yi: MultiClassLabel): MultiClassLabel = {

    val weights = model.getWeights()
    val numClasses = yi.numClasses

    // Obtain a list of scores for each class
    val mostViolatedContraint: (Double, Double) =
      (0 until numClasses).map {
        case cl =>
          (cl, weights dot featureFn(xi, MultiClassLabel(cl, numClasses)))
      }.map {
        case (cl, score) =>
          (cl.toDouble, score + 1.0)
      }.map { // Loss-augment the scores
        case (cl, score) =>
          if (yi.label == cl)
            (cl, score - 1.0)
          else
            (cl, score)
      }.maxBy { // Obtain the class with the maximum value
        case (cl, score) => score
      }

    MultiClassLabel(mostViolatedContraint._1, numClasses)
  }

  /**
   * Prediction function
   */
  def predictFn(model: StructSVMModel[Vector[Double], MultiClassLabel], xi: Vector[Double]): MultiClassLabel = {

    val weights = model.getWeights()
    val numClasses = model.numClasses

    assert(numClasses > 1)

    val prediction =
      (0 until numClasses).map {
        case cl =>
          (cl.toDouble, weights dot featureFn(xi, MultiClassLabel(cl, numClasses)))
      }.maxBy { // Obtain the class with the maximum value
        case (cl, score) => score
      }

    MultiClassLabel(prediction._1, numClasses)

  }

  /**
   * Classifying with in-built functions
   *
   * data needs to be 0-indexed
   */
  def train(
    data: RDD[LabeledPoint],
    numClasses: Int,
    solverOptions: SolverOptions[Vector[Double], MultiClassLabel],
    customWeights:Option[HashMap[MultiClassLabel,Double]]=None): StructSVMModel[Vector[Double], MultiClassLabel] = {

    solverOptions.numClasses = numClasses

    // Convert the RDD[LabeledPoint] to RDD[LabeledObject]
    val objectifiedData: RDD[LabeledObject[Vector[Double], MultiClassLabel]] =
      data.map {
        case x: LabeledPoint =>
          val features: Vector[Double] = x.features match {
            case features: org.apache.spark.mllib.linalg.SparseVector =>
              val builder: VectorBuilder[Double] = new VectorBuilder(features.indices, features.values, features.indices.length, x.features.size)
              builder.toSparseVector
            case _ => SparseVector(x.features.toArray)
          }
          new LabeledObject[Vector[Double], MultiClassLabel](MultiClassLabel(x.label, numClasses), features)
      }

    labelToWeight = ClassificationUtils.generateClassWeights(objectifiedData,solverOptions.classWeights,customWeights)

    val repartData =
      if (solverOptions.enableManualPartitionSize)
        objectifiedData.repartition(solverOptions.NUM_PART)
      else
        objectifiedData

    println(solverOptions)

    val (trainedModel,debugInfo) = solverOptions.solver match {
      case UseDBCFWSolver => new DBCFWSolverTuned[Vector[Double], MultiClassLabel](
        repartData,
        this,
        solverOptions,
        miniBatchEnabled = false).optimize()
      case UseSSGSolver => (new SSGSolver[Vector[Double], MultiClassLabel](
        repartData.collect(),
        this,
        solverOptions
        ).optimize(),"")
    }

    println(debugInfo)

    // Dump debug information into a file
    val fw = new FileWriter(solverOptions.debugInfoPath)
    // Write the current parameters being used
    fw.write(solverOptions.toString())
    fw.write("\n")

    // Write spark-specific parameters
    fw.write(SolverUtils.getSparkConfString(data.context.getConf))
    fw.write("\n")

    // Write values noted from the run
    fw.write(debugInfo)
    fw.close()

    trainedModel

  }

  /**
   * Classifying with user-submitted functions
   */
  def train(
    data: RDD[LabeledPoint],
    dissolveFunctions: DissolveFunctions[Vector[Double], MultiClassLabel],
    solverOptions: SolverOptions[Vector[Double], MultiClassLabel]): StructSVMModel[Vector[Double], MultiClassLabel] = {

    val numClasses = solverOptions.numClasses
    assert(numClasses > 1)

    val minlabel = data.map(_.label).min()
    val maxlabel = data.map(_.label).max()
    assert(minlabel == 0, "Label classes need to be 0-indexed")
    assert(maxlabel - minlabel + 1 == numClasses,
      "Number of classes in data do not tally with passed argument")

    // Convert the RDD[LabeledPoint] to RDD[LabeledObject]
    val objectifiedData: RDD[LabeledObject[Vector[Double], MultiClassLabel]] =
      data.map {
        case x: LabeledPoint =>
          new LabeledObject[Vector[Double], MultiClassLabel](MultiClassLabel(x.label, numClasses),
            if (solverOptions.sparse) {
              val features: Vector[Double] = x.features match {
                case features: org.apache.spark.mllib.linalg.SparseVector =>
                  val builder: VectorBuilder[Double] = new VectorBuilder(features.indices, features.values, features.indices.length, x.features.size)
                  builder.toSparseVector
                case _ => SparseVector(x.features.toArray)
              }
              features
            } else
              Vector(x.features.toArray))
      }

    val repartData =
      if (solverOptions.enableManualPartitionSize)
        objectifiedData.repartition(solverOptions.NUM_PART)
      else
        objectifiedData

    println(solverOptions)

    //choose optimizer
    val (trainedModel,debugInfo) = solverOptions.solver match {
      case UseDBCFWSolver => new DBCFWSolverTuned[Vector[Double], MultiClassLabel](
        repartData,
        dissolveFunctions,
        solverOptions,
        miniBatchEnabled = false).optimize()
      case UseSSGSolver => (new SSGSolver[Vector[Double], MultiClassLabel](
        repartData.collect(),
        dissolveFunctions,
        solverOptions
        ).optimize(),"")
    }

    // Dump debug information into a file
    val fw = new FileWriter(solverOptions.debugInfoPath)
    // Write the current parameters being used
    fw.write(solverOptions.toString())
    fw.write("\n")

    // Write spark-specific parameters
    fw.write(SolverUtils.getSparkConfString(data.context.getConf))
    fw.write("\n")

    // Write values noted from the run
    fw.write(debugInfo)
    fw.close()

    println(debugInfo)

    trainedModel

  }
}


text:
package com.foc.plugin;

import com.foc.desc.FocDesc;

public abstract class AbstractFocDescPlugIn implements IFocDescPlugIn {

	private FocDesc focDesc = null;

	public FocDesc getFocDesc(){
		return focDesc;
	}

	public void setFocDesc(FocDesc focDesc){
		this.focDesc = focDesc;
	}

	@Override
	public void dispose() {
		focDesc = null;
	}

	@Override
	public void afterConstruction(FocDesc focDesc){
	}
}


text:
from ..serialize import b2h_rev
from ..serialize.bitcoin_streamer import parse_struct, stream_struct

ITEM_TYPE_TX, ITEM_TYPE_BLOCK = (1, 2)

class InvItem(object):
    def __init__(self, item_type, data):
        self.item_type = item_type
        self.data = data

    def __str__(self):
        INV_TYPES = [None, "Tx", "Block"]
        return "%s [%s]" % (INV_TYPES[self.item_type], b2h_rev(self.data))

    def __repr__(self):
        return str(self)

    def __hash__(self):
        return hash(self.data)

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.item_type == other.item_type and self.data == other.data
        else:
            return False

    def __ne__(self, other):
        return not self.__eq__(other)

    def stream(self, f):
        stream_struct("L#", f, self.item_type, self.data)

    @classmethod
    def parse(self, f):
        return self(*parse_struct("L#", f))