text:
package org.drools.beliefs.bayes;

import java.util.Arrays;
import java.util.List;

public class PotentialMultiplier {
    //    BayesVariable   var;
    int             varPos;
    int[]           parentVarPos;
    double[][]      varPotential;
    int[]           parentIndexMultipliers;
    int             varProbabilityTableRow;
    BayesVariable[] vars;
    int[]           multipliers;
    int[]           path;

    double[] trgPotentials;
    int      trgPotentialIndex;

    public PotentialMultiplier(double[][] varPotential, int varPos, int[] parentVarPos, int[] parentIndexMultipliers,
                               BayesVariable[] vars, int[] multipliers, double[] trgPotentials) {
        this.varPotential = varPotential;
        this.varPos = varPos;
        this.parentVarPos = parentVarPos;
        this.parentIndexMultipliers = parentIndexMultipliers;
        this.vars = vars;
        this.multipliers = multipliers;
        this.path = new int[vars.length];;
        this.trgPotentials = trgPotentials;
    }

    public static int createNumberOfStates(List<BayesVariable> vars) {
        int numberOfStates = 1;
        for (int i = 0; i < vars.size(); i++) {
            BayesVariable var = vars.get(i);
            numberOfStates *= var.getOutcomes().length;
        }
        return numberOfStates;
    }

    public static int createNumberOfStates(BayesVariable[] vars) {
        return createNumberOfStates(Arrays.asList(vars));
    }

    public static int[] createIndexMultipliers(BayesVariable[] vars, int numberOfStates) {
        if ( vars.length == 0 ) {
            // length only == 0 during unit testing
            return new int[0];
        }

        int[] indexMultipliers = new int[vars.length];
        indexMultipliers[0] = numberOfStates / vars[0].getOutcomes().length;
        for (int i = 1; i < vars.length; i++) {
            indexMultipliers[i] = indexMultipliers[i - 1] / vars[i].getOutcomes().length;
        }
        return indexMultipliers;
    }

    public static int[] createSubsetVarPos(BayesVariable[] vars, BayesVariable[] subset) {
        int[] parentVarPos = new int[subset.length];
        int currentVar = 0;
        for ( int i = 0; i < vars.length && currentVar < subset.length; i++ ) {
            if ( vars[i] == subset[currentVar] ) {
                parentVarPos[currentVar++] = i;
            }
        }
        return parentVarPos;
    }

    public void multiple() {
        varProbabilityTableRow = 0;
        trgPotentialIndex = 0;
        multiple(0, 0);
    }

    public void multiple(int currentVar, int parentKeyPos) {
        // This performs a depth first recursion of the clique's variables.
        // It uses the intrinsic ordering between data structures.
        // The iteration maps the var ptable value(double[][]) to the clique's potential value(double[])
        // The current var state is tracked in a path, and the parent's too (if parents exist).
        // The ptable row is mapped using the parentIndexMultiplier, which is updated each time a parent is entered exited

        int numberOfOutcomes = vars[currentVar].getOutcomes().length;

        boolean isParent = false;
        int nextParentKeyPos = parentKeyPos;
        if (parentVarPos.length > 0 && parentKeyPos < parentVarPos.length &&  parentVarPos[parentKeyPos] == currentVar) {
            nextParentKeyPos++;
            isParent = true;
        }

        for (int j = 0; j < numberOfOutcomes; j++) {
            path[currentVar] = j;

            if (currentVar < vars.length - 1) {
                multiple(currentVar + 1, nextParentKeyPos);
            } else {
                trgPotentials[trgPotentialIndex++] *= varPotential[varProbabilityTableRow][path[varPos]];
            }
            if ( isParent ) {
                varProbabilityTableRow += parentIndexMultipliers[parentKeyPos];
            }
        }
        if ( isParent ) {
            varProbabilityTableRow -= (parentIndexMultipliers[parentKeyPos] * numberOfOutcomes );
        }
    }

    public static int[] indexToKey(int index, int[] indexMultipliers) {
        int[] stateIndex = new int[indexMultipliers.length + 1];

        int offset = 0;
        for (int i = 0; i < indexMultipliers.length; i++) {
            int multiplier = indexMultipliers[i];
            stateIndex[i] = Math.abs((index - offset) / multiplier);
            offset += multiplier * stateIndex[i];
        }
        stateIndex[indexMultipliers.length] = index - offset;

        return stateIndex;
    }

    public static int keyToIndex(int[] key, int[] indexMultipliers) {
        int index = 0;
        for (int i = 0; i < indexMultipliers.length; i++) {
            int value = key[i];
            index += value * indexMultipliers[i];
        }
        index += key[key.length - 1];
        return index;
    }
}


text:
<component name="libraryTable">
  <library name="signalr-client-sdk-android">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/libs/signalr-client-sdk-android.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>

redpajama_set_name: RedPajamaGithub


text: export { WifiOff24 as default } from "../../";


text:
<?php

namespace JsonDb\Operation;

use JsonDb\Query\QueryAny;
use JsonDb\Query\QueryInterface;

class Delete implements OperationInterface
{
    protected $query;

    public function __construct(QueryInterface $query = null)
    {
        if(is_null($query)){
            $query = new QueryAny(true); // match all
        }
        $this->query = $query;
    }

    /**
     * {@inheritdoc}
     */
    public function execute(array &$collection)
    {
        $copy = $collection;
        foreach($copy as $key => $document){
            if($this->query->match($document)){
                unset($collection[$key]);
            }
        }
    }
}


text:
package com.google.android.exoplayer.demo.ServerAnnotation;

/**
 * Created by chavez on 7/7/15.
 */
//import info.androidhive.camerafileupload.AndroidMultiPartEntity.ProgressListener;

import java.io.File;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.google.android.exoplayer.demo.R;

public class UploadActivity extends Activity {
    // LogCat tag
    private static final String TAG = "Upload Activity";

    private ProgressBar progressBar;
    private String filePath = null;
    private String filename = null;
    private TextView txtPercentage;
    private ImageView imgPreview;
    private VideoView vidPreview;
    private Button btnUpload;
    long totalSize = 0;
    public String video_id;
    public String video_name;
    public String video_currentTimeMS;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);

        txtPercentage = (TextView) findViewById(R.id.txtPercentage);
        btnUpload = (Button) findViewById(R.id.btnUpload);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        imgPreview = (ImageView) findViewById(R.id.imgPreview);
        vidPreview = (VideoView) findViewById(R.id.videoPreview);

        //todo get this work again
        //getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1f2649")));
        // Changing action bar background color
 /*       getActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor(getResources().getString(
                        R.color.action_bar))));*/

        // Receiving the data from previous activity
        Intent i = getIntent();

        // image or video path that is captured in previous activity
        filePath = i.getStringExtra("filePath");
        video_id = i.getStringExtra("video_id");
        video_name = i.getStringExtra("video_name");
        video_currentTimeMS  =  i.getStringExtra("video_currentTimeMS");

        Log.d("StringExtras", video_currentTimeMS + ", " + video_id);

        //Filename miliseconds of Image
        filename = i.getStringExtra("filename");

        // boolean flag to identify the media type, image or video
        boolean isImage = i.getBooleanExtra("isImage", true);

        if (filePath != null) {
            // Displaying the image or video on the screen
            previewMedia(isImage);
        } else {
            Toast.makeText(getApplicationContext(),
                    "Sorry, file path is missing!", Toast.LENGTH_LONG).show();
        }

        btnUpload.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // uploading the file to server
                new UploadFileToServer().execute();
            }
        });

    }

    /**
     * Displaying captured image/video on the screen
     * */
    private void previewMedia(boolean isImage) {
        // Checking whether captured media is image or video
        if (isImage) {
            imgPreview.setVisibility(View.VISIBLE);
            vidPreview.setVisibility(View.GONE);
            // bimatp factory
            BitmapFactory.Options options = new BitmapFactory.Options();

            // down sizing image as it throws OutOfMemory Exception for larger
            // images
            options.inSampleSize = 8;

            final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

            imgPreview.setImageBitmap(bitmap);
        } else {
            imgPreview.setVisibility(View.GONE);
            vidPreview.setVisibility(View.VISIBLE);
            vidPreview.setVideoPath(filePath);
            // start playing
            vidPreview.start();
        }
    }

    /**
     * Uploading the file to server
     * */
    private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
        @Override
        protected void onPreExecute() {
            // setting progress bar to zero
            progressBar.setProgress(0);
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            // Making progress bar visible
            progressBar.setVisibility(View.VISIBLE);

            // updating progress bar value
            progressBar.setProgress(progress[0]);

            // updating percentage value
            txtPercentage.setText(String.valueOf(progress[0]) + "%");
        }

        @Override
        protected String doInBackground(Void... params) {
            return uploadFile();
        }

        @SuppressWarnings("deprecation")
        private String uploadFile() {
            String responseString = null;

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);

            try {
                AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                        new AndroidMultiPartEntity.ProgressListener() {

                            @Override
                            public void transferred(long num) {
                                publishProgress((int) ((num / (float) totalSize) * 100));
                            }
                        });

                File sourceFile = new File(filePath);

                // Adding file data to http body
                entity.addPart("image", new FileBody(sourceFile));

                // Extra parameters if you want to pass to server
                entity.addPart("website",
                        new StringBody("www.androidhive.info"));
                entity.addPart("email", new StringBody("abc@gmail.com"));

                entity.addPart("filename", new StringBody(filename + ".png"));
                entity.addPart("video_id",  new StringBody(video_id));
                entity.addPart("video_currentTimeMS",  new StringBody(video_currentTimeMS));

                totalSize = entity.getContentLength();
                httppost.setEntity(entity);

                // Making server call
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity r_entity = response.getEntity();

                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    // Server response
                    responseString = EntityUtils.toString(r_entity);
                } else {
                    responseString = "Error occurred! Http Status Code: "
                            + statusCode;
                }

            } catch (ClientProtocolException e) {
                responseString = e.toString();
            } catch (IOException e) {
                responseString = e.toString();
            }

            return responseString;

        }

        @Override
        protected void onPostExecute(String result) {
            Log.e(TAG, "Response from server: " + result);

            // showing the server response in an alert dialog
            showAlert(result);

            super.onPostExecute(result);
        }

    }

    /**
     * Method to show alert dialog
     * */
    private void showAlert(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message).setTitle("Response from Servers")
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // do nothing
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

}


text:
// @flow

import { type Dispatch } from 'redux';

import {
    conferenceWillJoin,
    getCurrentConference,
    sendLocalParticipant,
    setPassword
} from '../base/conference';
import { getLocalParticipant } from '../base/participants';
import { onLobbyChatInitialized, removeLobbyChatParticipant, sendMessage } from '../chat/actions.any';
import { LOBBY_CHAT_MESSAGE } from '../chat/constants';
import { handleLobbyMessageReceived } from '../chat/middleware';
import { hideNotification, LOBBY_NOTIFICATION_ID } from '../notifications';
import { showNotification } from '../notifications/actions';

