text:
package com.ruesga.rview.misc;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.LeadingMarginSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.TypefaceSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ruesga.rview.R;
import com.ruesga.rview.attachments.Attachment;
import com.ruesga.rview.fragments.ChangeDetailsFragment;
import com.ruesga.rview.gerrit.model.AccountDetailInfo;
import com.ruesga.rview.gerrit.model.AccountInfo;
import com.ruesga.rview.gerrit.model.ChangeInfo;
import com.ruesga.rview.gerrit.model.ChangeKind;
import com.ruesga.rview.gerrit.model.ChangeMessageInfo;
import com.ruesga.rview.gerrit.model.ChangeStatus;
import com.ruesga.rview.gerrit.model.CommentInfo;
import com.ruesga.rview.gerrit.model.CommitInfo;
import com.ruesga.rview.gerrit.model.ConfigInfo;
import com.ruesga.rview.gerrit.model.FileInfo;
import com.ruesga.rview.gerrit.model.FileStatus;
import com.ruesga.rview.gerrit.model.GitPersonalInfo;
import com.ruesga.rview.gerrit.model.MergeableInfo;
import com.ruesga.rview.gerrit.model.ProjectStatus;
import com.ruesga.rview.gerrit.model.ReviewerStatus;
import com.ruesga.rview.gerrit.model.ReviewerUpdateInfo;
import com.ruesga.rview.gerrit.model.RevisionInfo;
import com.ruesga.rview.gerrit.model.SideType;
import com.ruesga.rview.gerrit.model.SubmitType;
import com.ruesga.rview.model.Account;
import com.ruesga.rview.model.ContinuousIntegrationInfo;
import com.ruesga.rview.model.EmptyState;
import com.ruesga.rview.model.UnresolvedComment;
import com.ruesga.rview.preferences.Constants;
import com.ruesga.rview.preferences.Preferences;
import com.ruesga.rview.text.QuotedSpan;
import com.ruesga.rview.text.TagSpan;
import com.ruesga.rview.widget.RegExLinkifyTextView;
import com.ruesga.rview.widget.RegExLinkifyTextView.RegExLink;
import com.ruesga.rview.widget.StyleableTextView;

import org.ocpsoft.prettytime.PrettyTime;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;

import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.Keep;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.databinding.BindingAdapter;

@Keep
@SuppressWarnings("unused")
public class Formatter {
    private static Account mAccount;
    private static final Map<String, PrettyTime> sPrettyTimeMap = new HashMap<>();
    private static String sDisplayFormat = Constants.ACCOUNT_DISPLAY_FORMAT_NAME;
    private static boolean sHighlightNotReviewed = true;
    private static boolean sDisplayAccountStatues = true;
    private static int sHighlightScoredMessages = Constants.HIGHLIGHT_SCORED_MESSAGE_MESSAGE;

    private static int sQuoteColor = -1;
    private static int sQuoteWidth = -1;
    private static int sQuoteMargin = -1;

    public static void refreshCachedPreferences(Context context) {
        mAccount = Preferences.getAccount(context);
        sDisplayFormat = Preferences.getAccountDisplayFormat(context, mAccount);
        sHighlightNotReviewed = Preferences.isAccountHighlightUnreviewed(context, mAccount);
        sDisplayAccountStatues = Preferences.isAccountDisplayStatuses(context, mAccount);
        sHighlightScoredMessages = Preferences.getAccountMessagesHighlightScored(context, mAccount);
    }

    private static PrettyTime getPrettyTime(Context context) {
        String localeTag = context.getString(R.string.bcp47_locale_tag);
        if (!sPrettyTimeMap.containsKey(localeTag)) {
            final String[] localeInfo = localeTag.split("-");
            final Locale locale = new Locale(localeInfo[0], localeInfo[1]);
            sPrettyTimeMap.put(localeTag, new PrettyTime(locale));
        }
        return sPrettyTimeMap.get(localeTag);
    }

    @BindingAdapter("prettyDateTime")
    public static void toPrettyDateTime(TextView view, Date date) {
        if (date == null) {
            view.setText(null);
            return;
        }
        view.setText(getPrettyTime(view.getContext()).format(date));
    }

    @SuppressWarnings("deprecation")
    @BindingAdapter("changeMessageAccount")
    public static void toChangeMessageAccount(TextView view, ChangeMessageInfo changeMessage) {
        if (changeMessage == null) {
            toAccountDisplayName(view, null);
            return;
        }

        if (ModelHelper.isOnBehalfOf(changeMessage)) {
            view.setText(Html.fromHtml(
                    view.getContext().getString(R.string.change_details_on_behalf_of,
                            toAccountDisplayName(changeMessage.realAuthor),
                            toAccountDisplayName(changeMessage.author))));
            view.setTypeface(TypefaceCache.getTypeface(view.getContext(), TypefaceCache.TF_REGULAR));
            return;
        }

        toAccountDisplayName(view, changeMessage.author);
    }

    @BindingAdapter("accountDisplayName")
    public static void toAccountDisplayName(TextView view, AccountInfo accountInfo) {
        if (accountInfo == null) {
            view.setText(null);
            return;
        }

        view.setText(toAccountDisplayName(accountInfo));
    }

    public static String toAccountDisplayName(AccountInfo accountInfo) {
        // Display Name
        String accountDisplayName = null;
        switch (sDisplayFormat) {
            case Constants.ACCOUNT_DISPLAY_FORMAT_NAME:
                accountDisplayName = accountInfo.name;
                break;
            case Constants.ACCOUNT_DISPLAY_FORMAT_EMAIL:
                accountDisplayName = accountInfo.email;
                break;
            case Constants.ACCOUNT_DISPLAY_FORMAT_USERNAME:
                accountDisplayName = accountInfo.username;
                break;
            case Constants.ACCOUNT_DISPLAY_FORMAT_DISPLAY_NAME:
                accountDisplayName = accountInfo.displayName;
                break;
        }
        if (TextUtils.isEmpty(accountDisplayName)) {
            accountDisplayName = accountInfo.displayName;
        }
        if (TextUtils.isEmpty(accountDisplayName)) {
            accountDisplayName = accountInfo.username;
        }
        if (TextUtils.isEmpty(accountDisplayName)) {
            accountDisplayName = accountInfo.name;
        }
        if (TextUtils.isEmpty(accountDisplayName)) {
            accountDisplayName = accountInfo.email;
        }
        if (TextUtils.isEmpty(accountDisplayName)) {
            accountDisplayName = String.valueOf(accountInfo.accountId);
        }

        // Status
        if (sDisplayAccountStatues && !TextUtils.isEmpty(accountInfo.status)) {
            accountDisplayName += " (" + accountInfo.status + ")";
        }

        return accountDisplayName;
    }

    @BindingAdapter({"draftAccountDisplayName", "isDraft"})
    public static void toDraftAccountDisplayName(
            TextView view, AccountInfo accountInfo, boolean isDraft) {

        if (isDraft) {
            Context ctx = view.getContext();
            view.setText(ctx.getString(R.string.menu_draft).toUpperCase(
                    AndroidHelper.getCurrentLocale(ctx)));
            Drawable dw = ContextCompat.getDrawable(ctx, R.drawable.bg_tag);
            if (dw != null) {
                dw = DrawableCompat.wrap(dw.mutate());
                DrawableCompat.setTint(dw, ContextCompat.getColor(ctx, R.color.unscored));
            }
            view.setBackground(dw);
            return;
        }

        view.setBackground(null);
        toAccountDisplayName(view, accountInfo);
    }

    @BindingAdapter("highlightUnreviewed")
    public static void toHighlightedUnreviewed(StyleableTextView view, boolean reviewed) {
        view.setTypeface(TypefaceCache.getTypeface(view.getContext(),
                sHighlightNotReviewed && !reviewed
                        ? TypefaceCache.TF_BOLD_CONDENSED : TypefaceCache.TF_CONDENSED));
    }

    @BindingAdapter("compressedText")
    public static void toCompressedText(TextView view, String value) {
        if (value == null) {
            view.setText(null);
            return;
        }
        view.setText(value.replaceAll("\n", " ").trim());
    }

    @BindingAdapter("commitMessage")
    public static void toCommitMessage(TextView view, CommitInfo info) {
        if (info == null || info.message == null) {
            view.setText(null);
            return;
        }

        String message = EmojiHelper.createEmoji(
                info.message.substring(info.subject.length()).trim());
        view.setText(StringHelper.removeLineBreaks(message));
    }

    @SuppressWarnings("deprecation")
    @BindingAdapter("userFoldMessage")
    public static void userFoldMessage(TextView view, ChangeMessageInfo msg) {
        if (msg == null) {
            view.setText(null);
            return;
        }

        // Create reviewer updates message
        if (msg._reviewer_updates.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (ReviewerStatus status : ReviewerStatus.values()) {
                sb.append(toReviewUpdateMessage(
                        view.getContext(), msg._reviewer_updates, status, sb.length() > 0));
            }
            view.setText(Html.fromHtml(StringHelper.fold(sb.toString())));
            return;
        }

        // Fold the user message
        String userMessage = StringHelper.fold(StringHelper.removeAllAttachments(msg.message));
        if (userMessage == null) {
            view.setText(null);
            return;
        }
        final SpannableStringBuilder spannable = new SpannableStringBuilder(userMessage);
        highlightUserMessageReviewScores(
                view.getContext(), StringHelper.firstLine(msg.message), spannable);
        view.setText(spannable);
    }