import {
    KNOCKING_PARTICIPANT_ARRIVED_OR_UPDATED,
    KNOCKING_PARTICIPANT_LEFT,
    SET_KNOCKING_STATE,
    SET_LOBBY_MODE_ENABLED,
    SET_PASSWORD_JOIN_FAILED,
    SET_LOBBY_VISIBILITY,
    SET_LOBBY_PARTICIPANT_CHAT_STATE,
    REMOVE_LOBBY_CHAT_WITH_MODERATOR
} from './actionTypes';
import { LOBBY_CHAT_INITIALIZED, MODERATOR_IN_CHAT_WITH_LEFT } from './constants';
import { getKnockingParticipants, getLobbyEnabled } from './functions';

/**
 * Tries to join with a preset password.
 *
 * @param {string} password - The password to join with.
 * @returns {Function}
 */
export function joinWithPassword(password: string) {
    return async (dispatch: Dispatch<any>, getState: Function) => {
        const conference = getCurrentConference(getState);

        dispatch(setPassword(conference, conference.join, password));
    };
}

/**
 * Action to be dispatched when a knocking poarticipant leaves before any response.
 *
 * @param {string} id - The ID of the participant.
 * @returns {{
 *     id: string,
 *     type: KNOCKING_PARTICIPANT_LEFT
 * }}
 */
export function knockingParticipantLeft(id: string) {
    return {
        id,
        type: KNOCKING_PARTICIPANT_LEFT
    };
}

/**
 * Action to be executed when a participant starts knocking or an already knocking participant gets updated.
 *
 * @param {Object} participant - The knocking participant.
 * @returns {{
 *     participant: Object,
 *     type: KNOCKING_PARTICIPANT_ARRIVED_OR_UPDATED
 * }}
 */
export function participantIsKnockingOrUpdated(participant: Object) {
    return {
        participant,
        type: KNOCKING_PARTICIPANT_ARRIVED_OR_UPDATED
    };
}

/**
 * Handles a knocking participant and dismisses the notification.
 *
 * @param {string} id - The id of the knocking participant.
 * @param {boolean} approved - True if the participant is approved, false otherwise.
 * @returns {Function}
 */
export function answerKnockingParticipant(id: string, approved: boolean) {
    return async (dispatch: Dispatch<any>) => {
        dispatch(setKnockingParticipantApproval(id, approved));
        dispatch(hideNotification(LOBBY_NOTIFICATION_ID));
    };
}

/**
 * Approves (lets in) or rejects a knocking participant.
 *
 * @param {string} id - The id of the knocking participant.
 * @param {boolean} approved - True if the participant is approved, false otherwise.
 * @returns {Function}
 */
export function setKnockingParticipantApproval(id: string, approved: boolean) {
    return async (dispatch: Dispatch<any>, getState: Function) => {
        const conference = getCurrentConference(getState);

        if (conference) {
            if (approved) {
                conference.lobbyApproveAccess(id);
            } else {
                conference.lobbyDenyAccess(id);
            }
        }
    };
}

/**
 * Action used to admit multiple participants in the conference.
 *
 * @param {Array<Object>} participants - A list of knocking participants.
 * @returns {void}
 */
export function admitMultiple(participants: Array<Object>) {
    return (dispatch: Function, getState: Function) => {
        const conference = getCurrentConference(getState);

        participants.forEach(p => {
            conference.lobbyApproveAccess(p.id);
        });
    };
}

/**
 * Approves the request of a knocking participant to join the meeting.
 *
 * @param {string} id - The id of the knocking participant.
 * @returns {Function}
 */
export function approveKnockingParticipant(id: string) {
    return (dispatch: Dispatch<any>, getState: Function) => {
        const conference = getCurrentConference(getState);

        conference && conference.lobbyApproveAccess(id);
    };
}

/**
 * Denies the request of a knocking participant to join the meeting.
 *
 * @param {string} id - The id of the knocking participant.
 * @returns {Function}
 */
export function rejectKnockingParticipant(id: string) {
    return (dispatch: Dispatch<any>, getState: Function) => {
        const conference = getCurrentConference(getState);

        conference && conference.lobbyDenyAccess(id);
    };
}

/**
 * Action to set the knocking state of the participant.
 *
 * @param {boolean} knocking - The new state.
 * @returns {{
 *     state: boolean,
 *     type: SET_KNOCKING_STATE
 * }}
 */
export function setKnockingState(knocking: boolean) {
    return {
        knocking,
        type: SET_KNOCKING_STATE
    };
}

/**
 * Action to set the new state of the lobby mode.
 *
 * @param {boolean} enabled - The new state to set.
 * @returns {{
 *     enabled: boolean,
 *     type: SET_LOBBY_MODE_ENABLED
 * }}
 */
export function setLobbyModeEnabled(enabled: boolean) {
    return {
        enabled,
        type: SET_LOBBY_MODE_ENABLED
    };
}

/**
 * Action to be dispatched when we failed to join with a password.
 *
 * @param {boolean} failed - True of recent password join failed.
 * @returns {{
 *     failed: boolean,
 *     type: SET_PASSWORD_JOIN_FAILED
 * }}
 */
export function setPasswordJoinFailed(failed: boolean) {
    return {
        failed,
        type: SET_PASSWORD_JOIN_FAILED
    };
}

/**
 * Starts knocking and waiting for approval.
 *
 * @returns {Function}
 */
export function startKnocking() {
    return async (dispatch: Dispatch<any>, getState: Function) => {
        const state = getState();
        const { membersOnly } = state['features/base/conference'];
        const localParticipant = getLocalParticipant(state);

        dispatch(conferenceWillJoin(membersOnly));

        // We need to update the conference object with the current display name, if approved
        // we want to send that display name, it was not updated in case when pre-join is disabled
        sendLocalParticipant(state, membersOnly);

        membersOnly.joinLobby(localParticipant.name, localParticipant.email);
        dispatch(setLobbyMessageListener());
        dispatch(setKnockingState(true));
    };
}

/**
 * Action to toggle lobby mode on or off.
 *
 * @param {boolean} enabled - The desired (new) state of the lobby mode.
 * @returns {Function}
 */
export function toggleLobbyMode(enabled: boolean) {
    return async (dispatch: Dispatch<any>, getState: Function) => {
        const conference = getCurrentConference(getState);

        if (enabled) {
            conference.enableLobby();
        } else {
            conference.disableLobby();
        }
    };
}

/**
 * Action to open the lobby screen.
 *
 * @returns {openDialog}
 */
export function openLobbyScreen() {
    return {
        type: SET_LOBBY_VISIBILITY,
        visible: true
    };
}

/**
 * Action to hide the lobby screen.
 *
 * @returns {hideDialog}
 */
export function hideLobbyScreen() {
    return {
        type: SET_LOBBY_VISIBILITY,
        visible: false
    };
}

/**
 * Action to handle chat initialized in the lobby room.
 *
 * @param {Object} payload - The payload received,
 * contains the information about the two participants
 * that will chat with each other in the lobby room.
 *
 * @returns {Promise<void>}
 */
export function handleLobbyChatInitialized(payload: Object) {
    return async (dispatch: Dispatch<any>, getState: Function) => {
        const state = getState();
        const conference = getCurrentConference(state);

        const id = conference.myLobbyUserId();

        dispatch({
            type: SET_LOBBY_PARTICIPANT_CHAT_STATE,
            participant: payload.attendee,
            moderator: payload.moderator
        });

        dispatch(onLobbyChatInitialized(payload));

        const attendeeIsKnocking = getKnockingParticipants(state).some(p => p.id === payload.attendee.id);

        if (attendeeIsKnocking && conference.getRole() === 'moderator' && payload.moderator.id !== id) {
            dispatch(showNotification({
                titleKey: 'lobby.lobbyChatStartedNotification',
                titleArguments: {
                    moderator: payload.moderator.name,
                    attendee: payload.attendee.name
                }
            }));
        }
    };
}

/**
 * Action to send message to the moderator.
 *
 * @param {string} message - The message to be sent.
 *
 * @returns {Promise<void>}
 */
export function onSendMessage(message: string) {
    return async (dispatch: Dispatch<any>) => {
        dispatch(sendMessage(message));
    };
}

/**
 * Action to send lobby message to every participant. Only allowed for moderators.
 *
 * @param {Object} message - The message to be sent.
 *
 * @returns {Promise<void>}
 */
export function sendLobbyChatMessage(message: Object) {
    return async (dispatch: Dispatch<any>, getState: Function) => {
        const conference = getCurrentConference(getState);

        conference.sendLobbyMessage(message);
    };
}

/**
 * Sets lobby listeners if lobby has been enabled.
 *
 * @returns {Function}
 */
export function maybeSetLobbyChatMessageListener() {
    return async (dispatch: Dispatch<any>, getState: Function) => {
        const state = getState();
        const lobbyEnabled = getLobbyEnabled(state);

        if (lobbyEnabled) {
            dispatch(setLobbyMessageListener());
        }
    };
}

/**
 * Action to handle the event when a moderator leaves during lobby chat.
 *
 * @param {string} participantId - The participant id of the moderator who left.
 * @returns {Function}
 */
export function updateLobbyParticipantOnLeave(participantId: string) {
    return async (dispatch: Dispatch<any>, getState: Function) => {
        const state = getState();
        const { knocking, knockingParticipants } = state['features/lobby'];
        const { lobbyMessageRecipient } = state['features/chat'];
        const { conference } = state['features/base/conference'];

        if (knocking && lobbyMessageRecipient && lobbyMessageRecipient.id === participantId) {
            return dispatch(removeLobbyChatParticipant(true));
        }

        if (!knocking) {
            // inform knocking participant when their moderator leaves
            const participantToNotify = knockingParticipants.find(p => p.chattingWithModerator === participantId);

            if (participantToNotify) {
                conference.sendLobbyMessage({
                    type: MODERATOR_IN_CHAT_WITH_LEFT,
                    moderatorId: participantToNotify.chattingWithModerator
                }, participantToNotify.id);
            }
            dispatch({
                type: REMOVE_LOBBY_CHAT_WITH_MODERATOR,
                moderatorId: participantId
            });
        }
    };
}

/**
 * Handles all messages received in the lobby room.
 *
 * @returns {Function}
 */
export function setLobbyMessageListener() {
    return async (dispatch: Dispatch<any>, getState: Function) => {
        const state = getState();
        const conference = getCurrentConference(state);
        const { enableLobbyChat = true } = state['features/base/config'];

        if (!enableLobbyChat) {
            return;
        }

        conference.addLobbyMessageListener((message: Object, participantId: string) => {
            if (message.type === LOBBY_CHAT_MESSAGE) {
                return dispatch(handleLobbyMessageReceived(message.message, participantId));
            }
            if (message.type === LOBBY_CHAT_INITIALIZED) {
                return dispatch(handleLobbyChatInitialized(message));
            }
            if (message.type === MODERATOR_IN_CHAT_WITH_LEFT) {
                return dispatch(updateLobbyParticipantOnLeave(message.moderatorId));
            }
        });
    };
}


text:
package moe.akagi.chibaproject.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.joanzapata.iconify.IconDrawable;
import com.joanzapata.iconify.fonts.FontAwesomeIcons;
import com.joanzapata.iconify.widget.IconTextView;

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

import de.hdodenhof.circleimageview.CircleImageView;
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.view.CardListView;
import moe.akagi.chibaproject.MyApplication;
import moe.akagi.chibaproject.R;
import moe.akagi.chibaproject.card.EventBriefInfo;
import moe.akagi.chibaproject.datatype.Event;
import moe.akagi.chibaproject.datatype.User;
import moe.akagi.chibaproject.network.API;
import moe.akagi.chibaproject.network.Utils;

/**
 * Created by yunze on 11/30/15.
 */
public class Main extends AppCompatActivity {

    public static final int LOGIN_ACTIVITY = 1;
    public static final int ADD_EVENT_ACTIVITY = 2;
    public static final int FRIEND_ACTIVITY = 3;

    DrawerLayout drawerLayout;
    ActionBarDrawerToggle drawerToggle;
    NavigationView navigation;

    protected int taskCount = 0;
    protected final Object lock = new Object();