    @BindingAdapter("userMessage")
    public static void toUserMessage(TextView view, String msg) {
        if (msg == null) {
            view.setText(null);
            return;
        }

        // Clean up paragraphs (to mimic "

" browsers behaviour) and create Emojis
        String message = EmojiHelper.createEmoji(StringHelper.cleanUpParagraphs(msg));

        // This process mimics the Gerrit formatting process done in class
        // ./gerrit-gwtexpui/src/main/java/com/google/gwtexpui/safehtml/client/SafeHtml.java

        // Split message into paragraphs
        String[] paragraphs = StringHelper.obtainParagraphs(message);
        StringBuilder sb = new StringBuilder();
        boolean formattedMessage = false;
        for (String p : paragraphs) {
            if (StringHelper.isQuote(p)) {
                sb.append(StringHelper.obtainQuote(StringHelper.prepareForQuote(p).trim()));
                formattedMessage = true;
            } else if (StringHelper.isList(p)) {
                sb.append(p);
                formattedMessage = true;
            } else if (StringHelper.isPreFormat(p)) {
                sb.append(StringHelper.obtainPreFormatMessage(p));
                formattedMessage = true;
            } else {
                sb.append(p);
            }
            if (sb.length() > 0) {
                while (sb.charAt(sb.length() - 1) == '\n') {
                    sb = sb.deleteCharAt(sb.length() - 1);
                }
            }
            sb.append("\n\n");
        }

        String userMessage = StringHelper.removeExtraLines(sb.toString());

        // Create the spannable
        final SpannableStringBuilder spannable;
        if (!formattedMessage) {
            spannable = new SpannableStringBuilder(userMessage);
        } else {
            spannable = new SpannableStringBuilder(
                    userMessage.replaceAll(StringHelper.NON_PRINTABLE_CHAR, "")
                            .replaceAll(StringHelper.NON_PRINTABLE_CHAR2, ""));
        }

        // Highlight user message's scores
        highlightUserMessageReviewScores(
                view.getContext(), StringHelper.firstLine(userMessage), spannable);

        // If the user message is not formatted, do not try to compute unnecessary stuff
        if (!formattedMessage) {
            view.setText(spannable);
            return;
        }

        if (sQuoteColor == -1) {
            sQuoteColor = ContextCompat.getColor(view.getContext(), R.color.quote);
            sQuoteWidth = (int) view.getContext().getResources().getDimension(R.dimen.quote_width);
            sQuoteMargin = (int) view.getContext().getResources().getDimension(R.dimen.quote_margin);
        }
        String[] lines = userMessage.split("\n");

        // Pre-Format
        int start = 0;
        int spans = 0;
        while ((start = userMessage.indexOf(StringHelper.NON_PRINTABLE_CHAR2, start)) != -1) {
            int end = userMessage.indexOf(StringHelper.NON_PRINTABLE_CHAR2, start + 1);
            if (end == -1) {
                //¿? This is supposed to be formatted by us. Skip it
                break;
            }

            // Find quote token occurrences
            int offset = StringHelper.countOccurrences(
                    StringHelper.NON_PRINTABLE_CHAR, userMessage, 0, start);
            start -= offset;
            end -= offset;

            // Ensure bounds
            int spanStart = start - spans;
            int spanEnd = Math.min(end - spans - 1, spannable.length());
            if (spanStart < 0 || spanEnd < 0) {
                //Something was wrong. Skip it
                break;
            }
            spannable.setSpan(new RelativeSizeSpan(0.8f), spanStart, spanEnd,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannable.setSpan(new TypefaceSpan("monospace"), spanStart, spanEnd,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            start = end;
            spans++;
        }

        start = 0;
        for (String line : lines) {
            // Quotes
            int maxIndent = StringHelper.countOccurrences(StringHelper.NON_PRINTABLE_CHAR, line);
            for (int i = 0; i < maxIndent; i++) {
                QuotedSpan span = new QuotedSpan(sQuoteColor, sQuoteWidth, sQuoteMargin);
                spannable.setSpan(span, start,
                        Math.min(start + line.length() - maxIndent, spannable.length()),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            // List
            if (StringHelper.isList(line)) {
                spannable.replace(start, start + 1, "\u2022");
                spannable.setSpan(new LeadingMarginSpan.Standard(sQuoteMargin),
                        start, Math.min(start + line.length(), spannable.length()),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            start += line.length() - maxIndent + 1;
        }

        view.setText(spannable);
    }

    @BindingAdapter("regexpLinkifyCommitsOnly")
    public static void toRegExLinkifyCommitsOnly(RegExLinkifyTextView view, Boolean only) {
        List<RegExLink> linksScanners = new ArrayList<>();

        if (mAccount != null) {
            linksScanners.addAll(
                    RegExLinkifyTextView.createRepositoryRegExpLinks(mAccount.mRepository));
        }

        if (only) {
            linksScanners.add(RegExLinkifyTextView.GERRIT_CHANGE_ID_REGEX);
            linksScanners.add(RegExLinkifyTextView.GERRIT_COMMIT_REGEX);
        }

        if (!linksScanners.isEmpty()) {
            view.addRegEx(linksScanners.toArray(new RegExLink[0]));
        }
    }

    @BindingAdapter("regexpLinkify")
    public static void toRegExLinkify(RegExLinkifyTextView view, ConfigInfo info) {
        List<RegExLink> linksScanners = new ArrayList<>();
        linksScanners.add(RegExLinkifyTextView.GERRIT_CHANGE_ID_REGEX);
        linksScanners.add(RegExLinkifyTextView.GERRIT_COMMIT_REGEX);
        if (mAccount != null) {
            linksScanners.addAll(
                    RegExLinkifyTextView.createRepositoryRegExpLinks(mAccount.mRepository));
        }

        if (info != null && info.commentLinks != null) {
            for (String key : info.commentLinks.keySet()) {
                switch (key) {
                    case "changeid":
                    case "commit":
                        break;
                    default:
                        String match = info.commentLinks.get(key).match;
                        String link = info.commentLinks.get(key).link;
                        String htmlLink = StringHelper.extractLinkFromHtml(
                                info.commentLinks.get(key).html);
                        if (TextUtils.isEmpty(match) && TextUtils.isEmpty(link)
                                && TextUtils.isEmpty(htmlLink)) {
                            continue;
                        }

                        // Use link if available, otherwise extract the link from the html
                        if (TextUtils.isEmpty(link)) {
                            link = htmlLink;
                        }

                        // Add the link scanner
                        linksScanners.add(new RegExLink(RegExLinkifyTextView.WEB_LINK_REGEX.mType,
                                match, link, true));
                        break;
                }
            }
        }

        view.addRegEx(linksScanners.toArray(new RegExLink[0]));
    }

    @BindingAdapter("committer")
    public static void toCommitter(TextView view, GitPersonalInfo info) {
        if (info == null) {
            view.setText(null);
            return;
        }

        String date = getPrettyTime(view.getContext()).format(info.date);
        String txt = view.getContext().getString(
                R.string.committer_format, info.name, info.email, date);
        view.setText(txt);
    }

    @BindingAdapter("score")
    public static void toScore(TextView view, Integer score) {
        if (score == null) {
            view.setText(null);
            return;
        }

        String txt = (score > 0 ? "+" : "") + String.valueOf(score);
        view.setText(txt);
    }

    @BindingAdapter("submitType")
    public static void toSubmitType(TextView view, SubmitType submitType) {
        if (submitType == null) {
            view.setText(null);
            return;
        }

        if (submitType.equals(SubmitType.FAST_FORWARD_ONLY)) {
            view.setText(R.string.submit_type_fast_forward_only);
        } else if (submitType.equals(SubmitType.MERGE_IF_NECESSARY)) {
            view.setText(R.string.submit_type_merge_if_necessary);
        } else if (submitType.equals(SubmitType.MERGE_ALWAYS)) {
            view.setText(R.string.submit_type_merge_always);
        } else if (submitType.equals(SubmitType.CHERRY_PICK)) {
            view.setText(R.string.submit_type_cherry_pick);
        } else if (submitType.equals(SubmitType.REBASE_IF_NECESSARY)) {
            view.setText(R.string.submit_type_rebase_if_necessary);
        } else {
            view.setText(null);
        }
    }

    @BindingAdapter("fileTypeDrawable")
    public static void toFileTypeDrawable(ImageView view, FileInfo model) {
        if (model == null || model.status == null) {
            view.setImageDrawable(null);
            return;
        }

        view.setImageDrawable(ContextCompat.getDrawable(view.getContext(),
                ModelHelper.toFileStatusDrawable(model.status)));
    }

    @BindingAdapter("fileStatus")
    public static void toFileStatus(TextView view, ChangeDetailsFragment.FileItemModel item) {
        if (item == null) {
            view.setText(null);
            return;
        }

        String status = "";
        String txt = "";
        if (item.info != null) {
            if (item.info.status.equals(FileStatus.R)) {
                status = "[" + view.getContext().getString(R.string.file_status_renamed) + "] ";
            } else if (item.info.status.equals(FileStatus.C)) {
                status = "[" + view.getContext().getString(R.string.file_status_copied) + "] ";
            } else if (item.info.status.equals(FileStatus.W)) {
                status = "[" + view.getContext().getString(R.string.file_status_rewritten) + "] ";
            }
            txt = status;
            if (!TextUtils.isEmpty(item.info.oldPath)) {
                txt += item.info.oldPath + " \u2192 ";
            }
        }
        txt += item.file.startsWith("/") ? item.file.substring(1) : item.file;
        view.setText(txt);
    }

    @BindingAdapter("fileStatus")
    public static void toFileStatus(TextView view, FileStatus status) {
        if (status == null) {
            view.setText(null);
            return;
        }

        if (status.equals(FileStatus.R)) {
            view.setText(R.string.file_status_renamed);
        } else if (status.equals(FileStatus.C)) {
            view.setText(R.string.file_status_copied);
        } else if (status.equals(FileStatus.W)) {
            view.setText(R.string.file_status_rewritten);
        } else if (status.equals(FileStatus.A)) {
            view.setText(R.string.file_status_added);
        } else if (status.equals(FileStatus.D)) {
            view.setText(R.string.file_status_deleted);
        } else if (status.equals(FileStatus.M)) {
            view.setText(R.string.file_status_modified);
        }
    }

    @BindingAdapter("file")
    public static void toFile(TextView view, String path) {
        view.setText(path.startsWith("/") ? path.substring(1) : path);
    }

    @BindingAdapter("moreItems")
    public static void toMoreItems(TextView view, Integer more) {
        int q = more == null ? 0 : more;
        view.setText(view.getResources().getQuantityString(R.plurals.more_items, q, q));
    }

    @BindingAdapter({"changeStatus", "mergeableInfo", "currentRevision"})
    public static void toChangeStatus(TextView view, ChangeInfo change, MergeableInfo mergeableInfo, boolean currentRevision) {
        if (change == null) {
            view.setText(null);
            return;
        }

        if (!currentRevision) {
            view.setText(R.string.change_statuses_not_current);
        } else if (ChangeStatus.NEW.equals(change.status)) {
            if (change.submittable) {
                view.setText(R.string.change_statuses_ready_to_submit);
            } else if (!mergeableInfo.mergeable) {
                view.setText(R.string.change_statuses_not_mergeable);
            } else {
                String neededLabel = ModelHelper.checkNeedsLabel(change.labels);
                if (neededLabel != null) {
                    view.setText(view.getContext().getString(
                            R.string.change_statuses_needs_label, neededLabel));
                } else {
                    view.setText(R.string.menu_open);
                }
            }
        } else if (ChangeStatus.SUBMITTED.equals(change.status)) {
            view.setText(R.string.change_statuses_submitted);
        } else if (ChangeStatus.MERGED.equals(change.status)) {
            view.setText(R.string.menu_merged);
        } else if (ChangeStatus.ABANDONED.equals(change.status)) {
            view.setText(R.string.menu_abandoned);
        } else if (ChangeStatus.DRAFT.equals(change.status)) {
            view.setText(R.string.menu_draft);
        } else {
            view.setText(null);
        }
    }

    @BindingAdapter("addedVsDeleted")
    public static void toAddedVsRemoved(TextView view, FileInfo info) {
        if (info == null) {
            view.setText(null);
            return;
        }

        final Resources res = view.getResources();
        String added = null;
        if (info.linesInserted != null && info.linesInserted > 0) {
            added = res.getQuantityString(
                    R.plurals.files_added, info.linesInserted, info.linesInserted);
        }
        String deleted = null;
        if (info.linesDeleted != null && info.linesDeleted > 0) {
            deleted = res.getQuantityString(
                    R.plurals.files_deleted, info.linesDeleted, info.linesDeleted);
        }
        if (added == null && deleted == null) {
            added = res.getQuantityString(R.plurals.files_added, 0, 0);
            deleted = res.getQuantityString(R.plurals.files_deleted, 0, 0);
        }

        String txt;
        if (added != null && deleted != null) {
            txt = res.getString(R.string.added_vs_deleted, added, deleted);
        } else if (added != null) {
            txt = added;
        } else {
            txt = deleted;
        }
        view.setText(txt);
    }

    @BindingAdapter("commitWebLinksTag")
    public static void toCommitWebLinksTag(View view, CommitInfo commit) {
        if (commit != null && commit.webLinks != null && commit.webLinks.length > 0) {
            view.setTag(commit.webLinks[0].url);
        } else {
            view.setTag(null);
        }
    }

    @BindingAdapter("revisionNumber")
    public static void toRevisionNumber(TextView view, RevisionInfo revision) {
        if (revision == null) {
            view.setText(null);
            return;
        }
        view.setText(String.format(Locale.US, "#%02d", revision.number));
    }

    @BindingAdapter("revisionCommit")
    public static void toRevisionCommit(TextView view, RevisionInfo revision) {
        if (revision == null) {
            view.setText(null);
            return;
        }
        if (revision.commit == null) {
            view.setText(view.getContext().getString(R.string.options_base));
        } else {
            view.setText(revision.commit.commit.substring(0, 10));
        }
    }

    @BindingAdapter("reviewerKind")
    public static void toReviewerKind(ImageView view, Boolean isGroup) {
        view.setImageResource(isGroup != null && isGroup
                ? R.drawable.ic_group : R.drawable.ic_person);
    }

    @BindingAdapter("accountEmails")
    public static void toAccountEmails(TextView v, AccountDetailInfo account) {
        if (account == null || account.email == null) {
            v.setText(null);
            return;
        }

        StringBuilder emails = new StringBuilder(account.email);
        if (account.secondaryEmails != null) {
            emails.append(" ")
                    .append(v.getContext().getString(R.string.account_details_emails_preferred))
                    .append("");
            for (String email : account.secondaryEmails) {
                emails.append("
").append(email);
            }
        }
        v.setText(Html.fromHtml(emails.toString()));
    }

    @BindingAdapter("projectStatus")
    public static void toProjectStatus(TextView v, ProjectStatus status) {
        if (status == null) {
            v.setText(null);
            return;
        }

        String statusText = null;
        if (status.equals(ProjectStatus.ACTIVE)) {
            statusText = v.getContext().getString(R.string.project_details_status_active);
        } else if (status.equals(ProjectStatus.READ_ONLY)) {
            statusText = v.getContext().getString(R.string.project_details_status_read_only);
        } else if (status.equals(ProjectStatus.HIDDEN)) {
            statusText = v.getContext().getString(R.string.project_details_status_hidden);
        }
        v.setText(statusText);
    }

    @BindingAdapter("commentLine")
    public static void toCommentLine(TextView v, CommentInfo comment) {
        if (comment == null) {
            v.setText(null);
            return;
        }

        String link = "";
        if (comment.patchSet != comment.messagePatchSet) {
            link = v.getContext().getString(
                    R.string.change_details_comment_patchset, comment.patchSet);
        }
        if (comment.line == null) {
            link += v.getContext().getString(R.string.change_details_comment_file);
        } else if (SideType.PARENT.equals(comment.side)) {
            link += v.getContext().getString(
                    R.string.change_details_comment_base_line_number, comment.line);
        } else {
            link += v.getContext().getString(
                    R.string.change_details_comment_line_number, comment.line);
        }
        v.setText(link);
    }

    @BindingAdapter("accountStatus")
    public static void toAccountStatus(TextView view, String status) {
        view.setText(EmojiHelper.resolveEmojiStatus(view.getContext(), status));
    }

    @BindingAdapter("revisionKind")
    public static void toRevisionKind(TextView view, RevisionInfo revision) {
        if (revision == null) {
            view.setText(null);
            view.setVisibility(View.GONE);
            return;
        }

        String text = null;
        if (ChangeKind.REWORK.equals(revision.kind)) {
            text = view.getContext().getString(R.string.revision_kind_rework);
        } else if (ChangeKind.TRIVIAL_REBASE.equals(revision.kind)) {
            text = view.getContext().getString(R.string.revision_kind_trivial_rebase);
        } else if (ChangeKind.MERGE_FIRST_PARENT_UPDATE.equals(revision.kind)) {
            text = view.getContext().getString(R.string.revision_kind_merge_first_parent_update);
        }
        view.setText(text);
        view.setVisibility(TextUtils.isEmpty(text) ? View.GONE : View.VISIBLE);
    }

    @BindingAdapter("unresolvedComments")
    public static void toUnresolvedComments(TextView view, UnresolvedComment unresolvedComment) {
        if (unresolvedComment == null || unresolvedComment.mTotal == 0) {
            view.setVisibility(View.GONE);
            return;
        }

        final Context ctx = view.getContext();
        view.setText(unresolvedComment.mUnresolved == 0
                ? ctx.getString(R.string.unresolved_comments_zero, unresolvedComment.mTotal)
                : ctx.getString(R.string.unresolved_comments_more,
                        unresolvedComment.mTotal, unresolvedComment.mUnresolved));
        view.setVisibility(View.VISIBLE);
    }

    @BindingAdapter("emptyStateDrawable")
    public static void toEmptyStateDrawable(ImageView v, EmptyState state) {
        if (state == null || state.state == EmptyState.NORMAL_STATE) {
            v.setImageDrawable(null);
        } else if (state.state == EmptyState.NO_RESULTS_STATE) {
            v.setImageDrawable(ContextCompat.getDrawable(
                    v.getContext(), R.drawable.ic_empty_results));
        } else if (state.state == EmptyState.ALL_DONE_STATE) {
            v.setImageDrawable(ContextCompat.getDrawable(
                    v.getContext(), R.drawable.ic_duck));
        } else if (state.state == EmptyState.NOT_CONNECTIVITY_STATE) {
            v.setImageDrawable(ContextCompat.getDrawable(
                    v.getContext(), R.drawable.ic_cloud_off));
        } else if (state.state == EmptyState.SERVER_CANNOT_BE_REACHED) {
            v.setImageDrawable(ContextCompat.getDrawable(
                    v.getContext(), R.drawable.ic_server_network_off));
        } else if (state.state == EmptyState.ERROR_STATE) {
            v.setImageDrawable(ContextCompat.getDrawable(
                    v.getContext(), R.drawable.ic_error_outline));
        } else if (state.state == EmptyState.NO_TRENDING_STATE) {
            v.setImageDrawable(ContextCompat.getDrawable(
                    v.getContext(), R.drawable.ic_vitals));
        } else if (state.state == EmptyState.NO_FOLLOWING_STATE) {
            v.setImageDrawable(ContextCompat.getDrawable(
                    v.getContext(), R.drawable.ic_follow_person));
        } else if (state.state == EmptyState.NO_SELECTION) {
            v.setImageDrawable(ContextCompat.getDrawable(
                    v.getContext(), R.drawable.ic_tap));
        }
    }

    @BindingAdapter("emptyStatedDescription")
    public static void toEmptyStateDescription(TextView v, EmptyState state) {
        if (state == null || state.state == EmptyState.NORMAL_STATE) {
            v.setText(null);
        } else if (state.state == EmptyState.NO_RESULTS_STATE) {
            v.setText(R.string.empty_states_no_results);
        } else if (state.state == EmptyState.ALL_DONE_STATE) {
            v.setText(R.string.empty_states_all_done);
        } else if (state.state == EmptyState.NOT_CONNECTIVITY_STATE) {
            v.setText(R.string.empty_states_not_connectivity);
        } else if (state.state == EmptyState.SERVER_CANNOT_BE_REACHED) {
            v.setText(R.string.empty_states_server_not_reached);
        } else if (state.state == EmptyState.ERROR_STATE) {
            v.setText(R.string.empty_states_error);
        } else if (state.state == EmptyState.NO_TRENDING_STATE) {
            v.setText(R.string.empty_states_no_trending);
        } else if (state.state == EmptyState.NO_FOLLOWING_STATE) {
            v.setText(R.string.empty_states_no_following);
        } else if (state.state == EmptyState.NO_SELECTION) {
            v.setText(R.string.empty_states_no_selection);
        }
    }

    public static boolean hasEmptyStateRetry(int state) {
        return state != EmptyState.NORMAL_STATE
                && state != EmptyState.NO_FOLLOWING_STATE
                && state != EmptyState.NO_SELECTION;
    }

    @BindingAdapter("humanReadableSize")
    public static void toHumanReadableSize(TextView v, Long size) {
        if (size == null) {
            v.setText(null);
            return;
        }
        v.setText(android.text.format.Formatter.formatFileSize(v.getContext(), size));
    }

    public static String toShortenCommit(String commitHash) {
        if (!TextUtils.isEmpty(commitHash) && commitHash.length() > 8) {
            return commitHash.substring(0, 8);
        }
        return commitHash;
    }

    @BindingAdapter("buildStatus")
    public static void toBuildStatus(ImageView v, ContinuousIntegrationInfo.BuildStatus status) {
        if (status == null) {
            v.setImageDrawable(null);
            return;
        }

        switch (status) {
            case SUCCESS:
                v.setImageResource(R.drawable.ic_status_success);
                break;
            case FAILURE:
                v.setImageResource(R.drawable.ic_status_failure);
                break;
            case SKIPPED:
                v.setImageResource(R.drawable.ic_status_skipped);
                break;
            case RUNNING:
            default:
                v.setImageResource(R.drawable.ic_status_running);
                break;
        }
    }

    // ./polygerrit-ui/app/elements/change-list/gr-change-list-item/gr-change-list-item.js
    @BindingAdapter("toCommitSize")
    public static void toCommitSize(TextView v, ChangeInfo change) {
        if (change == null) {
            v.setText(v.getContext().getString(R.string.commit_size_unknown));
            return;
        }

        int delta = change.insertions + change.deletions;
        final int resId;
        if (delta == 0) {
            v.setText(v.getContext().getString(R.string.commit_size_unknown));
            return;
        } else if (delta < 10) {
            resId = R.string.commit_size_xs;
        } else if (delta < 50) {
            resId = R.string.commit_size_s;
        } else if (delta < 250) {
            resId = R.string.commit_size_m;
        } else if (delta < 1000) {
            resId = R.string.commit_size_l;
        } else {
            resId = R.string.commit_size_xl;
        }
        v.setText(String.format(Locale.US, "%s  (+%d, -%d)",
                v.getContext().getString(resId),
                change.insertions,
                change.deletions));
    }

    @BindingAdapter("colorifyReviewedMessage")
    public static void colorifyReviewedMessage(View v, ChangeMessageInfo message) {
        if (message == null || message.message == null) {
            return;
        }
        if (!(sHighlightScoredMessages == Constants.HIGHLIGHT_SCORED_MESSAGE_MESSAGE
                || sHighlightScoredMessages == Constants.HIGHLIGHT_SCORED_MESSAGE_BOTH)) {
            return;
        }

        // Extract every review punctuation
        String firstLine = StringHelper.firstLine(message.message);
        int review = 0;
        boolean isPatchSetLine = StringHelper.PATCHSET_LINE_PATTERN.matcher(firstLine).matches();
        if (isPatchSetLine && !firstLine.contains(".")) {
            int start = firstLine.indexOf(": ") + 1;
            Matcher m = StringHelper.VOTE_PATTERN.matcher(firstLine);
            while (m.find()) {
                if (m.group(3) != null && m.start() == start) {
                    int value = StringHelper.parseNumberWithSign(m.group(3)).intValue();
                    if (Math.abs(value) > Math.abs(review)) {
                        review = value;
                    } else if (Math.abs(value) == Math.abs(review) && value < 0) {
                        review = value;
                    }
                    start = m.end();
                } else if (m.group(4) != null) {
                    start = m.end();
                }
            }
        }

        int color = android.R.color.transparent;
        if (review < 0) {
            color = R.color.messageWithNegativeReview;
        }
        if (review > 0) {
            color = R.color.messageWithPositiveReview;
        }
        v.setBackgroundColor(ContextCompat.getColor(v.getContext(), color));
    }

    @BindingAdapter("resolveAttachmentIcon")
    public static void resolveAttachmentIcon(ImageView v, Attachment attachment) {
        if (attachment == null) {
            v.setImageDrawable(null);
            return;
        }

        String mimetype = attachment.mMimeType;
        if ("application/octet-stream".equals(attachment.mMimeType)) {
            attachment.mMimeType = StringHelper.getMimeType(new File(attachment.mName));
        }

        @DrawableRes int resource;
        @ColorRes int color;
        if (mimetype.equals("text/xml") || mimetype.equals("application/xml")
                || mimetype.contains("+xml")) {
            resource = R.drawable.ic_mime_xml;
            color = R.color.mime_type_default;
        } else if (mimetype.startsWith("image/")) {
            resource = R.drawable.ic_mime_image;
            color = R.color.mime_type_default;
        } else if (mimetype.startsWith("video/")) {
            resource = R.drawable.ic_mime_video;
            color = R.color.mime_type_default;
        } else if (mimetype.startsWith("audio/")) {
            resource = R.drawable.ic_mime_audio;
            color = R.color.mime_type_default;
        } else if (mimetype.startsWith("text/")) {
            resource = R.drawable.ic_mime_document;
            color = R.color.mime_type_default;
        } else if (mimetype.equals("application/internet-shortcut")
                || mimetype.equals("application/x-url")) {
            resource = R.drawable.ic_mime_url;
            color = R.color.mime_type_default;
        } else if (mimetype.contains("excel") || mimetype.contains("xls")
                || mimetype.contains("spreadsheet")) {
            resource = R.drawable.ic_mime_excel;
            color = R.color.mime_type_excel;
        } else if (mimetype.contains("word")) {
            resource = R.drawable.ic_mime_word;
            color = R.color.mime_type_word;
        } else if (mimetype.contains("powerpoint")) {
            resource = R.drawable.ic_mime_powerpoint;
            color = R.color.mime_type_powerpoint;
        } else if (mimetype.contains("pdf")) {
            resource = R.drawable.ic_mime_pdf;
            color = R.color.mime_type_pdf;
        } else {
            resource = R.drawable.ic_mime_file;
            color = R.color.mime_type_default;
        }

        Drawable dw = ContextCompat.getDrawable(v.getContext(), resource);
        v.setImageDrawable(BitmapUtils.tintDrawable(v.getResources(), dw,
                ContextCompat.getColor(v.getContext(), color)));
    }

    @BindingAdapter("bindToVersion")
    public static void bindToVersion(View v, double version) {
        v.setVisibility(ModelHelper.isEqualsOrGreaterVersionThan(mAccount, version)
                ? View.VISIBLE : View.GONE);
    }

    private static String toReviewUpdateMessage(
            Context ctx, List<ReviewerUpdateInfo> updates, ReviewerStatus state, boolean newLine) {
        boolean first = true;
        StringBuilder sb = new StringBuilder();
        for (ReviewerUpdateInfo update : updates) {
            if (state.equals(update._extendedState)) {
                if (first) {
                    if (newLine) {
                        sb.append("
");
                    }
                    sb.append(ctx.getResources().getStringArray(
                            R.array.reviewer_update_states)[state.ordinal()]);
                    sb.append(" ");
                } else {
                    sb.append(", ");
                }
                sb.append("").append(toAccountDisplayName(update.reviewer)).append("");
                first = false;
            }
        }
        return sb.toString();
    }

    private static void highlightUserMessageReviewScores(
            Context context, String userMessage, Spannable spannable) {
        if (!(sHighlightScoredMessages == Constants.HIGHLIGHT_SCORED_MESSAGE_SCORE
                || sHighlightScoredMessages == Constants.HIGHLIGHT_SCORED_MESSAGE_BOTH)) {
            return;
        }

        final int approved = ContextCompat.getColor(context, R.color.approved);
        final int rejected = ContextCompat.getColor(context, R.color.rejected);
        final int noscore = ContextCompat.getColor(context, R.color.noscore);

        boolean isPatchSetLine = StringHelper.PATCHSET_LINE_PATTERN.matcher(userMessage).matches();
        if (isPatchSetLine && !userMessage.contains(".")) {
            Matcher m = StringHelper.VOTE_PATTERN.matcher(userMessage);
            int start = userMessage.indexOf(": ") + 1;
            while (m.find()) {
                if (m.start() == start) {
                    int color = 0;
                    if (m.group(3) != null) {
                        // Vote added
                        color = StringHelper.parseNumberWithSign(m.group(3)).intValue() > 0
                                ? approved : rejected;
                    } else if (m.group(4) != null) {
                        // Vote removed
                        color = noscore;
                    }

                    final TagSpan span = new TagSpan(context, color, Color.WHITE);
                    spannable.setSpan(span, m.start(2), m.end(2), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                start = m.end();
            }
        }
    }
}


text:
<!DOCTYPE html>

		<title>three.js webgl - geometry - NURBS</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

		<canvas id="debug" style="position:absolute; left:100px"></canvas>

three.js - NURBS curve and surface example

redpajama_set_name: RedPajamaGithub


text:
simplehttpclient
================

a simple c++ http client


text:
import {Page, NavController} from 'ionic-angular';
import {ValuesPipe} from '../../comon/pipes';
import {PouchSynchroPage} from './pouch-synchro/pouch-synchro';
import {PouchEditPage} from './pouch-edit/pouch-edit';
import {PouchParamPage} from './pouch-param/pouch-param';

declare var PouchDB: any;
/*
  Generated class for the PouchDbPage page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Page({
  templateUrl: 'build/pages/api/pouch-db/pouch-db.html',
  pipes: [ValuesPipe]
})
export class PouchDbPage {
  tab1: any;
  tab2: any;
  tab3: any;
  constructor(public nav: NavController) {
    this.tab1 = PouchSynchroPage;
    this.tab2 = PouchEditPage;
    this.tab3 = PouchParamPage;
  }
}


text:
$(document).ready(function() {
    // $('.navigation').load('nav.html');
});

$(document).delegate('*[data-toggle="lightbox"]', 'click', function(event) {
    event.preventDefault();
    $(this).ekkoLightbox();
});


text:
package com.hotmail.kalebmarc.textfighter.main;

class Start {

    public static void main(String[] args) {

        if (args.length != 0 && args[0].equalsIgnoreCase("nogui")) Ui.guiEnabled = false;
        Ui.println("Loading..");

        //Check if current version is a developer version, if so, enable debug menu
        if (Version.get().contains("DEV")) {
            Debug.enable();
        }

        //Runs the game
        Menu menu = new Menu();
        menu.load();

        //Clears Console
        Ui.cls();

    }
}

/*
 *
 * To create new enemies:
 *    First, create enemy object at the top of the com.hotmail.kalebmarc.textfighter.Game class.
 *    Change the properties in the com.hotmail.kalebmarc.player.Settings class, in the setConstants method.
 *    Remember to set both easy, and hard properties. Formatting information is given
 *    above all the enemy initializations in setConstants. To edit existing properties,
 *    simply change the values in the same setConstants method. This should automatically
 *    create everything needed; including achievements, and a help section for that enemy.
 *
 * To create new weapons:
 *    Pretty much the same as creating a new enemy. Create the object at the top of the
 *    com.hotmail.kalebmarc.textfighter.Game class. Change the properties in the com.hotmail.kalebmarc.player.Settings class. There's
 *    two different formatting options for the parameters. One for melee, one for a gun.
 *    More information is given in the com.hotmail.kalebmarc.player.Settings class above the section with the rest
 *    of the weapon initializations. Make sure to add both easy, and hard difficulty inits.
 *    You can change pre-existing weapon properties without causing any problems.
 *
 */


text:
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var minifyCss = require('gulp-minify-css');
var del = require('del');
var webpack = require('webpack-stream')

var jsPaths = 'src/router.js';
var destJs = 'build/m.js';
var cssPath = 'src/m.css';
var cssAniPath = 'src/m.animate.css';

gulp.task('clean', function(cb) {
  del(['build'], cb);
});

gulp.task('scripts', ['clean'], function() {
  return gulp.src(jsPaths)
    .pipe(webpack({
      output: {
        filename: 'm.js',
        library: 'M',
        libraryTarget: 'umd'
      }
    }))
    .pipe(gulp.dest('build/'));
});

gulp.task('minscripts', ['scripts'], function() {
  return gulp.src(destJs)
    .pipe(concat('m.min.js'))
    .pipe(uglify({
      mangle: {
        except: ['require', 'exports', 'module']
      }
    }))
    .pipe(gulp.dest('build/'));
});

gulp.task('css', ['clean'], function() {
  return gulp.src(cssPath)
    .pipe(minifyCss())
    .pipe(gulp.dest('build/'));
});

gulp.task('cssAni', ['clean'], function() {
  return gulp.src(cssAniPath)
    .pipe(minifyCss())
    .pipe(gulp.dest('build/'));
});

gulp.task('default', ['minscripts', 'css', 'cssAni']);


text:
.class Lcom/google/inject/matcher/Matchers$IdenticalTo;
.super Lcom/google/inject/matcher/AbstractMatcher;
.source "Matchers.java"

# interfaces
.implements Ljava/io/Serializable;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/google/inject/matcher/Matchers;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "IdenticalTo"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Lcom/google/inject/matcher/AbstractMatcher",
        "<",
        "Ljava/lang/Object;",
        ">;",
        "Ljava/io/Serializable;"
    }
.end annotation

# static fields
.field private static final serialVersionUID:J

# instance fields
.field private final value:Ljava/lang/Object;

# direct methods
.method public constructor <init>(Ljava/lang/Object;)V
    .locals 1
    .param p1, "value"    # Ljava/lang/Object;

    .prologue
    .line 261
    invoke-direct {p0}, Lcom/google/inject/matcher/AbstractMatcher;-><init>()V

    .line 262
    const-string v0, "value"

    invoke-static {p1, v0}, Lcom/google/inject/internal/util/$Preconditions;->checkNotNull(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    iput-object v0, p0, Lcom/google/inject/matcher/Matchers$IdenticalTo;->value:Ljava/lang/Object;

    .line 263
    return-void
.end method

# virtual methods
.method public equals(Ljava/lang/Object;)Z
    .locals 2
    .param p1, "other"    # Ljava/lang/Object;

    .prologue
    .line 270
    instance-of v0, p1, Lcom/google/inject/matcher/Matchers$IdenticalTo;

    if-eqz v0, :cond_0

    check-cast p1, Lcom/google/inject/matcher/Matchers$IdenticalTo;

    .end local p1    # "other":Ljava/lang/Object;
    iget-object v0, p1, Lcom/google/inject/matcher/Matchers$IdenticalTo;->value:Ljava/lang/Object;

    iget-object v1, p0, Lcom/google/inject/matcher/Matchers$IdenticalTo;->value:Ljava/lang/Object;

    if-ne v0, v1, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public hashCode()I
    .locals 1

    .prologue
    .line 275
    iget-object v0, p0, Lcom/google/inject/matcher/Matchers$IdenticalTo;->value:Ljava/lang/Object;

    invoke-static {v0}, Ljava/lang/System;->identityHashCode(Ljava/lang/Object;)I

    move-result v0

    mul-int/lit8 v0, v0, 0x25

    return v0
.end method

.method public matches(Ljava/lang/Object;)Z
    .locals 1
    .param p1, "other"    # Ljava/lang/Object;

    .prologue
    .line 266
    iget-object v0, p0, Lcom/google/inject/matcher/Matchers$IdenticalTo;->value:Ljava/lang/Object;

    if-ne v0, p1, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public toString()Ljava/lang/String;
    .locals 2

    .prologue
    .line 279
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    const-string v1, "identicalTo("

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget-object v1, p0, Lcom/google/inject/matcher/Matchers$IdenticalTo;->value:Ljava/lang/Object;

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, ")"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method


text:
node-gyp-counter
================

An unscientific exploration of how node-gyp is being used in the node.js ecosystem.

## How to install

NPM is your friend:

```bash
$ npm install node-gyp-counter
```

Although generally one suspects package.json is preferable.

## How to use
Take a look at tests/tests.js for an example. There are really just two key functions and they are in index.js.

```javascript
var nodeGypCounter = require("node-gyp-counter");
var npmUtilities = require("node-gyp-counter/lib/npmUtilities");

nodeGypCounter.downloadAndDisplayData("localNpmDBName", "npmStatCache", npmUtilities.skimDbUrl);
```

This will output to the console a few statistics about node-gyp usage in NPM. You can also call
downloadGenerateIndexAndAnalyze with the same arguments and get back a JSON object with the raw data.

## Q&A
### The code doesn't seem very friendly, it eats up the main thread!
This code was really written as a canned query not as anything that would be run on an actual production server. I just
load it up on my local node.js instance and run. So I have spent no time worrying about making it friendly to any code
it shares the node.js server with.

### How correct is the code?
You may have noticed that there is literally no testing, at all, anywhere. Who knows what horrific
programming errors I have committed?

But wait, it gets worse! You see I didn't have a fully reliable way to figure out which packages use node-gyp. So I
built a heuristic instead. The reason is that to be really sure which packages use node-gyp I would have to download
and install, well, all packages. That turns out to involve terabytes of downloads and um... no. So instead I look for
things like install scripts or gyp flags. Again, not terribly scientific.

### How correct is the analysis?
Oy... where to begin? I decided for no good reason to only look at the latest versions of projects. So if a project did
use node-gyp and doesn't anymore I'll miss it. I only use the previous month's data for download stats. So a project
that hasn't had a recent release and so doesn't have a lot of updates could easily be undercounted. I allow in projects
with broken dependencies for no good reason at all (presumably their downloads are low since they shouldn't work). Etc.

### How long should it take to download all the data?
A long, long time. PouchDB seems pretty glacial. It took me 54 minutes to download
the NPM package database. By comparison CouchDB synch'd the same data in 20 minutes. I hope to eventually track down
and fix these problems (I have suspicions about what the problem is) but in the meantime, patience is a virtue.

### How do I run tests?
What tests? O.k. there is one test. I just use that because Mocha is easy to run in Intellij. But really, there are
no tests.

### Why do you use the skimdb.npmjs.com URL rather than skimdb.iriscouch.com?
In theory iriscouch is faster, especially because it doesn't use HTTPS. But in practice I've had endless problems with
node.js timing out trying to connect to iriscouch. Iriscouch does appear to be up and working but in examining
connection times it does take quite a while to establish a connection. I think this time exceeds node.js's patience
and I have not found a way to configure node.js's behavior. Note that the timeout option on things like request is
about how long to wait for data, not for the TCP handshake.


text:
package com.google.gerrit.client.changes;

import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.NotFoundScreen;
import com.google.gerrit.client.info.ChangeInfo;
import com.google.gerrit.client.rpc.Natives;
import com.google.gerrit.client.rpc.ScreenLoadCallback;
import com.google.gerrit.client.ui.InlineHyperlink;
import com.google.gerrit.client.ui.Screen;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.extensions.client.ListChangesOption;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwtexpui.globalkey.client.KeyCommand;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.Set;

public class AccountDashboardScreen extends Screen implements ChangeListScreen {
  // If changing default options, also update in
  // ChangeIT#defaultSearchDoesNotTouchDatabase().
  private static final Set<ListChangesOption> MY_DASHBOARD_OPTIONS;

  static {
    EnumSet<ListChangesOption> options = EnumSet.copyOf(ChangeTable.OPTIONS);
    options.add(ListChangesOption.REVIEWED);
    MY_DASHBOARD_OPTIONS = Collections.unmodifiableSet(options);
  }

  private final Account.Id ownerId;
  private final boolean mine;
  private ChangeTable table;
  private ChangeTable.Section workInProgress;
  private ChangeTable.Section outgoing;
  private ChangeTable.Section incoming;
  private ChangeTable.Section closed;

  public AccountDashboardScreen(Account.Id id) {
    ownerId = id;
    mine = Gerrit.isSignedIn() && ownerId.equals(Gerrit.getUserAccount().getId());
  }

  @Override
  protected void onInitUI() {
    super.onInitUI();
    table =
        new ChangeTable() {
          {
            keysNavigation.add(
                new KeyCommand(0, 'R', Util.C.keyReloadSearch()) {
                  @Override
                  public void onKeyPress(KeyPressEvent event) {
                    Gerrit.display(getToken());
                  }
                });
          }
        };
    table.addStyleName(Gerrit.RESOURCES.css().accountDashboard());

    workInProgress = new ChangeTable.Section();
    outgoing = new ChangeTable.Section();
    incoming = new ChangeTable.Section();
    closed = new ChangeTable.Section();

    String who = mine ? "self" : ownerId.toString();
    workInProgress.setTitleWidget(
        new InlineHyperlink(
            Util.C.workInProgress(), PageLinks.toChangeQuery(queryWorkInProgress(who))));
    outgoing.setTitleWidget(
        new InlineHyperlink(Util.C.outgoingReviews(), PageLinks.toChangeQuery(queryOutgoing(who))));
    incoming.setTitleWidget(
        new InlineHyperlink(Util.C.incomingReviews(), PageLinks.toChangeQuery(queryIncoming(who))));
    incoming.setHighlightUnreviewed(mine);
    closed.setTitleWidget(
        new InlineHyperlink(Util.C.recentlyClosed(), PageLinks.toChangeQuery(queryClosed(who))));

    table.addSection(workInProgress);
    table.addSection(outgoing);
    table.addSection(incoming);
    table.addSection(closed);
    add(table);
    table.setSavePointerId("owner:" + ownerId);
  }

  private static String queryWorkInProgress(String who) {
    return "is:open is:wip owner:" + who;
  }

  private static String queryOutgoing(String who) {
    return "is:open -is:wip owner:" + who;
  }

  private static String queryIncoming(String who) {
    return "is:open ((reviewer:"
        + who
        + " -owner:"
        + who
        + " -is:ignored) OR assignee:"
        + who
        + ")";
  }

  private static String queryClosed(String who) {
    return "is:closed (owner:" + who + " OR reviewer:" + who + " OR assignee:" + who + ")";
  }

  @Override
  protected void onLoad() {
    super.onLoad();

    String who = mine ? "self" : ownerId.toString();
    ChangeList.queryMultiple(
        new ScreenLoadCallback<JsArray<ChangeList>>(this) {
          @Override
          protected void preDisplay(JsArray<ChangeList> result) {
            display(result);
          }
        },
        mine ? MY_DASHBOARD_OPTIONS : DashboardTable.OPTIONS,
        queryWorkInProgress(who),
        queryOutgoing(who),
        queryIncoming(who),
        queryClosed(who) + " -age:4w limit:10");
  }

  @Override
  public void registerKeys() {
    super.registerKeys();
    table.setRegisterKeys(true);
  }

  private void display(JsArray<ChangeList> result) {
    if (!mine && !hasChanges(result)) {
      // When no results are returned and the data is not for the
      // current user, the target user is presumed to not exist.
      Gerrit.display(getToken(), new NotFoundScreen());
      return;
    }

    ChangeList wip = result.get(0);
    ChangeList out = result.get(1);
    ChangeList in = result.get(2);
    ChangeList done = result.get(3);

    if (mine) {
      setWindowTitle(Util.C.myDashboardTitle());
      setPageTitle(Util.C.myDashboardTitle());
    } else {
      // The server doesn't tell us who the dashboard is for. Try to guess
      // by looking at a change started by the owner and extract the name.
      String name = guessName(out);
      if (name == null) {
        name = guessName(done);
      }
      if (name != null) {
        setWindowTitle(name);
        setPageTitle(Util.M.accountDashboardTitle(name));
      } else {
        setWindowTitle(Util.C.unknownDashboardTitle());
        setWindowTitle(Util.C.unknownDashboardTitle());
      }
    }

    Collections.sort(Natives.asList(out), outComparator());

    table.updateColumnsForLabels(wip, out, in, done);
    workInProgress.display(wip);
    outgoing.display(out);
    incoming.display(in);
    closed.display(done);
    table.finishDisplay();
  }

  private Comparator<ChangeInfo> outComparator() {
    return new Comparator<ChangeInfo>() {
      @Override
      public int compare(ChangeInfo a, ChangeInfo b) {
        int cmp = a.created().compareTo(b.created());
        if (cmp != 0) {
          return cmp;
        }
        return a._number() - b._number();
      }
    };
  }

  private boolean hasChanges(JsArray<ChangeList> result) {
    for (ChangeList list : Natives.asList(result)) {
      if (list.length() != 0) {
        return true;
      }
    }
    return false;
  }

  private static String guessName(ChangeList list) {
    for (ChangeInfo change : Natives.asList(list)) {
      if (change.owner() != null && change.owner().name() != null) {
        return change.owner().name();
      }
    }
    return null;
  }
}


text:
from sqlalchemy import BigInteger, Boolean, Column, String
from sqlalchemy.orm import relationship, object_session

from app.database.base_model import Base
from app.models.pending_actions import PendingAction
from app.models.relationships import group_members

class User(Base):
    __tablename__ = 'users'

    id = Column(BigInteger, primary_key=True)
    login = Column(String)
    name = Column(String, nullable=False)

    is_mute_enabled = Column(Boolean, nullable=False, default=False)
    is_known = Column(Boolean, nullable=False, default=False)
    locale = Column(String, nullable=True)

    groups = relationship("Group", secondary=group_members, back_populates='users')
    requests = relationship("Request")
    responses = relationship("Response")
    pending_actions = relationship("PendingAction")

    def mention_name(self):
        return '@' + self.login if self.login else self.name

    def _maybe_find_pending_action(self, chat_id: int) -> PendingAction:
        for pending_action in self.pending_actions:
            if pending_action.chat_id == chat_id:
                return pending_action
        return None

    def _update_existing_action(self, pending_action: PendingAction, action_string: str) -> bool:
        if not action_string:
            object_session(self).delete(pending_action)
        elif pending_action.action != action_string:
            pending_action.action = action_string
        else:
            return False
        return True

    # Returns previous pending action string (if any).
    def reset_pending_action(self, action_string: str, chat_id: int) -> str:
        existing_action = self._maybe_find_pending_action(chat_id)
        if existing_action:
            previous_action_string = existing_action.action
            if self._update_existing_action(existing_action, action_string):
                return previous_action_string
        elif action_string:
            self.pending_actions.append(PendingAction(user_id=self.id, chat_id=chat_id, action=action_string))
        return ''


text:
package com.sm.store;

import com.sm.message.Request;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.channel.*;

import java.util.concurrent.*;

public class AppSyncHandler extends SimpleChannelUpstreamHandler {
    private static final Log logger = LogFactory.getLog(AppSyncHandler.class);

    private int maxThreads;
    private int maxQueue ;
    private Executor threadPools;

    public AppSyncHandler(int maxThreads, int maxQueue) {
        this.maxThreads = maxThreads;
        this.maxQueue = maxQueue;
        init();
    }

    private void init() {

        BlockingQueue<Runnable> queue= new LinkedBlockingQueue<Runnable>(maxQueue );
        threadPools = new ThreadPoolExecutor( maxThreads, maxThreads , 30, TimeUnit.SECONDS , queue );
    }

    @Override
    public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
      // Let SimpleChannelHandler call actual event handler methods below.
      super.handleUpstream(ctx, e);
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
      Request req =  (Request) e.getMessage();
      logger.info("receive " + req.toString()+" from "+e.getRemoteAddress().toString());
      // it might need to create a different copy
      threadPools.execute(new SyncCall(req, ctx));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
      // Close the connection when an exception is raised.
      logger.error( e.getCause().getMessage(), e.getCause() );
      e.getChannel().close();
    }

    public class SyncCall implements Runnable, SyncCallback {
        private Request request;
        private ChannelHandlerContext ctx;

        public SyncCall(Request request, ChannelHandlerContext ctx) {
            this.request = request;
            this.ctx = ctx;
        }

        @Override
        public void processRequest(Request request, ChannelHandlerContext ctx) {
            Request req = new Request(request.getHeader(), request.getHeader().toByte() ,  Request.RequestType.Response  );
            logger.info("write "+req.getHeader().toString() );
            ctx.getChannel().write(request);
        }

        @Override
        public void run() {
            try {
                //Thread.sleep( 100L);
                processRequest(request, ctx);
            } catch ( Exception ex) {
                // swallow exception
                logger.error( ex.getMessage(), ex);
            }

        }
    }

}


text:
import os, shutil, pickle, datetime

from multiprocessing import Pool, cpu_count
from matplotlib      import pyplot, path, patches
from shapefile       import Reader

def inside_box(p1, p2, p3, space = 0):
    """Checks if p3 is inside a box formed by p1 and p2."""

    if p1[0] < p3[0] and p3[0] < p2[0] or p1[0] > p3[0] and p3[0] > p2[0]:

        # x value is inside

        if p1[1] < p3[1] and p3[1] < p2[1] or p1[1] > p3[1] and p3[1] > p2[1]:

            # y value is inside

            return True

        else: return False

def get_boundaries(shapes, space = 0.1):
    """Gets the boundaries for the plot."""

    boundaries = shapes[0].bbox
    for shape in shapes[0:]:
        b = shape.bbox
        if b[0] < boundaries[0]: boundaries[0] = b[0]
        if b[1] < boundaries[1]: boundaries[1] = b[1]
        if b[2] > boundaries[2]: boundaries[2] = b[2]
        if b[3] > boundaries[3]: boundaries[3] = b[3]

    xmin = boundaries[0] - (boundaries[2] - boundaries[0]) * space
    ymin = boundaries[1] - (boundaries[3] - boundaries[1]) * space
    xmax = boundaries[2] + (boundaries[2] - boundaries[0]) * space
    ymax = boundaries[3] + (boundaries[3] - boundaries[1]) * space

    return xmin, ymin, xmax, ymax

def make_patch(points, facecolor, edgecolor = 'Black', width = 1, alpha = None,
               hatch = None, label = None):
    """Uses a list or array of points to generate a matplotlib patch."""

    vertices = [(point[0], point[1]) for point in points]
    vertices.append((points[0][0], points[0][1]))

    codes     = [path.Path.LINETO for i in range(len(points) + 1)]
    codes[0]  = path.Path.MOVETO

    patch = patches.PathPatch(path.Path(vertices, codes), facecolor = facecolor,
                              edgecolor = edgecolor, lw = width, hatch = hatch,
                              alpha = alpha, label = label)
    return patch

def plot_NRCM(lons, lats, bfile = None, sfile = None, space = 0.05,
              show = False, output = None):

    fig = pyplot.figure()

    sub = fig.add_subplot(111, aspect = 'equal')
    sub.set_title('Nested Regional Climate Model Grid Points')
    sub.scatter(lons, lats, marker = '+', c = 'r', s = 40)

    if bfile is not None:

        sf = Reader(bfile)
        boundary = sf.shape(0).points
        sub.add_patch(make_patch(boundary, (1, 0, 0, 0), width = 1.2))

    if sfile is not None:

        sf = Reader(sfile)

        for s in sf.shapes():
            boundary = s.points
            sub.add_patch(make_patch(boundary, (1, 0, 0, 0), width = 0.2))

    sub.set_xlabel('Longitude, Decimal Degrees', size = 13)
    sub.set_ylabel('Latitude, Decimal Degrees', size = 13)

    xmin, ymin, xmax, ymax = get_boundaries(sf.shapes(), space = space)

    pyplot.xlim([xmin, xmax])
    pyplot.ylim([ymin, ymax])

    if output is not None: pyplot.savefig(output)

    if show: pyplot.show()

    pyplot.clf()
    pyplot.close()

def extract_raw(source, destination, HUC8, plot = True, show = False,
                save = True, verbose = True):
    """Extracts the grid data for the HUC8."""

    if verbose: print('extracting NRCM predictions...\n')

    # make a new directory for the HUC8

    d = '{}/{}/NRCM'.format(destination, HUC8)

    if not os.path.isdir(d): os.mkdir(d)

    # make a "raw directory" for the unaltered info

    raw = '{}/raw'.format(d)

    if not os.path.isdir(raw): os.mkdir(raw)

    # use the boundary file to find the bounding box for the grid points

    boundaryfile = '{0}/{1}/{1}boundaries'.format(destination, HUC8)
    subbasinfile = '{0}/{1}/{1}subbasins'.format(destination, HUC8)
    space        = 0.1

    sf = Reader(boundaryfile)

    bbox = get_boundaries(sf.shapes(), space = space)

    xmin, ymin, xmax, ymax = bbox

    if verbose: print('bounding box =', xmin, ymin, xmax, ymax, '\n')

    lats, lons = [], []
    for f in os.listdir(source):
        i = f.index('_')
        lon = float(f[:i])
        lat = float(f[i+1:])

        if inside_box([xmin, ymin], [xmax, ymax], [lon, lat]):
            lats.append(lat)
            lons.append(lon)

            if not os.path.isfile('{}/{}'.format(raw, f)):
                print('copying {}'.format(f))
                shutil.copy('{}/{}'.format(source, f), '{}/{}'.format(raw, f))

    if plot:
        if save: output = '{}/gridpoints'.format(d)
        else:    output = None
        if not os.path.isfile(output):
            plot_NRCM(lons, lats, bfile = boundaryfile, sfile = subbasinfile,
                      output = output, show = show)

def extract_timeseries(directory, start, end,
                       series = ['rain', 'temperature', 'wind', 'humidity',
                                 'solar', 'snowdepth', 'evaporation']):

    source = '{}/raw'.format(directory)

    gridfiles = [os.path.join(source, f) for f in os.listdir(source)]

    for ts in series:

        destination = '{}/{}'.format(directory, ts)
        if not os.path.isdir(destination):
            os.mkdir(destination)

    # iterate through the grid point data files

    for f in gridfiles:

        print('re-organizing {}'.format(f))

        if any([not os.path.isfile('{}/{}/{}'.format(directory, ts, f))
                for f in os.listdir(source)]):

            with open(f, 'rb') as p: g = pickle.load(p)

            # dump each time series and get rid of time zone info

            for ts in series:

                data = [(datetime.datetime(t.year, t.month, t.day, t.hour), v)
                        for t, v in g.data[ts]]
                data = [(t, v) for t, v in data if start <= t and t < end]

                it = directory, ts, g.lon, g.lat

                destination = '{}/{}/{:8.4f}_{:7.4f}'.format(*it)

                if not os.path.isfile(destination):
                    with open(destination, 'wb') as f: pickle.dump(data, f)

if __name__ == '__main__':

    if os.name == 'nt':
        source      = 'c:/hspf_data/NRCM/gridpoints'
        destination = 'c:/hspf_data'
    elif os.name == 'posix':
        source      = '/home/dave/HSPF_data/NRCM/gridpoints'
        destination = '/home/dave/HSPF_data'

    HUC8        = '07080106'
    plot        = True
    show        = False

    d = '{}/{}/NRCM/raw'.format(destination, HUC8)

    if not os.path.isdir(d):
        extract_raw(source, destination, HUC8, plot = plot, show = show)

    start       = 1985
    end         = 2005

    s = datetime.datetime(start, 1, 1)
    e = datetime.datetime(end,   1, 1)

    d = '{}/{}/NRCM'.format(destination, HUC8)

    if not any([os.path.isdir('{}/{}'.format(d, ts))
                for ts in ['rain', 'snowdepth', 'temperature', 'humidity',
                           'wind', 'solar', 'evaporation']]):
        extract_timeseries(d, s, e)


text:
require 'fog'

module S3rbsync
  class Synchronizer

    def initialize(configure, directory = nil)
      @configure = configure
      @local_dir = directory
      @s3 = Fog::Storage.new(:provider              => 'AWS',
                             :aws_access_key_id     => @configure.access_key,
                             :aws_secret_access_key => @configure.secret_key,
                             :region                => (@configure.region || 'ap-northeast-1'),
                             :persistent            => false )
      @bucket = @s3.directories.get(@configure.bucket_name)
      @queue = Queue.new
    rescue => e
      puts "----- Error -----"
      puts e.message
      exit 1
    end

    def connected?
      !!@bucket
    end

    def sync!
      # puts '...call sync!'
      upload_files(@local_dir)
    end

    private

    def upload_files(dir)
      upload_in_directory(dir)
      recursive_upload
    end

    def recursive_upload
      upload_in_directory(@queue.pop, :recursible => true) until @queue.empty?
    end

    def upload_in_directory(dir, options={})
      Dir.entries(dir).each do |file|
        next if file.start_with?('.')

        file_name = options[:recursible] ? File.join(dir, file) : file
        if File.directory?(file_name)
          @queue.push(file_name)
        else
          upload!(file_name)
        end
      end
    end

    def upload!(file_name)
      remote_file = get_remote_file(file_name)
      return if remote_file && (not modified?(file_name, remote_file))
      remote_file.destroy if remote_file && modified?(file_name, remote_file)
      @bucket.files.create(:key => "#{file_name}", :body => open(file_name), :public => false)
      puts "copied #{file_name}"
    end

    def get_remote_file(file_name)
      @bucket.files.get(file_name)
    end

    def modified?(local_file, remote_file)
      # puts "verifying file: #{local_file}"
      return true unless remote_file
      File.mtime(local_file) > remote_file.last_modified
    end

  end
end


text:
namespace openscreen {
namespace discovery {

MdnsProbe::MdnsProbe(DomainName target_name, IPAddress address)
    : target_name_(std::move(target_name)),
      address_(std::move(address)),
      address_record_(CreateAddressRecord(target_name_, address_)) {}

MdnsProbe::~MdnsProbe() = default;

MdnsProbeImpl::Observer::~Observer() = default;

MdnsProbeImpl::MdnsProbeImpl(MdnsSender* sender,
                             MdnsReceiver* receiver,
                             MdnsRandom* random_delay,
                             TaskRunner* task_runner,
                             ClockNowFunctionPtr now_function,
                             Observer* observer,
                             DomainName target_name,
                             IPAddress address)
    : MdnsProbe(std::move(target_name), std::move(address)),
      random_delay_(random_delay),
      task_runner_(task_runner),
      now_function_(now_function),
      alarm_(now_function_, task_runner_),
      sender_(sender),
      receiver_(receiver),
      observer_(observer) {
  OSP_DCHECK(sender_);
  OSP_DCHECK(receiver_);
  OSP_DCHECK(random_delay_);
  OSP_DCHECK(task_runner_);
  OSP_DCHECK(observer_);

  receiver_->AddResponseCallback(this);
  alarm_.ScheduleFromNow([this]() { ProbeOnce(); },
                         random_delay_->GetInitialProbeDelay());
}

MdnsProbeImpl::~MdnsProbeImpl() {
  OSP_DCHECK(task_runner_->IsRunningOnTaskRunner());

  Stop();
}

void MdnsProbeImpl::ProbeOnce() {
  OSP_DCHECK(task_runner_->IsRunningOnTaskRunner());

  if (successful_probe_queries_++ < kProbeIterationCountBeforeSuccess) {
    // MdnsQuerier cannot be used, because probe queries cannot use the cache,
    // so instead directly send the query through the MdnsSender.
    MdnsMessage probe_query(CreateMessageId(), MessageType::Query);
    MdnsQuestion probe_question(target_name(), DnsType::kANY, DnsClass::kIN,
                                ResponseType::kUnicast);
    probe_query.AddQuestion(probe_question);
    probe_query.AddAuthorityRecord(address_record());
    sender_->SendMulticast(probe_query);

    alarm_.ScheduleFromNow([this]() { ProbeOnce(); },
                           kDelayBetweenProbeQueries);
  } else {
    Stop();
    observer_->OnProbeSuccess(this);
  }
}

void MdnsProbeImpl::Stop() {
  OSP_DCHECK(task_runner_->IsRunningOnTaskRunner());

  if (is_running_) {
    alarm_.Cancel();
    receiver_->RemoveResponseCallback(this);
    is_running_ = false;
  }
}

void MdnsProbeImpl::Postpone(std::chrono::seconds delay) {
  OSP_DCHECK(task_runner_->IsRunningOnTaskRunner());

  successful_probe_queries_ = 0;
  alarm_.Cancel();
  alarm_.ScheduleFromNow([this]() { ProbeOnce(); },
                         std::chrono::duration_cast<Clock::duration>(delay));
}

void MdnsProbeImpl::OnMessageReceived(const MdnsMessage& message) {
  OSP_DCHECK(task_runner_->IsRunningOnTaskRunner());
  OSP_DCHECK(message.type() == MessageType::Response);

  for (const auto& record : message.answers()) {
    if (record.name() == target_name()) {
      Stop();
      observer_->OnProbeFailure(this);
    }
  }
}

}  // namespace discovery
}  // namespace openscreen


text:
package com.example.deephouse;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity
{
	public final static String EXTRA_MESSAGE = "com.example.deephouse.MESSAGE";
	public static final String PREFS_NAME = "DeepHousePrefs";

	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		if (savedInstanceState == null)
		{
			getFragmentManager().beginTransaction()
			.add(R.id.container, new PlaceholderFragment())
			.commit();
		}

		restoreLoginInfos();
		getActionBar().hide();
	}

	private void restoreLoginInfos()
	{
		SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
		String ip = settings.getString("ip","");
		String login = settings.getString("login", "");
		String password = settings.getString("password","");
		final TextView textViewIp = (TextView) findViewById(R.id.editTextIP);
		final TextView textViewLogin = (TextView) findViewById(R.id.editTextLogin);
		final TextView textViewPassword = (TextView) findViewById(R.id.editTextPassword);
		if (!ip.equals("") || !login.equals("") || !password.equals(""))
		{
			textViewIp.setText(ip);
			textViewLogin.setText(login);
			textViewPassword.setText(password);
			//Try connecting with the infos
			connexion(findViewById(0));
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		if(item.getItemId() == R.id.action_settings)
			return true;
		else
			return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment
	{
		public PlaceholderFragment()
		{

		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
		{
			View rootView = inflater.inflate(R.layout.fragment_main, container, false);
			return rootView;
		}
	}

	/** Called when the user clicks the connection button */
	public void connexion(View view)
	{
		EditText editTextLogin = (EditText) findViewById(R.id.editTextLogin);
		String login = editTextLogin.getText().toString();
		EditText editTextPassword = (EditText) findViewById(R.id.editTextPassword);
		String password = editTextPassword.getText().toString();
		EditText editTextIP = (EditText) findViewById(R.id.editTextIP);
		String ip = editTextIP.getText().toString();
		EchangesModeleMaison.setIp(ip);
		if (login.equals("admin") && password.equals("root"))
		{
			//Checking connectivity
			try {
				String retour = EchangesModeleMaison.recupererMaison();

				if (retour.contains("true"))
				{
					Intent intent = new Intent(this, HouseActivity.class); //creates next activity
					SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
					SharedPreferences.Editor editor = settings.edit();
					editor.putString("ip", ip)
					.commit();
					startActivity(intent);}
				else
				{
					displayError("IP invalide 1");
				}
			}
			catch(Exception e)
			{
				displayError("IP invalide 2"); //seems to never be used
			}
		}
		else
		{
			displayError("Adresse IP, nom d'utilisateur ou mot de passe invalide.");
		}
	}

	public boolean isReachable(String ip)
	{
		if (android.os.Build.VERSION.SDK_INT > 9)
		{
			StrictMode.ThreadPolicy policy =
					new StrictMode.ThreadPolicy.Builder().permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}

		try {
			return InetAddress.getByName(ip).isReachable(100);
		}
		catch (UnknownHostException e) {
			e.printStackTrace();
			return false;
		}
		catch (IOException e) {
			return false;
		}
	}

	public void displayError(String error)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(error)
		.setCancelable(true)
		.setPositiveButton("OK", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int id)
			{

			}
		});

		AlertDialog alert = builder.create();
		alert.show();
	}

	@Override
	protected void onStop()
	{
		super.onStop();

		// We need an Editor object to make preference changes.
		// All objects are from android.context.Context
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		final CheckBox checkBoxInfos = (CheckBox) findViewById(R.id.checkBoxSaveInfo);

		if (checkBoxInfos.isChecked())
		{
			//Retrieving infos
			final TextView textViewLogin = (TextView) findViewById(R.id.editTextLogin);
			final TextView textViewPassword = (TextView) findViewById(R.id.editTextPassword);
			String login = textViewLogin.getText().toString();
			String password = textViewPassword.getText().toString();
			//Saving infos
			editor.putString("password", password)
			.putString("login", login)
			// Commit the edits!
			.commit();
		}
	}
}


text:
require "cases/helper"
require 'models/mass_assignment_specific'

class MassAssignmentSecurityTest < ActiveModel::TestCase

  def test_attribute_protection
    user = User.new
    expected = { "name" => "John Smith", "email" => "john@smith.com" }
    sanitized = user.sanitize_for_mass_assignment(expected.merge("admin" => true))
    assert_equal expected, sanitized
  end

  def test_attributes_accessible
    user = Person.new
    expected = { "name" => "John Smith", "email" => "john@smith.com" }
    sanitized = user.sanitize_for_mass_assignment(expected.merge("super_powers" => true))
    assert_equal expected, sanitized
  end

  def test_attributes_protected_by_default
    firm = Firm.new
    expected = { }
    sanitized = firm.sanitize_for_mass_assignment({ "type" => "Client" })
    assert_equal expected, sanitized
  end

  def test_mass_assignment_protection_inheritance
    assert_blank LoosePerson.accessible_attributes
    assert_equal Set.new([ 'credit_rating', 'administrator']), LoosePerson.protected_attributes

    assert_blank LooseDescendant.accessible_attributes
    assert_equal Set.new([ 'credit_rating', 'administrator', 'phone_number']), LooseDescendant.protected_attributes

    assert_blank LooseDescendantSecond.accessible_attributes
    assert_equal Set.new([ 'credit_rating', 'administrator', 'phone_number', 'name']), LooseDescendantSecond.protected_attributes,
      'Running attr_protected twice in one class should merge the protections'

    assert_blank TightPerson.protected_attributes - TightPerson.attributes_protected_by_default
    assert_equal Set.new([ 'name', 'address' ]), TightPerson.accessible_attributes

    assert_blank TightDescendant.protected_attributes - TightDescendant.attributes_protected_by_default
    assert_equal Set.new([ 'name', 'address', 'phone_number' ]), TightDescendant.accessible_attributes
  end

  def test_mass_assignment_multiparameter_protector
    task = Task.new
    attributes = { "starting(1i)" => "2004", "starting(2i)" => "6", "starting(3i)" => "24" }
    sanitized = task.sanitize_for_mass_assignment(attributes)
    assert_equal sanitized, { }
  end

end


text:
package com.coolweather.app.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.coolweather.app.model.City;
import com.coolweather.app.model.County;
import com.coolweather.app.model.Province;

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

/**
 * Created by Administrator on 2016/4/16.
 */
public class CoolWeatherDB
{
    public static final String DB_NAME="cool_weather";

    public static final int VERSION=1;
    private static CoolWeatherDB coolWeatherDB;
    private SQLiteDatabase db;

    private CoolWeatherDB(Context context)
    {
        CoolWeatherOpenHelper dbHelper=new CoolWeatherOpenHelper(context, DB_NAME,null,VERSION);
        db=dbHelper.getWritableDatabase();
    }

    public synchronized static CoolWeatherDB getInstance(Context context)
    {
        if(coolWeatherDB==null)
        {
            coolWeatherDB=new CoolWeatherDB(context);
        }
        return coolWeatherDB;
    }

    //添加数据
    public void saveProvince(Province province)
    {
        if(province !=null)
        {
            ContentValues values=new ContentValues();
            values.put("province_name",province.getProvinceName());
            values.put("province_code",province.getProvinceCode());
            db.insert("Province",null,values);
        }
    }

    public void saveCity(City city)
    {
        if(city !=null)
        {
            ContentValues values=new ContentValues();
            values.put("city_name",city.getCityName());
            values.put("city_code",city.getCityCode());
            values.put("province_id",city.getProvinceId());
            db.insert("City",null,values);
        }
    }

    public void saveCounty(County county)
    {
        if(county !=null)
        {
            ContentValues values=new ContentValues();
            values.put("County_name",county.getCountyName());
            values.put("County_code",county.getCountyCode());
            values.put("city_id",county.getCityId());
            db.insert("County",null,values);
        }
    }

    //查询数据
    public List<Province> loadProvinces()
    {
        List<Province> list=new ArrayList<Province>();
        Cursor cursor=db.query("Province",null,null,null,null,null,null);
        if(cursor.moveToFirst())
        {
            do
            {
                Province province=new Province();
                province.setId(cursor.getInt(cursor.getColumnIndex("id")));
                province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name")));
                province.setProvinceCode((cursor.getString(cursor.getColumnIndex("province_code"))));
                list.add(province);
            }
            while (cursor.moveToNext());
        }
        if(cursor!=null)
        {
            cursor.close();
        }
        return list;
    }

    public List<City> loadCities(int provinceId)
    {
        List<City> list=new ArrayList<City>();
        Cursor cursor=db.query("City",null,"province_id=?",new String[]{String.valueOf(provinceId)},null,null,null);
        if (cursor.moveToFirst())
        {
            do
            {
                City city=new City();
                city.setId(cursor.getInt(cursor.getColumnIndex("id")));
                city.setCityName(cursor.getString(cursor.getColumnIndex("city_name")));
                city.setCityCode(cursor.getString(cursor.getColumnIndex("city_code")));
                city.setProvinceId(provinceId);
                list.add(city);
            }
            while (cursor.moveToNext());
        }
        if(cursor!=null)
        {
            cursor.close();
        }
        return list;
    }
    //从数据库中获取countyCode等数据,配置list
    public List<County> loadCounties(int cityId)
    {
        List<County> list=new ArrayList<County>();
        Cursor cursor=db.query("County",null,"city_Id=?",new String[]{String.valueOf(cityId)},null,null,null);
        if(cursor.moveToFirst())
        {
            do
            {
                County county=new County();
                county.setId(cursor.getInt(cursor.getColumnIndex("id")));
                county.setCountyName(cursor.getString(cursor.getColumnIndex("county_name")));
                county.setCountyCode(cursor.getString(cursor.getColumnIndex("county_code")));
                county.setCityId(cityId);
                list.add(county);
            }
            while (cursor.moveToNext());
        }
        if(cursor !=null)
        {
            cursor.close();
        }
        return list;
    }
}


text:
//
//  ExtendedUIViewController.m
//  zSMTH
//
//  Created by Zhengfa DANG on 2015-3-13.
//  Copyright (c) 2015 Zhengfa. All rights reserved.
//

#import "ExtendedUIViewController.h"
#import "LeftMenuViewController.h"

@interface ExtendedUIViewController ()
{
}
@end

@implementation ExtendedUIViewController

@synthesize progressTitle;

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    helper = [SMTHHelper sharedManager];
    setting = [ZSMTHSetting sharedManager];
    self.progressTitle = @"加载中...";
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.hidesBarsOnSwipe = NO;
}

- (bool) prefersStatusBarHidden {
    return self.navigationController.navigationBarHidden;
}

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

- (void)startAsyncTask
{
    progressBar = [[MBProgressHUD alloc] initWithView:self.view];
    progressBar.mode = MBProgressHUDModeIndeterminate;
    progressBar.delegate = self;
    progressBar.labelText = self.progressTitle;

    //    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(HudTapped)];
    //    tap.delegate = self;
    //    [progressBar addGestureRecognizer:tap];
    [self.view addSubview:progressBar];

    [progressBar showWhileExecuting:@selector(asyncTask) onTarget:self withObject:nil animated:YES];
}

- (void)asyncTask
{
    NSLog(@"asyncTask");
}

- (void)finishAsyncTask
{

}

#pragma mark MBProgressHUD Delegate
- (void)hudWasHidden:(MBProgressHUD *)hud
{
    [hud removeFromSuperview];
    [self finishAsyncTask];
}

- (IBAction)showLeftMenu:(id)sender {
    [self.view endEditing:YES];
    [self.frostedViewController.view endEditing:YES];

    // Present the view controller
    [self.frostedViewController presentMenuViewController];
}

/*
#pragma mark - Navigation

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

@end


text:
<?php
/**
 * File header here
 *
 * @author Ralph Schindler <ralph.schindler@zend.com>
 */

/**
 * class docblock
 *
 * @package ZendL_Reflection_TestSampleSingleClass
 */
class ZendL_Reflection_TestSampleSingleClass
{

    /**
     * Enter description here...
     *
     * @return bool
     */
    public function someMethod()
    {
        /* test test */
    }

}


text:
/*
 * This test verifies non-returnable interrupt handling
 * Note: "iret" is never called here
 */

	lc r100, 0x10000000 // test result output pointer
	lcs r101, halt
	lc r102, failure
	lc r103, 0x20000000 // timer: number of pulses (0xFFFFFFFF - infinite)
	lc r104, 0x20000004 // timer: delay between pulses (in cycles)
	lcs r105, success

	lcs r32, 0 // counter

	lcs iv0, test_loop@1 // set IRF to mark the interrupt as non-returnable
	mov cr, 1 // enable timer interrupt
	sw r104, 100 // delay between interrupts
	sw r103, 100 // generate 100 interrupts
	hlt // wait for a non-returnable interrupt

test_loop:
	add r32, r32, 1
	cjmpuge r105, r32, 100 // success
	hlt // wait for a non-returnable interrupt

failure:
	sw r100, 2 // should never reach here
	jmp r101 // halt

success:
	sw r100, 1 // success

halt:
	hlt
	jmp r101 // halt


text:
from jnius import autoclass
from jnius import cast
from jnius import java_method
from jnius import PythonJavaClass
from math import exp
from plyer.facades import Humidity
from plyer.platforms.android import activity

ActivityInfo = autoclass('android.content.pm.ActivityInfo')
Context = autoclass('android.content.Context')
Sensor = autoclass('android.hardware.Sensor')
SensorManager = autoclass('android.hardware.SensorManager')

class RelativeHumiditySensorListener(PythonJavaClass):
    __javainterfaces__ = ['android/hardware/SensorEventListener']

    def __init__(self):
        super(RelativeHumiditySensorListener, self).__init__()
        service = activity.getSystemService(Context.SENSOR_SERVICE)
        self.SensorManager = cast('android.hardware.SensorManager', service)

        self.sensor = self.SensorManager.getDefaultSensor(
            Sensor.TYPE_RELATIVE_HUMIDITY)
        self.value = None

    def enable(self):
        self.SensorManager.registerListener(self, self.sensor,
                                            SensorManager.SENSOR_DELAY_NORMAL)

    def disable(self):
        self.SensorManager.unregisterListener(self, self.sensor)

    @java_method('(Landroid/hardware/SensorEvent;)V')
    def onSensorChanged(self, event):
        self.value = event.values[0]

    @java_method('(Landroid/hardware/Sensor;I)V')
    def onAccuracyChanged(self, sensor, accuracy):
        pass

class AmbientTemperatureSensorListener(PythonJavaClass):
    __javainterfaces__ = ['android/hardware/SensorEventListener']

    def __init__(self):
        super(AmbientTemperatureSensorListener, self).__init__()
        service = activity.getSystemService(Context.SENSOR_SERVICE)
        self.SensorManager = cast('android.hardware.SensorManager', service)

        self.sensor = self.SensorManager.getDefaultSensor(
            Sensor.TYPE_AMBIENT_TEMPERATURE)
        self.value = None

    def enable(self):
        self.SensorManager.registerListener(self, self.sensor,
                                            SensorManager.SENSOR_DELAY_NORMAL)

    def disable(self):
        self.SensorManager.unregisterListener(self, self.sensor)

    @java_method('(Landroid/hardware/SensorEvent;)V')
    def onSensorChanged(self, event):
        self.value = event.values[0]

    @java_method('(Landroid/hardware/Sensor;I)V')
    def onAccuracyChanged(self, sensor, accuracy):
        pass

class AndroidHumidity(Humidity):

    def __init__(self):
        self.state = False

    def _get_humidity(self):
        if self.state:
            m = 17.62
            Tn = 243.12
            Ta = 216.7
            Rh = self.listener_r.value
            Tc = self.listener_a.value
            A = 6.112
            K = 273.15
            humidity = (Ta * (Rh / 100) * A * exp(m * Tc / (Tn + Tc))
                        / (K + Tc))
            return humidity

    def _enable(self):
        if not self.state:
            self.listener_r = RelativeHumiditySensorListener()
            self.listener_a = AmbientTemperatureSensorListener()
            self.listener_r.enable()
            self.listener_a.enable()
            self.state = True

    def _disable(self):
        if self.state:
            self.listener_r.disable()
            self.listener_a.disable()
            self.state = False
            delattr(self, 'listener_r')
            delattr(self, 'listener_a')

def instance():
    return AndroidHumidity()


text:
using System.Reflection;

[assembly: AssemblyTitle("DotNetGroup Tests")]
[assembly: AssemblyDescription("Contains test siuites of DotNetGroup platform")]
[assembly: AssemblyProduct("DotNetGroup Tests")]