    protected List<Card> cards;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_activity_actionbar_menu, menu);
        // Set the icons
        menu.findItem(R.id.main_activity_action_bar_add_event).setIcon(
                new IconDrawable(this, FontAwesomeIcons.fa_plus)
                        .actionBarSize()
        );
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (drawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        switch (item.getItemId()) {
            // to do: add event
            case R.id.main_activity_action_bar_add_event:
                Intent intent = new Intent(Main.this, AddEvent.class);
                startActivityForResult(intent, ADD_EVENT_ACTIVITY);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCollector.addActivity(this);
        initLayout();
        if (MyApplication.user == null) {
            Intent intent = new Intent(Main.this, Login.class);
            startActivityForResult(intent, LOGIN_ACTIVITY);
        } else {
            refreshUserInfo();
            createCardList();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case LOGIN_ACTIVITY:
                if (resultCode == RESULT_OK) {
                    boolean returnedData = data.getBooleanExtra("login_succeed", false);
                    if (returnedData) {
                        createCardList();
                        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
                            drawerLayout.closeDrawer(GravityCompat.START);
                        }
                    }
                    refreshUserInfo();
                }
                break;
            case ADD_EVENT_ACTIVITY:
                if (resultCode == RESULT_OK) {
                    createCardList();
                } else {
                    // Nothing
                }
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    private void createCardList() {

        cards = new ArrayList<Card>();

        User user = MyApplication.user;
        GetPartInEventsTask partInEventsTask = new GetPartInEventsTask();
        partInEventsTask.execute(user.get_id());
    }

    private void refreshCardList() {

        //Set card in the cardView
        CardArrayAdapter mCardArrayAdapter = new CardArrayAdapter(getActivity(),cards);
        CardListView listView = (CardListView) getActivity().findViewById(R.id.event_brief_info_card_list);
        if (listView!=null){
            listView.setAdapter(mCardArrayAdapter);
        }

        //bind click listener on 'more info'
        IconTextView moreInfo = (IconTextView) findViewById(R.id.event_brief_info_more);

    }

    private void initLayout() {
        setContentView(R.layout.main_layout);
        // Add action bar
        Toolbar myToolbar = (Toolbar) findViewById(R.id.main_activity_toolbar);
        setSupportActionBar(myToolbar);

        drawerLayout = (DrawerLayout) findViewById(R.id.main_activity_drawer);
        drawerToggle = new ActionBarDrawerToggle(Main.this, drawerLayout, R.string.open_drawer, R.string.close_drawer);
        drawerLayout.setDrawerListener(drawerToggle);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        navigation = (NavigationView) findViewById(R.id.main_activity_navi);
        navigation.inflateHeaderView(R.layout.main_navi_header);
        navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                int id = item.getItemId();
                switch (id) {
                    case R.id.navi_item_profile:
                        break;
                    case R.id.navi_item_friends:
                        Intent intentFriend = new Intent(Main.this, AllFriends.class);
                        startActivityForResult(intentFriend, FRIEND_ACTIVITY);
                        break;
                    case R.id.navi_item_logout:
                        LogoutTask logoutTask = new LogoutTask();
                        logoutTask.execute(MyApplication.user.get_id());
                        break;
                }
                return false;
            }
        });
    }

    private void refreshUserInfo() {
        CircleImageView naviImage = (CircleImageView) navigation.getHeaderView(0).findViewById(R.id.main_navi_profile_image);
        TextView naviNickname = (TextView) navigation.getHeaderView(0).findViewById(R.id.main_navi_profile_nickname);
        String resString = "profile_image_" + MyApplication.user.getPhone();
        int resId = getResources().getIdentifier(resString, "drawable", getPackageName());
        naviImage.setImageResource(resId);
        naviNickname.setText(MyApplication.user.getNickname());
    }

    private Context getContext() {
        return this;
    }

    private Activity getActivity() {
        return this;
    }

    private class GetPartInEventsTask extends AsyncTask<String, Integer, Integer> {

        public static final int SUCC = 100;
        public static final int FAIL_NOT_LOGGED = 101;
        public static final int FAIL_NOT_FIND_PERSON = 102;
        public static final int FAIL_SOMETHING_WRONG = 110;

        @Override
        protected Integer doInBackground(String... params) {
            String person_id = params[0];
            Object res = API.getPartInEventsByPersonId(person_id);

            if (res instanceof List) {
                User user = MyApplication.user;
                List<String> partInEvents = (List<String>)res;
                user.setPartInEventIds(partInEvents);
                return SUCC;
            } else if (res instanceof Integer) {
                return (Integer)res;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            if (integer == null) return;
            switch (integer) {
                case SUCC:
                    List<String> partInEvents = MyApplication.user.getPartInEventIds();
                    synchronized (lock) {
                        taskCount = 0;
                    }
                    for (String partInEvent : partInEvents) {
                        GetEventTask getEventTask = new GetEventTask();
                        getEventTask.execute(partInEvent);
                    }
                    break;
                case FAIL_NOT_LOGGED:
                    Log.v("GetPartInEvent", "Not logged!");
                    break;
                case FAIL_NOT_FIND_PERSON:
                    Log.v("GetPartInEvent", "Not find person / wrong person_id");
                    break;
                case FAIL_SOMETHING_WRONG:
                    Log.v("GetPartInEvent", "Something wrong in Server");
                    break;
                default:
            }
        }
    }

    private class GetEventTask extends AsyncTask<String, Integer, Object> {

        public static final int SUCC = 100;
        public static final int FAIL_NOT_LOGGED = 101;
        public static final int FAIL_WRONG_ID = 102;
        public static final int FAIL_SOMETHING_WRONG = 110;

        @Override
        protected Object doInBackground(String... params) {

            String event_id = params[0];
            Object res = API.getEventById(event_id);

            if (res instanceof Event) {
                Event event = (Event)res;
                synchronized (lock) {
                    taskCount++;
                }
                return event;
            } else if (res instanceof Integer) {
                return res;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object obj) {
            if (obj != null) {
                if (obj instanceof Event) {
                    Event event = (Event) obj;
                    EventBriefInfo card = new EventBriefInfo(getContext(), event);
                    cards.add(card);
                    synchronized (lock) {
                        Log.v("taskCount", "num = " + taskCount);
                        if (taskCount == MyApplication.user.getPartInEventIds().size()) {
                            refreshCardList();
                        }
                    }
                } else if (obj instanceof Integer) {
                    switch ((Integer)obj) {
                        case SUCC:
                            break;
                        case FAIL_NOT_LOGGED:
                            Log.v("GetEvent", "Not logged!");
                            break;
                        case FAIL_WRONG_ID:
                            Log.v("GetEvent", "Not find event / wrong event_id");
                            break;
                        case FAIL_SOMETHING_WRONG:
                            Log.v("GetEvent", "Something wrong in Server");
                            break;
                    }
                }
            }

        }
    }

    private class LogoutTask extends AsyncTask<String, Integer, Boolean> {

        @Override
        protected Boolean doInBackground(String... params) {
            return API.logOut(params[0]);
        }

        @Override
        protected void onPostExecute(Boolean res) {
            if (res) {
                MyApplication.user = null;
                Intent intentLogout = new Intent(Main.this, Login.class);
                startActivityForResult(intentLogout, LOGIN_ACTIVITY);
                return;
            } else {
                Toast.makeText(Main.this, "注销失败", Toast.LENGTH_SHORT).show();
                return;
            }
        }
    }
}


text:
using System;
using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Threading.Tasks;

using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Internals.Fibers;
using Microsoft.Bot.Connector;

namespace Microsoft.Bot.Builder.ConnectorEx
{
    /// <summary>
    /// The data persisted for ConversationReference that will be consumed for Conversation.ResumeAsync.
    /// </summary>
    public sealed class ResumptionData
    {
        /// <summary>
        /// The locale.
        /// </summary>
        public string Locale { set; get; }

        /// <summary>
        /// The flag indicating if the ServiceUrl is trusted.
        /// </summary>
        public bool IsTrustedServiceUrl { set; get; }
    }

    /// <summary>
    /// The resumption context that is responsible for loading/persisting the <see cref="ResumptionData"/>.
    /// </summary>
    public sealed class ResumptionContext
    {

        /// <summary>
        /// The key for <see cref="ResumptionData"/> in <see cref="botDataBag"/>.
        /// </summary>
        public const string RESUMPTION_CONTEXT_KEY = "ResumptionContext";

        /// <summary>
        /// The <see cref="IBotDataBag"/> used to store the data.
        /// </summary>
        private readonly Lazy<IBotDataBag> botDataBag;

        public ResumptionContext(Func<IBotDataBag> makeBotDataBag)
        {
            SetField.CheckNull(nameof(makeBotDataBag), makeBotDataBag);
            this.botDataBag = new Lazy<IBotDataBag>(() => makeBotDataBag());
        }

        /// <summary>
        /// Load <see cref="ResumptionData"/> from <see cref="botDataBag"/>.
        /// </summary>
        /// <param name="token"> The cancellation token.</param>
        public async Task<ResumptionData> LoadDataAsync(CancellationToken token)
        {
            ResumptionData data;
            botDataBag.Value.TryGetValue(ResumptionContext.RESUMPTION_CONTEXT_KEY, out data);
            return data;
        }

        /// <summary>
        /// Save the <paramref name="data"/> in <see cref="botDataBag"/>.
        /// </summary>
        /// <param name="data"> The <see cref="ResumptionData"/>.</param>
        /// <param name="token"> The cancellation token.</param>
        public async Task SaveDataAsync(ResumptionData data, CancellationToken token)
        {
            var clonedData = new ResumptionData
            {
                Locale = data.Locale,
                IsTrustedServiceUrl = data.IsTrustedServiceUrl
            };

            botDataBag.Value.SetValue(ResumptionContext.RESUMPTION_CONTEXT_KEY, clonedData);
        }
    }

    /// <summary>
    /// Helpers for <see cref="ConversationReference"/>
    /// </summary>
    public sealed class ConversationReferenceHelpers
    {

        /// <summary>
        /// Deserializes the GZip serialized <see cref="ConversationReference"/> using <see cref="Extensions.GZipSerialize(ConversationReference)"/>.
        /// </summary>
        /// <param name="str"> The Base64 encoded string.</param>
        /// <returns> An instance of <see cref="ConversationReference"/></returns>
        public static ConversationReference GZipDeserialize(string str)
        {
            byte[] bytes = Convert.FromBase64String(str);

            using (var stream = new MemoryStream(bytes))
            using (var gz = new GZipStream(stream, CompressionMode.Decompress))
            {
                return (ConversationReference)(new BinaryFormatter().Deserialize(gz));
            }
        }
    }

    public static partial class Extensions
    {
        /// <summary>
        /// Creates a <see cref="ConversationReference"/> from <see cref="IAddress"/>.
        /// </summary>
        /// <param name="address"> The address.</param>
        /// <returns> The <see cref="ConversationReference"/>.</returns>
        public static ConversationReference ToConversationReference(this IAddress address)
        {
            return new ConversationReference
            {
                Bot = new ChannelAccount { Id = address.BotId },
                ChannelId = address.ChannelId,
                User = new ChannelAccount { Id = address.UserId },
                Conversation = new ConversationAccount { Id = address.ConversationId },
                ServiceUrl = address.ServiceUrl
            };
        }

#pragma warning disable CS0618 //disable obsolete warning for this helper.
        /// <summary>
        /// Creates a <see cref="ConversationReference"/> from <see cref="ResumptionCookie"/>.
        /// </summary>
        /// <param name="resumptionCookie"> The resumption cookie.</param>
        /// <returns> The <see cref="ConversationReference"/>.</returns>
        public static ConversationReference ToConversationReference(this ResumptionCookie resumptionCookie)
        {
            return new ConversationReference
            {
                Bot = new ChannelAccount { Id = resumptionCookie.Address.BotId, Name = resumptionCookie.UserName },
                ChannelId = resumptionCookie.Address.ChannelId,
                User = new ChannelAccount { Id = resumptionCookie.Address.UserId, Name = resumptionCookie.UserName },
                Conversation = new ConversationAccount { Id = resumptionCookie.Address.ConversationId, IsGroup = resumptionCookie.IsGroup },
                ServiceUrl = resumptionCookie.Address.ServiceUrl
            };
        }
#pragma warning restore CS0618

        /// <summary>
        /// Creates a <see cref="ConversationReference"/> from <see cref="IActivity"/>.
        /// </summary>
        /// <param name="activity"> The <see cref="IActivity"/>  posted to bot.</param>
        /// <returns> The <see cref="ConversationReference"/>.</returns>
        public static ConversationReference ToConversationReference(this IActivity activity)
        {
            return new ConversationReference
            {
                Bot = new ChannelAccount { Id = activity.Recipient.Id, Name = activity.Recipient.Name },
                ChannelId = activity.ChannelId,
                User = new ChannelAccount { Id = activity.From.Id, Name = activity.From.Name },
                Conversation = new ConversationAccount { Id = activity.Conversation.Id, IsGroup = activity.Conversation.IsGroup, Name = activity.Conversation.Name },
                ServiceUrl = activity.ServiceUrl
            };
        }

        /// <summary>
        /// Binary serializes <see cref="ConversationReference"/> using <see cref="GZipStream"/>.
        /// </summary>
        /// <param name="conversationReference"> The resumption cookie.</param>
        /// <returns> A Base64 encoded string.</returns>
        public static string GZipSerialize(this ConversationReference conversationReference)
        {
            using (var cmpStream = new MemoryStream())
            using (var stream = new GZipStream(cmpStream, CompressionMode.Compress))
            {
                new BinaryFormatter().Serialize(stream, conversationReference);
                stream.Close();
                return Convert.ToBase64String(cmpStream.ToArray());
            }
        }
    }
}


text:
A similar PR may already be submitted!
Please search among the [pull requests](../../../pulls) before creating one.

Thanks for submitting a pull request! Please provide enough information so that others can review your pull request:

For more information, see the [CONTRIBUTING](CONTRIBUTING.md) guide.

**Summary**

<!-- Summary of the PR -->

This PR fixes/implements the following **bugs/features**

* [ ] Bug 1
* [ ] Bug 2
* [ ] Feature 1
* [ ] Feature 2
* [ ] Breaking changes

<!-- You can skip this if you're fixing a typo or adding an app to the Showcase. -->

Explain the **motivation** for making this change. What existing problem does the pull request solve?

<!-- Example: When "Adding a function to do X", explain why it is necessary to have a way to do X. -->

**Test plan (required)**

Demonstrate the code is solid. Example: The exact commands you ran and their output.

<!-- Make sure tests pass on both Travis and AppVeyor. -->

**Closing issues**

<!-- Put `closes #XXXX` in your comment to auto-close the issue that your PR fixes (if such). -->
Fixes #

**Checklist**

- [ ] Have you followed the guidelines in our [CONTRIBUTING](CONTRIBUTING.md) guide?
- [ ] Have you fmt your code locally prior to submission (`orbit run fmt`)?
- [ ] Have you written new tests for your core changes, as applicable?
- [ ] Have you successfully ran tests with your changes locally (`orbit run ci`)?
- [ ] I have squashed any insignificant commits
- [ ] This change has comments for package types, values, functions, and non-obvious lines of code


text:
import os
import contextlib

from .. import documents
from .. import results
from .. import lists
from .xmlparser import node_types

def read_document_xml_element(element, numbering=None, content_types=None, relationships=None, docx_file=None):
    reader = _create_reader(numbering=numbering, content_types=content_types, relationships=relationships, docx_file=docx_file)
    return reader(element)

def _create_reader(numbering, content_types, relationships, docx_file):
    _handlers = {}
    _ignored_elements = set([
        "w:bookmarkStart",
        "w:bookmarkEnd",
        "w:sectPr",
        "w:proofErr",
        "w:lastRenderedPageBreak",
        "w:commentRangeStart",
        "w:commentRangeEnd",
        "w:commentReference",
        "w:del",
        "w:pPr",
        "w:rPr",
    ])

    def handler(name):
        def add(func):
            _handlers[name] = func
            return func

        return add

    @handler("w:t")
    def text(element):
        return results.success(documents.Text(_inner_text(element)))

    @handler("w:r")
    def run(element):
        properties = element.find_child_or_null("w:rPr")
        style_name = properties \
            .find_child_or_null("w:rStyle") \
            .attributes.get("w:val")
        is_bold = properties.find_child("w:b")
        is_italic = properties.find_child("w:i")

        return _read_xml_elements(element.children) \
            .map(lambda children: documents.run(
                children=children,
                style_name=style_name,
                is_bold=is_bold,
                is_italic=is_italic,
            ))

    @handler("w:p")
    def paragraph(element):
        properties = element.find_child_or_null("w:pPr")
        style_name = properties \
            .find_child_or_null("w:pStyle") \
            .attributes.get("w:val")
        numbering_properties = properties.find_child("w:numPr")
        if numbering_properties is None:
            numbering = None
        else:
            numbering = _read_numbering_properties(numbering_properties)

        return _read_xml_elements(element.children) \
            .map(lambda children: documents.paragraph(
                children=children,
                style_name=style_name,
                numbering=numbering,
            ))

    def _read_numbering_properties(element):
        num_id = element.find_child("w:numId").attributes["w:val"]
        level_index = element.find_child("w:ilvl").attributes["w:val"]
        return numbering.find_level(num_id, level_index)

    @handler("w:body")
    def body(element):
        return _read_xml_elements(element.children)

    @handler("w:document")
    def document(element):
        body_element = _find_child(element, "w:body")
        return _read_xml_elements(body_element.children) \
            .map(documents.document)

    @handler("w:tab")
    def tab(element):
        return results.success(documents.tab())

    @handler("w:ins")
    @handler("w:smartTag")
    @handler("w:drawing")
    def read_child_elements(element):
        return _read_xml_elements(element.children)

    @handler("w:hyperlink")
    def hyperlink(element):
        relationship_id = element.attributes.get("r:id")
        children_result = _read_xml_elements(element.children)
        if relationship_id is None:
            return children_result
        else:
            href = relationships[relationship_id].target
            return children_result.map(lambda children: documents.hyperlink(href, children))

    @handler("wp:inline")
    @handler("wp:anchor")
    def inline(element):
        alt_text = element.find_child_or_null("wp:docPr").attributes.get("descr")
        blips = element.find_children("a:graphic") \
            .find_children("a:graphicData") \
            .find_children("pic:pic") \
            .find_children("pic:blipFill") \
            .find_children("a:blip")
        return _read_blips(blips, alt_text)

    def _read_blips(blips, alt_text):
        return results.combine(map(lambda blip: _read_blip(blip, alt_text), blips))

    def _read_blip(element, alt_text):
        relationship_id = element.attributes["r:embed"]
        image_path = os.path.join("word", relationships[relationship_id].target)
        content_type = content_types.find_content_type(image_path)

        def open_image():
            image_file = docx_file.open(image_path)
            if hasattr(image_file, "__exit__"):
                return image_file
            else:
                return contextlib.closing(image_file)

        image = documents.image(alt_text=alt_text, content_type=content_type, open=open_image)
        return results.success(image)

    def read(element):
        handler = _handlers.get(element.name)
        if handler is None:
            if element.name not in _ignored_elements:
                warning = results.warning("An unrecognised element was ignored: {0}".format(element.name))
                return results.Result(None, [warning])
            else:
                return results.success(None)
        else:
            return handler(element)

    def _read_xml_elements(elements):
        return results.combine(map(read, elements)) \
            .map(lambda values: lists.collect(values))

    return read

def _find(predicate, iterable):
    for item in iterable:
        if predicate(item):
            return item

def _find_child(element, name):
    return _find(lambda child: child.name == name, element.children)

def _inner_text(node):
    if node.node_type == node_types.text:
        return node.value
    else:
        return "".join(_inner_text(child) for child in node.children)


text:
#ifndef FCGIEV__BASE_H
#define FCGIEV__BASE_H

#include <Python.h>
#include <pyconfig.h>
#include <structmember.h>
#include <stdint.h>
#include <assert.h>

/* Types */
#if (PY_VERSION_HEX < 0x02050000)
  typedef inquiry lenfunc;
  typedef int     Py_ssize_t;
  #define PY_SSIZE_FMT "%d"
#else
  #define PY_SSIZE_FMT "%zd"
#endif
typedef uint8_t byte;

/* Python 3 is on the horizon... (currently only used by ) */
#if (PY_VERSION_HEX < 0x02060000)  /* really: before python trunk r63675 */
  /* These #defines map to their equivalent on earlier python versions. */
  #define PyBytes_FromStringAndSize   PyString_FromStringAndSize
  #define PyBytes_FromString          PyString_FromString
  #define PyBytes_AsStringAndSize     PyString_AsStringAndSize
  #define PyBytes_Check               PyString_Check
  #define PyBytes_GET_SIZE            PyString_GET_SIZE
  #define PyBytes_AS_STRING           PyString_AS_STRING
  #define PyBytes_AsString            PyString_AsString
  #define PyBytes_FromFormat          PyString_FromFormat
  #define PyBytes_Size                PyString_Size
  #define PyBytes_ConcatAndDel        PyString_ConcatAndDel
  #define PyBytes_Concat              PyString_Concat
  #define _PyBytes_Resize             _PyString_Resize
#endif
#if (PY_VERSION_HEX >= 0x03000000)
  #define NUMBER_Check    PyLong_Check
  #define NUMBER_AsLong   PyLong_AsLong
  #define NUMBER_FromLong PyLong_FromLong
#else
  #define NUMBER_Check    PyInt_Check
  #define NUMBER_AsLong   PyInt_AsLong
  #define NUMBER_FromLong PyInt_FromLong
#endif

/* Assertion macros */
#ifndef NDEBUG
#define AZ(foo) assert((foo) == 0)
#define AN(foo) assert((foo) != 0)
#else
#define AZ(foo) (foo)
#define AN(foo) (foo)
#endif

/* Get minimum value */
#ifndef min
  #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
#endif
#ifndef max
  #define max(X, Y)  ((X) > (Y) ? (X) : (Y))
#endif

/* Align a value */
#define FE_ALIGN(value, size) (((value)+(size)-1)&~((size)-1))
/* Align to memory, counted in bytes */
#if __LP64__
  #define FE_ALIGN_M(value) FE_ALIGN(value, 8)
#else
  #define FE_ALIGN_M(value) FE_ALIGN(value, 4)
#endif

/* Module identifier, used in logging */
#define MOD_IDENT "fcgiev"

/* Converting MY_MACRO to "<value of MY_MACRO>" i.e. QUOTE(PY_MAJOR_VERSION) -> "2" */
#define _QUOTE(x) #x
#define QUOTE(x) _QUOTE(x)

/* Replace a PyObject while counting references */
#define REPLACE_OBJ(destination, new_value, type) \
  do { \
    type *__old_ ## type ## __LINE__ = (type *)(destination); \
    (destination) = (type *)(new_value); \
    Py_XINCREF(destination); \
    Py_XDECREF(__old_ ## type ## __LINE__); \
  } while (0)

#define REPLACE_PyObject(dst, value) REPLACE_OBJ(dst, value, PyObject)

#ifndef Py_TYPE
  #define Py_TYPE(ob)	(((PyObject*)(ob))->ob_type)
#endif

/* Ensure a lazy instance variable is available */
#define ENSURE_BY_GETTER(direct, getter, ...) \
  if (direct == NULL) {\
    PyObject *tmp = getter;\
    if (tmp == NULL) {\
      __VA_ARGS__ ;\
    } else {\
      Py_DECREF(tmp);\
    }\
  }

/* Get and set arbitrary attributes of objects.
 * This is the only way to set/get Type/Class properties.
 * Uses the interal function PyObject **_PyObject_GetDictPtr(PyObject *);
 * Returns PyObject * (NULL if an exception was raised)
 */
#define PYTC_PyObject_GET(PyObject_ptr_type, char_ptr_name) \
  PyDict_GetItemString(*_PyObject_GetDictPtr((PyObject *)PyObject_ptr_type), char_ptr_name)

/* Returns 0 on success, -1 on failure. */
#define PYTC_PyObject_SET(PyObject_ptr_type, char_ptr_name, PyObject_ptr_value) \
  PyDict_SetItemString(*_PyObject_GetDictPtr((PyObject *)PyObject_ptr_type), char_ptr_name,\
  (PyObject *)PyObject_ptr_value)

/* instanceof(obj, (bytes, str, unicode) */
#define PYTC_STRING_CHECK(obj) (PyBytes_Check(obj) || PyUnicode_Check(obj))

/* Set IOError with errno and filename info. Return NULL */
#define PyErr_SET_FROM_ERRNO   PyErr_SetFromErrnoWithFilename(PyExc_IOError, __FILE__)

/* Log to stderr */
#define log_error(fmt, ...) fprintf(stderr, MOD_IDENT " [%d] ERROR %s:%d: " fmt "\n", \
  getpid(), __FILE__, __LINE__, ##__VA_ARGS__)

/* Used for temporary debugging */
#define _DUMP_REFCOUNT(o) log_error("*** %s: %ld", #o, (o) ? (long int)(o)->ob_refcnt : 0)

/* Log to stderr, but only in debug builds */
#if DEBUG
  #define log_debug(fmt, ...) fprintf(stderr, MOD_IDENT " [%d] DEBUG %s:%d: " fmt "\n",\
    getpid(), __FILE__, __LINE__, ##__VA_ARGS__)
  #define IFDEBUG(x) x
  #define assert_refcount(o, count_test) \
    do { \
      if (!((o)->ob_refcnt count_test)){ \
        log_debug("assert_refcount(" PY_SSIZE_FMT ", %s)", (Py_ssize_t)(o)->ob_refcnt, #count_test);\
      }\
      assert((o)->ob_refcnt count_test); \
    } while (0)
  #define DUMP_REFCOUNT(o) log_debug("*** %s: " PY_SSIZE_FMT, #o, (o) ? (Py_ssize_t)(o)->ob_refcnt : 0)
  #define DUMP_REPR(o) \
    do { PyObject *repr = PyObject_Repr((PyObject *)(o));\
      if (repr) {\
        log_debug("repr(%s) = %s", #o, PyBytes_AS_STRING(repr));\
        Py_DECREF(repr);\
      } else {\
        log_debug("repr(%s) = <NULL>", #o);\
      }\
    } while (0)
  #define DUMPBYTES(p, sz) \
    do {\
      PyObject *s = PyString_FromStringAndSize(p, sz);\
      PyObject *repr = PyObject_Repr((PyObject *)s);\
      Py_DECREF(s);\
      log_debug("DUMPBYTES(%p) => %s", (p), PyBytes_AS_STRING(repr));\
      Py_DECREF(repr);\
    } while (0)
#else
  #define log_debug(fmt, ...) ((void)0)
  #define assert_refcount(o, count_test)
  #define IFDEBUG(x)
  #define DUMP_REFCOUNT(o)
  #define DUMP_REPR(o)
#endif

#if FCGIEV_TRACE
  #define log_trace(fmt, ...) fprintf(stderr, MOD_IDENT " [%d] TRACE %s:%d in %s " fmt "\n", \
    getpid(), __FILE__, __LINE__, __FUNCTION__, ##__VA_ARGS__)
  #define IFTRACE(x) x
#else
  #define log_trace(fmt, ...) ((void)0)
  #define IFTRACE(x)
#endif

#endif


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>HShapeLayout (Javadocs: HYPE)</title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

hype.extended.layout

Class HShapeLayout

java.lang.Object

hype.extended.layout.HShapeLayout

All Implemented Interfaces:

HLayout

public class HShapeLayout
extends java.lang.Object
implements HLayout

Constructor Summary

Constructors

Constructor and Description

HShapeLayout()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
applyTo(HDrawable target)

processing.core.PVector
getNextPoint()

int
iterationLimit()

HShapeLayout
iterationLimit(int i)

HDrawable
target()

HShapeLayout
target(HDrawable d)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HShapeLayout

public HShapeLayout()

Method Detail

iterationLimit

public HShapeLayout iterationLimit(int i)

iterationLimit

public int iterationLimit()

target

public HShapeLayout target(HDrawable d)

target

public HDrawable target()

applyTo

public void applyTo(HDrawable target)

Specified by:

applyTo in interface HLayout

getNextPoint

public processing.core.PVector getNextPoint()

Specified by:

getNextPoint in interface HLayout

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Processing library HYPE by Joshua Davis. (c) 2013-2016


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">

Tests that scripts for dynamically added script elements are shown in sources panel if loaded with inspector open.

Bug 99324


text:
package org.optaplanner.core.impl.heuristic.selector.move.composite;

import java.util.Collection;
import java.util.List;

import org.optaplanner.core.api.domain.valuerange.CountableValueRange;
import org.optaplanner.core.api.domain.valuerange.ValueRange;
import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider;
import org.optaplanner.core.impl.heuristic.selector.move.AbstractMoveSelector;
import org.optaplanner.core.impl.heuristic.selector.move.MoveSelector;

/**
 * Abstract superclass for every composite {@link MoveSelector}.
 * @see MoveSelector
 */
public abstract class CompositeMoveSelector extends AbstractMoveSelector {

    protected final List<MoveSelector> childMoveSelectorList;
    protected final boolean randomSelection;

    protected CompositeMoveSelector(List<MoveSelector> childMoveSelectorList, boolean randomSelection) {
        this.childMoveSelectorList = childMoveSelectorList;
        this.randomSelection = randomSelection;
        for (MoveSelector childMoveSelector : childMoveSelectorList) {
            phaseLifecycleSupport.addEventListener(childMoveSelector);
        }
        if (!randomSelection) {
            // Only the last childMoveSelector can be neverEnding
            if (!childMoveSelectorList.isEmpty()) {
                for (MoveSelector childMoveSelector
                        : childMoveSelectorList.subList(0, childMoveSelectorList.size() - 1)) {
                    if (childMoveSelector.isNeverEnding()) {
                        throw new IllegalStateException("The selector (" + this
                                + ")'s non-last childMoveSelector (" + childMoveSelector
                                + ") has neverEnding (" + childMoveSelector.isNeverEnding()
                                + ") with randomSelection (" + randomSelection + ")."
                                + (childMoveSelector.isCountable() ? ""
                                : "\nThe selector is not countable, check the "
                                + ValueRange.class.getSimpleName() + "s involved.\n"
                                + "Verify that a " + ValueRangeProvider.class.getSimpleName()
                                + " does not return " + ValueRange.class.getSimpleName()
                                + " when it can return " + CountableValueRange.class.getSimpleName()
                                + " or " + Collection.class.getSimpleName() + "."));
                    }
                }
            }
        }
    }

    public List<MoveSelector> getChildMoveSelectorList() {
        return childMoveSelectorList;
    }

    // ************************************************************************
    // Worker methods
    // ************************************************************************

    public boolean isCountable() {
        for (MoveSelector moveSelector : childMoveSelectorList) {
            if (!moveSelector.isCountable()) {
                return false;
            }
        }
        return true;
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + "(" + childMoveSelectorList + ")";
    }

}


text:
.ms-skin-default .ms-slide .ms-slide-vpbtn,
.ms-skin-default .ms-video-btn{
	width: 50px;
	height: 51px;
	background: url(../img/light-skin-1.png) no-repeat -14px -150px;
	top: 50%;
	left: 50%;
	margin: -25px 0 0 -25px;
}

.ms-skin-default .ms-slide .ms-slide-vcbtn {
	width: 30px;
	height: 30px;
	background: url(../img/light-skin-1.png) no-repeat -24px -28px;
	top: 18px;
	right: 30px;
}

/* controls */

.ms-skin-default .ms-nav-next,
.ms-skin-default .ms-nav-prev {
	width: 30px;
	background: url(../img/light-skin-1.png);
	background-position: -89px -26px;
	height: 40px;
	cursor: pointer;
	top: 112%;
	left: 145px;
	margin-top: -20px;
	position: absolute;
	z-index: 10;
	opacity:1 !important;
}
.ms-skin-default .ms-nav-next {
	right: 145px;
	left: auto;
	background-position: -89px -103px;
	opacity:1 !important;
}

.ms-skin-default .ms-thumb-frame-selected {
	opacity: 0.6;
}

.ms-skin-default .ms-thumb-list.ms-dir-h {
	bottom: -60px;
	width: 100%;
	height: 60px;
}

.ms-skin-default .ms-thumb-list.ms-dir-v {
	height: 100%;
	width: 60px;
	right: -60px;
	top: 0;
}

.ms-skin-default .ms-thumb-frame {
	cursor: pointer;
	float: left;
	width: 60px;
	height: 60px;
	margin: 1px 0 0 1px;
	overflow: hidden;
}

.ms-skin-default .ms-bullets.ms-dir-h {
	position: absolute;
	bottom: 20px;
	right: 50%;
	width: 100px;
}

.ms-skin-default .ms-bullets.ms-dir-h .ms-bullets-count {
	position: relative;
	right: -50%;
}

.ms-skin-default .ms-bullet {
	width: 10px;
	height: 10px;
	background: url(../img/light-skin-1.png) no-repeat;
	margin: 4px;
	background-position: -34px -117px;
}

.ms-skin-default .ms-bullet-selected {
	background-position: -34px -84px;
}

.ms-skin-default .ms-sbar {
	position: absolute;
}

.ms-skin-default .ms-sbar.ms-dir-h {
	left: 10px;
	right: 10px;
	top: 5px
}

.ms-skin-default .ms-sbar.ms-dir-v {
	top: 10px;
	bottom: 10px;
	right: 5px
}

.ms-skin-default .ms-sbar .ms-bar {
	height: 4px;
	background: #DD00FF;
	border-radius: 4px;
}

.ms-skin-default .ms-sbar.ms-dir-v .ms-bar {
	width: 4px;
}

.ms-skin-default .ms-timerbar {
	width: 100%;
	bottom: 0px;
	position: absolute;
}

.ms-skin-default .ms-time-bar {
	height: 3px;
	background: #FFFFFF;
	border-top: solid 1px rgba(0, 0, 0, 0.41);
}

.ms-skin-default .ms-ctimer {
	position: absolute;
	top: 30px;
	left: 30px;
	cursor: pointer;
}

.ms-skin-default .ms-ctimer-bullet {}

.ms-skin-default .ms-tooltip{
	position: absolute;
	z-index: 110;
	cursor: auto;
}

.ms-skin-default .ms-tooltip-top .ms-tooltip-arrow,
.ms-skin-default .ms-tooltip-bottom .ms-tooltip-arrow{
	border-left: solid 10px transparent;
	border-right: solid 10px transparent;
	position: absolute;
	left: 50%;
	margin-left: -10px;
}

.ms-skin-default .ms-tooltip-top .ms-tooltip-arrow{
	border-top: solid 10px;
	border-top-color: silver;
	border-top-color: rgba(240, 240, 240, 0.88);
	bottom: -10px;
}

.ms-skin-default .ms-tooltip-bottom .ms-tooltip-arrow {
	border-bottom: solid 10px;
	border-bottom-color: silver;
	border-bottom-color: rgba(240, 240, 240, 0.88);
	top: -10px;
}

.ms-skin-default .ms-tooltip-right .ms-tooltip-arrow,
.ms-skin-default .ms-tooltip-left .ms-tooltip-arrow{
	border-top: solid 10px transparent;
	border-bottom: solid 10px transparent;
	position: absolute;
	top: 50%;
	margin-top: -10px;
}

.ms-skin-default .ms-tooltip-right .ms-tooltip-arrow{
	border-right: solid 10px;
	border-right-color: silver;
	border-right-color: rgba(240, 240, 240, 0.88);
	left: -10px;
}

.ms-skin-default .ms-tooltip-left .ms-tooltip-arrow {
	border-left: solid 10px;
	border-left-color: silver;
	border-left-color: rgba(240, 240, 240, 0.88);
	right: -10px;
}

@keyframes point-anim{
	0% 		{transform: scale(0.5); -webkit-transform: scale(0.5); -moz-transform: scale(0.5); -o-transform: scale(0.5); -ms-transform: scale(0.5);  opacity: 1; }
	100% 	{transform: scale(0.5); -webkit-transform: scale(0.5); -moz-transform: scale(1.5); -o-transform: scale(1.5); -ms-transform: scale(1.5);  opacity: 0; }
}

@-webkit-keyframes point-anim{
	0% 		{-webkit-transform: scale(0.5); opacity: 1; }
	100% 	{-webkit-transform: scale(1.5);	opacity: 0; }
}

.ms-skin-default .ms-tooltip-point {cursor: pointer;}
.ms-skin-default .ms-tooltip-point .ms-point-center {
	width: 12px;
	height: 12px;
	border-radius: 15px;
	border: solid 2px #BBB;
	background: white;
	margin: -8px 0 0 -8px;
	position: absolute;
	z-index: 5;
}

.ms-skin-default .ms-tooltip-point .ms-point-border {
	width: 22px;
	height: 22px;
	background: black;
	background:rgba(0, 0, 0, 0.36);
	margin: -11px 0 0 -11px;
	position: absolute;
	border-radius: 15px;

	animation: point-anim 1.5s infinite ;
	-moz-animation: point-anim 1.5s infinite;
	-webkit-animation: point-anim 1.5s infinite;
	-o-animation: point-anim 1.5s infinite;
}

/* In Android browser, using css animations over slider causes some crashes */
.ms-android.ms-skin-default .ms-tooltip-point .ms-point-border{
	animation:none;
	-moz-animation:none;
	-webkit-animation:none;
	-o-animation:none;
}

.ms-skin-default .ms-tooltip {
	max-width:200px;
}

.ms-skin-default .ms-tooltip-cont {
	padding: 10px;
	background: silver;
	background: rgba(240, 240, 240, 0.88);
	text-shadow: 0 1px 0px white;
	margin-left: -1px;
}

/* retina */
@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (   min--moz-device-pixel-ratio: 2),
only screen and (     -o-min-device-pixel-ratio: 2/1),
only screen and (        min-device-pixel-ratio: 2),
only screen and (                min-resolution: 192dpi),
only screen and (                min-resolution: 2dppx) {

	.ms-skin-default .ms-slide .ms-slide-vpbtn,
	.ms-skin-default .ms-video-btn,
	.ms-skin-default .ms-slide .ms-slide-vcbtn,
	.ms-skin-default .ms-nav-next,
	.ms-skin-default .ms-nav-prev,
	.ms-skin-default .ms-bullet{
		background-image:url(../img/light-skin-1-retina.png);
		background-size: 152px 225px;
	}

}


text:
"""Wrapper classes for document, token, and mention frames"""

import sling

# Token break types.
NO_BREAK = 0
SPACE_BREAK = 1
LINE_BREAK = 2
SENTENCE_BREAK = 3
PARAGRAPH_BREAK = 4
SECTION_BREAK = 5
CHAPTER_BREAK = 6

class DocumentSchema:
  def __init__(self, store):
    self.isa = store['isa']
    self.document = store['document']
    self.document_text = store['text']
    self.document_tokens = store['tokens']
    self.document_mention = store['mention']
    self.document_theme = store['theme']

    self.token = store['token']
    self.token_index = store['index']
    self.token_word = store['word']
    self.token_start = store['start']
    self.token_size = store['size']
    self.token_break = store['break']
    self.token_pos = store['postag']

    self.phrase = store['phrase']
    self.phrase_begin = store['begin']
    self.phrase_length = store['length']
    self.phrase_evokes = store['evokes']

    self.thing = store['thing']

class Token(object):
  def __init__(self, document, frame, index):
    self.document = document
    self.schema = document.schema
    self.frame = frame
    self.index = index

  @property
  def word(self):
    text = self.frame[self.schema.token_word]
    if text == None:
      start = self.frame[self.schema.token_start]
      if start != None:
        size = self.frame[self.schema.token_size]
        if size == None: size = 1
        text = self.document._text[start : start + size].decode()
    return text

  @word.setter
  def word(self, value):
    self.frame[self.schema.token_word] = value

  @property
  def start(self):
    return self.frame[self.schema.token_start]

  @start.setter
  def start(self, value):
    self.frame[self.schema.token_start] = value

  @property
  def size(self):
    s = self.frame[self.schema.token_size]
    if s == None: s = 1
    return s

  @size.setter
  def size(self, value):
    self.frame[self.schema.token_size] = value

  @property
  def end(self):
    return self.start + self.size

  @property
  def brk(self):
    b = self.frame[self.schema.token_break]
    if b == None: b = SPACE_BREAK if self.index > 0 else NO_BREAK
    return b

  @brk.setter
  def brk(self, value):
    self.frame[self.schema.token_break] = value

class Mention(object):
  def __init__(self, schema, frame):
    self.schema = schema
    self.frame = frame

  @property
  def begin(self):
    return self.frame[self.schema.phrase_begin]

  @begin.setter
  def begin(self, value):
    self.frame[self.schema.phrase_begin] = value

  @property
  def length(self):
    l = self.frame[self.schema.phrase_length]
    if l == None: l = 1
    return l

  @length.setter
  def length(self, value):
    self.frame[self.schema.phrase_length] = value

  @property
  def end(self):
    return self.begin + self.length

  def evokes(self):
    return self.frame(self.schema.phrase_evokes)

  def evoke(self, evoked):
    return self.frame.append(self.schema.phrase_evokes, evoked)

  def evoke_type(self, frame_type):
    f = self.frame.store().frame({self.schema.isa: frame_type})
    self.evoke(f)
    return f

class Document(object):
  def __init__(self, frame=None, store=None, schema=None):
    # Create store, frame, and schema if missing.
    if frame != None:
      store = frame.store()
    if store == None:
      store = sling.Store()
    if schema == None:
      schema = DocumentSchema(store)
    if frame == None:
      frame = store.frame([(schema.isa, schema.document)])

    # Initialize document from frame.
    self.frame = frame
    self.schema = schema
    self._text = frame.get(schema.document_text, binary=True)
    self.tokens = []
    self.mentions = []
    self.themes = []
    self.tokens_dirty = False
    self.mentions_dirty = False
    self.themes_dirty = False

    # Get tokens.
    tokens = frame[schema.document_tokens]
    if tokens != None:
      for t in tokens:
        token = Token(self, t, len(self.tokens))
        self.tokens.append(token)

    # Get mentions.
    for m in frame(schema.document_mention):
      mention = Mention(schema, m)
      self.mentions.append(mention)

    # Get themes.
    for theme in frame(schema.document_theme):
      self.themes.append(theme)

  @property
  def store(self):
    return self.frame.store()

  def add_token(self, word=None, start=None, length=None, brk=SPACE_BREAK):
    slots = []
    if word != None: slots.append((self.schema.token_word, word))
    if start != None: slots.append((self.schema.token_start, start))
    if length != None: slots.append((self.schema.token_length, length))
    if brk != SPACE_BREAK: slots.append((self.schema.token_break, brk))
    token = Token(self, self.store.frame(slots), len(self.tokens))
    self.tokens.append(token)
    self.tokens_dirty = True
    return token

  def add_mention(self, begin, end):
    length = end - begin
    slots = [(self.schema.phrase_begin, begin)]
    if length != 1: slots.append((self.schema.phrase_length, length))
    mention = Mention(self.schema, self.store.frame(slots))
    self.mentions.append(mention)
    self.mentions_dirty = True
    return mention

  def evoke(self, begin, end, frame):
    mention = self.add_mention(begin, end)
    mention.evoke(frame)
    return frame

  def evoke_type(self, begin, end, frame_type):
    mention = self.add_mention(begin, end)
    return mention.evoke_type(frame_type)

  def add_theme(self, theme):
    self.themes.append(theme)
    self.themes_dirty = True

  def update(self):
    # Update tokens in document frame.
    if self.tokens_dirty:
      array = []
      for token in self.tokens: array.append(token.frame)
      self.frame[self.schema.document_tokens] = array
      self.tokens_dirty = False

    # Update mentions in document frame.
    if self.mentions_dirty:
      slots = []
      for mention in self.mentions:
        slots.append((self.schema.document_mention, mention.frame))
      del self.frame[self.schema.document_mention]
      self.frame.extend(slots)
      self.mentions_dirty = False

    # Update themes in document frame.
    if self.themes_dirty:
      slots = []
      for theme in self.themes:
        slots.append((self.schema.document_theme, theme))
      del self.frame[self.schema.document_theme]
      self.frame.extend(slots)
      self.themes_dirty = False

  @property
  def text(self):
    return self._text

  @text.setter
  def text(self, value):
    if isinstance(value, str): value = value.encode()
    self._text = value
    self.frame[self.schema.document_text] = value

  def phrase(self, begin, end):
    parts = []
    for token in self.tokens[begin:end]:
      if len(parts) > 0 and token.brk != NO_BREAK: parts.append(' ')
      parts.append(token.word)
    return ''.join(parts)

  def tolex(self):
    self.update()
    return sling.api.tolex(self.frame)

  def decorate(self):
    self.update()
    index = 0
    for t in self.tokens:
      t.frame.index = index
      if t.frame.word == None: t.word = self.text[t.start:t.end]
      index += 1
    for m in self.mentions:
      if m.frame.name is None:
        m.frame.name = self.phrase(m.begin, m.end)

  def remove_annotations(self):
    if len(self.mentions) > 0:
      self.mentions = []
      self.mentions_dirty = True
    if len(self.themes) > 0:
      self.themes = []
      self.themes_dirty = True
    self.update()

  def refresh_annotations(self):
    self.mentions = []
    for m in self.frame(self.schema.document_mention):
      mention = Mention(self.schema, m)
      self.mentions.append(mention)
    self.mentions_dirty = False

    self.themes = []
    for theme in self.frame(self.schema.document_theme):
      self.themes.append(theme)
    self.themes_dirty = False

class Corpus:
  def __init__(self, filename, commons=None):
    self.input = sling.RecordDatabase(filename)
    self.iter = iter(self.input)
    if commons == None:
      self.commons = sling.Store()
      self.docschema = sling.DocumentSchema(self.commons)
      self.commons.freeze()
    else:
      self.commons = commons
      if "document" in commons:
        self.docschema = sling.DocumentSchema(commons)
      else:
        self.docschema = None

  def __getitem__(self, key):
    data = self.input.lookup(key)
    f = sling.Store(self.commons).parse(data)
    return sling.Document(f, schema=self.docschema)

  def __iter__(self):
    return self

  def __next__(self):
    _, data = self.input.__next__()
    f = sling.Store(self.commons).parse(data)
    return sling.Document(f, schema=self.docschema)


text:
> Yeobara(`여봐라` in Korea), which mean is almost the same meaning of `Excuse me. I'm here` in English

![](https://cloud.githubusercontent.com/assets/124117/11326132/13954860-91a4-11e5-9300-92565cb8f6f6.png)

## Dev

```
$ FB_APIKEY=YOURKEY FB_APPNAME=https://YOURAPP.firebaseio.com/ GCM_KEY=YOUR_GCM_KEY npm install
```

### Configuration

This app requires `env` file at root location with information of connecting Firebase and GCM. It will be loaded as environment value on starting application. here are kinds of requirement value.

```
FB_APIKEY=YOUR_FB_KEY
FB_APPNAME=YOUR_FB_APPNAME
GCM_KEY=YOUR_GCM_KEY
```

There are two way of making env file. one way is that pass environment values when it called npm commands, `npm install` or `npm run env`. like this.

```
// after install
$ FB_APIKEY=YOURKEY FB_APPNAME=https://YOURAPP.firebaseio.com/ GCM_KEY=YOUR_GCM_KEY npm install

// update env file when it is needed
$ FB_APIKEY=YOURKEY FB_APPNAME=https://YOURAPP.firebaseio.com/ GCM_KEY=YOUR_GCM_KEY npm run env
```

The other hand is creating `env` file manually by yourself.

### Run

```
$ npm start
```

### Build

```
$ npm run bundle && npm run build
```

Builds the app for OS X, Linux, and Windows, using [electron-packager](https://github.com/maxogden/electron-packager).

## Download

You can [download](https://github.com/yeobara/yeobara-desktop/releases/latest) installable version of Yeobara which has been tested and showed for [Google Hackfair for Korea 2015](http://googlekoreablog.blogspot.kr/2015/10/2015-google-hackfair.html)
## License

MIT © [Yeobara](http://github.com/yeobara)


text:
package org.hl7.fhir.instance.model.valuesets;

// Generated on Tue, Jul 21, 2015 10:37-0400 for FHIR v0.5.0

public enum IssueType {

        /**
         * Content invalid against the Specification or a Profile
         */
        INVALID,
        /**
         * A structural issue in the content such as wrong namespace, or unable to parse the content completely, or invalid json syntax
         */
        STRUCTURE,
        /**
         * A required element is missing
         */
        REQUIRED,
        /**
         * element value invalid
         */
        VALUE,
        /**
         * A content validation rule failed - e.g. a schematron rule
         */
        INVARIANT,
        /**
         * An authentication/authorization/permissions issueof some kind
         */
        SECURITY,
        /**
         * the client needs to initiate an authentication process
         */
        LOGIN,
        /**
         * The user or system was not able to be authenticated (either there is no process, or the proferred token is unacceptable)
         */
        UNKNOWN,
        /**
         * User session expired; a login may be required
         */
        EXPIRED,
        /**
         * The user does not have the rights to perform this action
         */
        FORBIDDEN,
        /**
         * Some information was not or may not have been returned due to business rules, consent or privacy rules, or access permission constraints.  This information may be accessible through alternate processes
         */
        SUPPRESSED,
        /**
         * Processing issues. These are expected to be final e.g. there is no point resubmitting the same content unchanged
         */
        PROCESSING,
        /**
         * The resource or profile is not supported
         */
        NOTSUPPORTED,
        /**
         * An attempt was made to create a duplicate record
         */
        DUPLICATE,
        /**
         * The reference provided was not found. In a pure RESTful environment, this would be an HTTP 404 error, but this code may be used where the content is not found further into the application architecture
         */
        NOTFOUND,
        /**
         * Provided content is too long (typically, this is a denial of service protection type of error)
         */
        TOOLONG,
        /**
         * The code or system could not be understood, or it was not valid in the context of a particular ValueSet
         */
        CODEINVALID,
        /**
         * An extension was found that was not acceptable, or that could not be resolved, or a modifierExtension that was not recognised
         */
        EXTENSION,
        /**
         * The operation was stopped to protect server resources. E.g. a request for a value set expansion on all of SNOMED CT
         */
        TOOCOSTLY,
        /**
         * The content/operation failed to pass some business rule, and so could not proceed
         */
        BUSINESSRULE,
        /**
         * content could not be accepted because of an edit conflict (i.e. version aware updates) (In a pure RESTful environment, this would be an HTTP 404 error, but this code may be used where the conflict is discovered further into the application architecture)
         */
        CONFLICT,
        /**
         * Not all data sources typically accessed could be reached, or responded in time, so the returned information may not be complete
         */
        INCOMPLETE,
        /**
         * Transient processing issues. The system receiving the error may be able to resubmit the same content once an underlying issue is resolved
         */
        TRANSIENT,
        /**
         * A resource/record locking failure (usually in an underlying database)
         */
        LOCKERROR,
        /**
         * The persistent store unavailable. E.g. the database is down for maintenance or similar
         */
        NOSTORE,
        /**
         * An unexpected internal error
         */
        EXCEPTION,
        /**
         * An internal timeout occurred
         */
        TIMEOUT,
        /**
         * The system is not prepared to handle this request due to load management
         */
        THROTTLED,
        /**
         * A message unrelated to the processing success of the completed operation (Examples of the latter include things like reminders of password expiry, system maintenance times, etc.)
         */
        INFORMATIONAL,
        /**
         * added to help the parsers
         */
        NULL;
        public static IssueType fromCode(String codeString) throws Exception {
            if (codeString == null || "".equals(codeString))
                return null;
        if ("invalid".equals(codeString))
          return INVALID;
        if ("structure".equals(codeString))
          return STRUCTURE;
        if ("required".equals(codeString))
          return REQUIRED;
        if ("value".equals(codeString))
          return VALUE;
        if ("invariant".equals(codeString))
          return INVARIANT;
        if ("security".equals(codeString))
          return SECURITY;
        if ("login".equals(codeString))
          return LOGIN;
        if ("unknown".equals(codeString))
          return UNKNOWN;
        if ("expired".equals(codeString))
          return EXPIRED;
        if ("forbidden".equals(codeString))
          return FORBIDDEN;
        if ("suppressed".equals(codeString))
          return SUPPRESSED;
        if ("processing".equals(codeString))
          return PROCESSING;
        if ("not-supported".equals(codeString))
          return NOTSUPPORTED;
        if ("duplicate".equals(codeString))
          return DUPLICATE;
        if ("not-found".equals(codeString))
          return NOTFOUND;
        if ("too-long".equals(codeString))
          return TOOLONG;
        if ("code-invalid".equals(codeString))
          return CODEINVALID;
        if ("extension".equals(codeString))
          return EXTENSION;
        if ("too-costly".equals(codeString))
          return TOOCOSTLY;
        if ("business-rule".equals(codeString))
          return BUSINESSRULE;
        if ("conflict".equals(codeString))
          return CONFLICT;
        if ("incomplete".equals(codeString))
          return INCOMPLETE;
        if ("transient".equals(codeString))
          return TRANSIENT;
        if ("lock-error".equals(codeString))
          return LOCKERROR;
        if ("no-store".equals(codeString))
          return NOSTORE;
        if ("exception".equals(codeString))
          return EXCEPTION;
        if ("timeout".equals(codeString))
          return TIMEOUT;
        if ("throttled".equals(codeString))
          return THROTTLED;
        if ("informational".equals(codeString))
          return INFORMATIONAL;
        throw new Exception("Unknown IssueType code '"+codeString+"'");
        }
        public String toCode() {
          switch (this) {
            case INVALID: return "invalid";
            case STRUCTURE: return "structure";
            case REQUIRED: return "required";
            case VALUE: return "value";
            case INVARIANT: return "invariant";
            case SECURITY: return "security";
            case LOGIN: return "login";
            case UNKNOWN: return "unknown";
            case EXPIRED: return "expired";
            case FORBIDDEN: return "forbidden";
            case SUPPRESSED: return "suppressed";
            case PROCESSING: return "processing";
            case NOTSUPPORTED: return "not-supported";
            case DUPLICATE: return "duplicate";
            case NOTFOUND: return "not-found";
            case TOOLONG: return "too-long";
            case CODEINVALID: return "code-invalid";
            case EXTENSION: return "extension";
            case TOOCOSTLY: return "too-costly";
            case BUSINESSRULE: return "business-rule";
            case CONFLICT: return "conflict";
            case INCOMPLETE: return "incomplete";
            case TRANSIENT: return "transient";
            case LOCKERROR: return "lock-error";
            case NOSTORE: return "no-store";
            case EXCEPTION: return "exception";
            case TIMEOUT: return "timeout";
            case THROTTLED: return "throttled";
            case INFORMATIONAL: return "informational";
            default: return "?";
          }
        }
        public String getSystem() {
          return "http://hl7.org/fhir/issue-type";
        }
        public String getDefinition() {
          switch (this) {
            case INVALID: return "Content invalid against the Specification or a Profile";
            case STRUCTURE: return "A structural issue in the content such as wrong namespace, or unable to parse the content completely, or invalid json syntax";
            case REQUIRED: return "A required element is missing";
            case VALUE: return "element value invalid";
            case INVARIANT: return "A content validation rule failed - e.g. a schematron rule";
            case SECURITY: return "An authentication/authorization/permissions issueof some kind";
            case LOGIN: return "the client needs to initiate an authentication process";
            case UNKNOWN: return "The user or system was not able to be authenticated (either there is no process, or the proferred token is unacceptable)";
            case EXPIRED: return "User session expired; a login may be required";
            case FORBIDDEN: return "The user does not have the rights to perform this action";
            case SUPPRESSED: return "Some information was not or may not have been returned due to business rules, consent or privacy rules, or access permission constraints.  This information may be accessible through alternate processes";
            case PROCESSING: return "Processing issues. These are expected to be final e.g. there is no point resubmitting the same content unchanged";
            case NOTSUPPORTED: return "The resource or profile is not supported";
            case DUPLICATE: return "An attempt was made to create a duplicate record";
            case NOTFOUND: return "The reference provided was not found. In a pure RESTful environment, this would be an HTTP 404 error, but this code may be used where the content is not found further into the application architecture";
            case TOOLONG: return "Provided content is too long (typically, this is a denial of service protection type of error)";
            case CODEINVALID: return "The code or system could not be understood, or it was not valid in the context of a particular ValueSet";
            case EXTENSION: return "An extension was found that was not acceptable, or that could not be resolved, or a modifierExtension that was not recognised";
            case TOOCOSTLY: return "The operation was stopped to protect server resources. E.g. a request for a value set expansion on all of SNOMED CT";
            case BUSINESSRULE: return "The content/operation failed to pass some business rule, and so could not proceed";
            case CONFLICT: return "content could not be accepted because of an edit conflict (i.e. version aware updates) (In a pure RESTful environment, this would be an HTTP 404 error, but this code may be used where the conflict is discovered further into the application architecture)";
            case INCOMPLETE: return "Not all data sources typically accessed could be reached, or responded in time, so the returned information may not be complete";
            case TRANSIENT: return "Transient processing issues. The system receiving the error may be able to resubmit the same content once an underlying issue is resolved";
            case LOCKERROR: return "A resource/record locking failure (usually in an underlying database)";
            case NOSTORE: return "The persistent store unavailable. E.g. the database is down for maintenance or similar";
            case EXCEPTION: return "An unexpected internal error";
            case TIMEOUT: return "An internal timeout occurred";
            case THROTTLED: return "The system is not prepared to handle this request due to load management";
            case INFORMATIONAL: return "A message unrelated to the processing success of the completed operation (Examples of the latter include things like reminders of password expiry, system maintenance times, etc.)";
            default: return "?";
          }
        }
        public String getDisplay() {
          switch (this) {
            case INVALID: return "Invalid Content";
            case STRUCTURE: return "Structural Issue";
            case REQUIRED: return "Required element missing";
            case VALUE: return "Element value invalid";
            case INVARIANT: return "Validation rule failed";
            case SECURITY: return "Security Problem";
            case LOGIN: return "Login Required";
            case UNKNOWN: return "Unknown User";
            case EXPIRED: return "Session Expired";
            case FORBIDDEN: return "Forbidden";
            case SUPPRESSED: return "Information  Suppressed";
            case PROCESSING: return "Processing Failure";
            case NOTSUPPORTED: return "Content not supported";
            case DUPLICATE: return "Duplicate";
            case NOTFOUND: return "Not Found";
            case TOOLONG: return "Content Too Long";
            case CODEINVALID: return "Invalid Code";
            case EXTENSION: return "Unacceptable Extension";
            case TOOCOSTLY: return "Operation Too Costly";
            case BUSINESSRULE: return "Business Rule Violation";
            case CONFLICT: return "Edit Version Conflict";
            case INCOMPLETE: return "Incomplete Results";
            case TRANSIENT: return "Transient Issue";
            case LOCKERROR: return "Lock Error";
            case NOSTORE: return "No Store Available";
            case EXCEPTION: return "Exception";
            case TIMEOUT: return "Timeout";
            case THROTTLED: return "Throttled";
            case INFORMATIONAL: return "Informational Note";
            default: return "?";
          }
    }

}


text:
package com.yuzhouwan.hadoop.customer_behaviour_analyse;

import java.io.UnsupportedEncodingException;
import java.util.List;

import net.spy.memcached.compat.log.Logger;
import net.spy.memcached.compat.log.LoggerFactory;
import backtype.storm.spout.Scheme;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;

public class TestMessageScheme implements Scheme {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private static final Logger LOGGER = LoggerFactory
			.getLogger(TestMessageScheme.class);

	@Override
	public List<Object> deserialize(byte[] ser) {

		String msg;
		try {
			msg = new String(ser, "UTF-8");
			System.out.println("$$$$$$$$$$$$$$" + msg);
			return new Values(msg);
		} catch (UnsupportedEncodingException e) {
			LOGGER.error("Can not parse the provide message from bytes.");
			throw new RuntimeException(e);
		}
	}

	@Override
	public Fields getOutputFields() {
		return new Fields("msg");
	}

}


text:
The Go gopher was designed by Renee French. (http://reneefrench.blogspot.com/)
The design is licensed under the Creative Commons 3.0 Attributions license.
Read this article for more details: http://blog.golang.org/gopher

The Go Gopher mascot has been modified for this program.


text:
<?php defined("INCLUDED") or die("Acceso denegado.");

if(!isset($_SESSION['logged'])) {
    $_SESSION['logged'] = false;
}

echo json_data(["logged" => $_SESSION['logged']]);


text:
package be.belgium.eid.exceptions;

/**
 * The "invalid SW" exception indicates that the values 0x90 and 0x00 should
 * have been returned for Status Word (SW) 1 and 2 respectively.
 *
 * @author Kristof Overdulve
 * @version 1.0.0 25 Nov 2007
 */
@SuppressWarnings("serial")
public class InvalidSWException extends Exception {

	/** contains the invalid SW1 */
	private final int fSW1;

	/** contains the invalid SW2 */
	private final int fSW2;

	/**
	 * Initializes a new invalid SW exception.
	 *
	 * @param sw1
	 *            is the first invalid status word
	 * @param sw2
	 *            is the second invalid status word
	 */
	public InvalidSWException(final int sw1, final int sw2) {
		super();
		fSW1 = sw1;
		fSW2 = sw2;
	}

	/**
	 * Initializes a new invalid SW exception with the cause of the problem.
	 *
	 * @param sw1
	 *            is the first invalid status word
	 * @param sw2
	 *            is the second invalid status word
	 * @param cause
	 *            is the cause of the exception
	 */
	public InvalidSWException(final int sw1, final int sw2, Throwable cause) {
		super(cause);
		fSW1 = sw1;
		fSW2 = sw2;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Throwable#getMessage()
	 */
	public String getMessage() {
		return "The returned status word values " + fSW1 + " and " + fSW2
				+ " should have been 0x90 and 0x00.";
	}
}