text:
// -----------------------------------------------------------------------------
// This file provides implementations of the font resolution members of
// SkFontHost by using the fontconfig[1] library. Fontconfig is usually found
// on Linux systems and handles configuration, parsing and caching issues
// involved with enumerating and matching fonts.
//
// [1] http://fontconfig.org
// -----------------------------------------------------------------------------

#include <map>
#include <string>

#include <fontconfig/fontconfig.h>

#include "SkFontHost.h"
#include "SkStream.h"

// This is an extern from SkFontHost_FreeType
SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name);

// -----------------------------------------------------------------------------
// The rest of Skia requires that fonts be identified by a unique unsigned id
// and that we be able to load them given the id. What we actually get from
// fontconfig is the filename of the font so we keep a locked map from
// filenames to fileid numbers and back.
//
// Note that there's also a unique id in the SkTypeface. This is unique over
// both filename and style. Thus we encode that id as (fileid << 8) | style.
// Although truetype fonts can support multiple faces in a single file, at the
// moment Skia doesn't.
// -----------------------------------------------------------------------------
static SkMutex global_fc_map_lock;
static std::map<std::string, unsigned> global_fc_map;
static std::map<unsigned, std::string> global_fc_map_inverted;
static std::map<uint32_t, SkTypeface *> global_fc_typefaces;
static unsigned global_fc_map_next_id = 0;

// This is the maximum size of the font cache.
static const unsigned kFontCacheMemoryBudget = 2 * 1024 * 1024;  // 2MB

static unsigned UniqueIdToFileId(unsigned uniqueid)
{
    return uniqueid >> 8;
}

static SkTypeface::Style UniqueIdToStyle(unsigned uniqueid)
{
    return static_cast<SkTypeface::Style>(uniqueid & 0xff);
}

static unsigned FileIdAndStyleToUniqueId(unsigned fileid,
                                         SkTypeface::Style style)
{
    SkASSERT((style & 0xff) == style);
    return (fileid << 8) | static_cast<int>(style);
}

// -----------------------------------------------------------------------------
// Normally we only return exactly the font asked for. In last-resort cases,
// the request is for one of the basic font names "Sans", "Serif" or
// "Monospace". This function tells you whether a given request is for such a
// fallback.
// -----------------------------------------------------------------------------
static bool IsFallbackFontAllowed(const char* request)
{
    return strcmp(request, "Sans") == 0 ||
           strcmp(request, "Serif") == 0 ||
           strcmp(request, "Monospace") == 0;
}

class FontConfigTypeface : public SkTypeface {
public:
    FontConfigTypeface(Style style, uint32_t id)
        : SkTypeface(style, id)
    { }
};

// -----------------------------------------------------------------------------
// Find a matching font where @type (one of FC_*) is equal to @value. For a
// list of types, see http://fontconfig.org/fontconfig-devel/x19.html#AEN27.
// The variable arguments are a list of triples, just like the first three
// arguments, and must be NULL terminated.
//
// For example,
//   FontMatchString(FC_FILE, FcTypeString, "/usr/share/fonts/myfont.ttf",
//                   NULL);
// -----------------------------------------------------------------------------
static FcPattern* FontMatch(const char* type, FcType vtype, const void* value,
                            ...)
{
    va_list ap;
    va_start(ap, value);

    FcPattern* pattern = FcPatternCreate();
    const char* family_requested = NULL;

    for (;;) {
        FcValue fcvalue;
        fcvalue.type = vtype;
        switch (vtype) {
            case FcTypeString:
                fcvalue.u.s = (FcChar8*) value;
                break;
            case FcTypeInteger:
                fcvalue.u.i = (int)(intptr_t)value;
                break;
            default:
                SkASSERT(!"FontMatch unhandled type");
        }
        FcPatternAdd(pattern, type, fcvalue, 0);

        if (vtype == FcTypeString && strcmp(type, FC_FAMILY) == 0)
            family_requested = (const char*) value;

        type = va_arg(ap, const char *);
        if (!type)
            break;
        // FcType is promoted to int when passed through ...
        vtype = static_cast<FcType>(va_arg(ap, int));
        value = va_arg(ap, const void *);
    };
    va_end(ap);

    FcConfigSubstitute(0, pattern, FcMatchPattern);
    FcDefaultSubstitute(pattern);

    // Font matching:
    // CSS often specifies a fallback list of families:
    //    font-family: a, b, c, serif;
    // However, fontconfig will always do its best to find *a* font when asked
    // for something so we need a way to tell if the match which it has found is
    // "good enough" for us. Otherwise, we can return NULL which gets piped up
    // and lets WebKit know to try the next CSS family name. However, fontconfig
    // configs allow substitutions (mapping "Arial -> Helvetica" etc) and we
    // wish to support that.
    //
    // Thus, if a specific family is requested we set @family_requested. Then we
    // record two strings: the family name after config processing and the
    // family name after resolving. If the two are equal, it's a good match.
    //
    // So consider the case where a user has mapped Arial to Helvetica in their
    // config.
    //    requested family: "Arial"
    //    post_config_family: "Helvetica"
    //    post_match_family: "Helvetica"
    //      -> good match
    //
    // and for a missing font:
    //    requested family: "Monaco"
    //    post_config_family: "Monaco"
    //    post_match_family: "Times New Roman"
    //      -> BAD match
    //
    // However, we special-case fallback fonts; see IsFallbackFontAllowed().
    FcChar8* post_config_family;
    FcPatternGetString(pattern, FC_FAMILY, 0, &post_config_family);

    FcResult result;
    FcPattern* match = FcFontMatch(0, pattern, &result);
    if (!match) {
        FcPatternDestroy(pattern);
        return NULL;
    }

    FcChar8* post_match_family;
    FcPatternGetString(match, FC_FAMILY, 0, &post_match_family);
    const bool family_names_match =
        !family_requested ?
        true :
        strcasecmp((char *)post_config_family, (char *)post_match_family) == 0;

    FcPatternDestroy(pattern);

    if (!family_names_match && !IsFallbackFontAllowed(family_requested)) {
        FcPatternDestroy(match);
        return NULL;
    }

    return match;
}

// -----------------------------------------------------------------------------
// Check to see if the filename has already been assigned a fileid and, if so,
// use it. Otherwise, assign one. Return the resulting fileid.
// -----------------------------------------------------------------------------
static unsigned FileIdFromFilename(const char* filename)
{
    SkAutoMutexAcquire ac(global_fc_map_lock);

    std::map<std::string, unsigned>::const_iterator i =
        global_fc_map.find(filename);
    if (i == global_fc_map.end()) {
        const unsigned fileid = global_fc_map_next_id++;
        global_fc_map[filename] = fileid;
        global_fc_map_inverted[fileid] = filename;
        return fileid;
    } else {
        return i->second;
    }
}

// static
SkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace,
                                       const char familyName[],
                                       const void* data, size_t bytelength,
                                       SkTypeface::Style style)
{
    const char* resolved_family_name = NULL;
    FcPattern* face_match = NULL;

    {
        SkAutoMutexAcquire ac(global_fc_map_lock);
        FcInit();
    }

    if (familyFace) {
        // Here we use the inverted global id map to find the filename from the
        // SkTypeface object. Given the filename we can ask fontconfig for the
        // familyname of the font.
        SkAutoMutexAcquire ac(global_fc_map_lock);

        const unsigned fileid = UniqueIdToFileId(familyFace->uniqueID());
        std::map<unsigned, std::string>::const_iterator i =
            global_fc_map_inverted.find(fileid);
        if (i == global_fc_map_inverted.end())
            return NULL;

        FcInit();
        face_match = FontMatch(FC_FILE, FcTypeString, i->second.c_str(),
                               NULL);

        if (!face_match)
            return NULL;
        FcChar8* family;
        if (FcPatternGetString(face_match, FC_FAMILY, 0, &family)) {
            FcPatternDestroy(face_match);
            return NULL;
        }
        // At this point, @family is pointing into the @face_match object so we
        // cannot release it yet.

        resolved_family_name = reinterpret_cast<char*>(family);
    } else if (familyName) {
        resolved_family_name = familyName;
    } else {
        return NULL;
    }

    // At this point, we have a resolved_family_name from somewhere
    SkASSERT(resolved_family_name);

    const int bold = style & SkTypeface::kBold ?
                     FC_WEIGHT_BOLD : FC_WEIGHT_NORMAL;
    const int italic = style & SkTypeface::kItalic ?
                       FC_SLANT_ITALIC : FC_SLANT_ROMAN;
    FcPattern* match = FontMatch(FC_FAMILY, FcTypeString, resolved_family_name,
                                 FC_WEIGHT, FcTypeInteger, bold,
                                 FC_SLANT, FcTypeInteger, italic,
                                 NULL);
    if (face_match)
        FcPatternDestroy(face_match);

    if (!match)
        return NULL;

    FcChar8* filename;
    if (FcPatternGetString(match, FC_FILE, 0, &filename) != FcResultMatch) {
        FcPatternDestroy(match);
        return NULL;
    }
    // Now @filename is pointing into @match

    const unsigned fileid = FileIdFromFilename(reinterpret_cast<char*>(filename));
    const unsigned id = FileIdAndStyleToUniqueId(fileid, style);
    SkTypeface* typeface = SkNEW_ARGS(FontConfigTypeface, (style, id));
    FcPatternDestroy(match);

    {
        SkAutoMutexAcquire ac(global_fc_map_lock);
        global_fc_typefaces[id] = typeface;
    }

    return typeface;
}

// static
SkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream* stream)
{
    SkASSERT(!"SkFontHost::CreateTypefaceFromStream unimplemented");
    return NULL;
}

// static
SkTypeface* SkFontHost::CreateTypefaceFromFile(const char path[])
{
    SkASSERT(!"SkFontHost::CreateTypefaceFromFile unimplemented");
    return NULL;
}

// static
bool SkFontHost::ValidFontID(SkFontID uniqueID) {
    SkAutoMutexAcquire ac(global_fc_map_lock);
    return global_fc_typefaces.find(uniqueID) != global_fc_typefaces.end();
}

// static
SkStream* SkFontHost::OpenStream(uint32_t id)
{
    SkAutoMutexAcquire ac(global_fc_map_lock);
    const unsigned fileid = UniqueIdToFileId(id);

    std::map<unsigned, std::string>::const_iterator i =
        global_fc_map_inverted.find(fileid);
    if (i == global_fc_map_inverted.end())
        return NULL;

    return SkNEW_ARGS(SkFILEStream, (i->second.c_str()));
}

size_t SkFontHost::GetFileName(SkFontID fontID, char path[], size_t length,
                               int32_t* index) {
    SkAutoMutexAcquire ac(global_fc_map_lock);
    const unsigned fileid = UniqueIdToFileId(fontID);

    std::map<unsigned, std::string>::const_iterator i =
    global_fc_map_inverted.find(fileid);
    if (i == global_fc_map_inverted.end()) {
        return 0;
    }

    const std::string& str = i->second;
    if (path) {
        memcpy(path, str.c_str(), SkMin32(str.size(), length));
    }
    if (index) {    // TODO: check if we're in a TTC
        *index = 0;
    }
    return str.size();
}

void SkFontHost::Serialize(const SkTypeface*, SkWStream*) {
    SkASSERT(!"SkFontHost::Serialize unimplemented");
}

SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
    SkASSERT(!"SkFontHost::Deserialize unimplemented");
    return NULL;
}

SkFontID SkFontHost::NextLogicalFont(SkFontID currFontID, SkFontID origFontID) {
    // We don't handle font fallback, WebKit does.
    return 0;
}

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

size_t SkFontHost::ShouldPurgeFontCache(size_t sizeAllocatedSoFar)
{
    if (sizeAllocatedSoFar > kFontCacheMemoryBudget)
        return sizeAllocatedSoFar - kFontCacheMemoryBudget;
    else
        return 0;   // nothing to do
}


text:
<?php
namespace TYPO3\Eel;

/**
 * Utility to reduce boilerplate code needed to set default context variables and evaluate a string that possibly is an EEL expression.
 *
 */
class Utility
{
    /**
     * Get variables from configuration that should be set in the context by default.
     * For example Eel helpers are made available by this.
     *
     * @param array $configuration An one dimensional associative array of context variable paths mapping to object names
     * @return array Array with default context variable objects.
     */
    public static function getDefaultContextVariables(array $configuration)
    {
        $defaultContextVariables = array();
        foreach ($configuration as $variableName => $objectType) {
            $currentPathBase = & $defaultContextVariables;
            $variablePathNames = explode('.', $variableName);
            foreach ($variablePathNames as $pathName) {
                if (!isset($currentPathBase[$pathName])) {
                    $currentPathBase[$pathName] = array();
                }
                $currentPathBase = & $currentPathBase[$pathName];
            }
            $currentPathBase = new $objectType();
        }

        return $defaultContextVariables;
    }

    /**
     * Evaluate an Eel expression.
     *
     * @param string $expression
     * @param EelEvaluatorInterface $eelEvaluator
     * @param array $contextVariables
     * @param array $defaultContextConfiguration
     * @return mixed
     * @throws Exception
     */
    public static function evaluateEelExpression($expression, EelEvaluatorInterface $eelEvaluator, array $contextVariables, array $defaultContextConfiguration = array())
    {
        $matches = null;
        if (!preg_match(Package::EelExpressionRecognizer, $expression, $matches)) {
            throw new Exception('The EEL expression "' . $expression . '" was not a valid EEL expression. Perhaps you forgot to wrap it in ${...}?', 1410441849);
        }

        $defaultContextVariables = self::getDefaultContextVariables($defaultContextConfiguration);
        $contextVariables = array_merge($defaultContextVariables, $contextVariables);

        if (isset($contextVariables['q'])) {
            throw new Exception('Context variable "q" not allowed, as it is already reserved for FlowQuery use.', 1410441819);
        }

        $contextVariables['q'] = function ($element) {
            return new FlowQuery\FlowQuery(is_array($element) || $element instanceof \Traversable ? $element : array($element));
        };

        $context = new ProtectedContext($contextVariables);
        $context->whitelist('q');

        return $eelEvaluator->evaluate($matches['exp'], $context);
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace content {

PeerConnectionTrackerHost::PeerConnectionTrackerHost(int render_process_id)
    : BrowserMessageFilter(PeerConnectionTrackerMsgStart),
      render_process_id_(render_process_id) {}

bool PeerConnectionTrackerHost::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;

  IPC_BEGIN_MESSAGE_MAP(PeerConnectionTrackerHost, message)
    IPC_MESSAGE_HANDLER(PeerConnectionTrackerHost_AddPeerConnection,
                        OnAddPeerConnection)
    IPC_MESSAGE_HANDLER(PeerConnectionTrackerHost_RemovePeerConnection,
                        OnRemovePeerConnection)
    IPC_MESSAGE_HANDLER(PeerConnectionTrackerHost_UpdatePeerConnection,
                        OnUpdatePeerConnection)
    IPC_MESSAGE_HANDLER(PeerConnectionTrackerHost_AddStats, OnAddStats)
    IPC_MESSAGE_HANDLER(PeerConnectionTrackerHost_GetUserMedia, OnGetUserMedia)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void PeerConnectionTrackerHost::OverrideThreadForMessage(
    const IPC::Message& message, BrowserThread::ID* thread) {
  if (IPC_MESSAGE_CLASS(message) == PeerConnectionTrackerMsgStart)
    *thread = BrowserThread::UI;
}

PeerConnectionTrackerHost::~PeerConnectionTrackerHost() {
}

void PeerConnectionTrackerHost::OnAddPeerConnection(
    const PeerConnectionInfo& info) {
  WebRTCInternals::GetInstance()->OnAddPeerConnection(
      render_process_id_,
      peer_pid(),
      info.lid,
      info.url,
      info.servers,
      info.constraints);
}

void PeerConnectionTrackerHost::OnRemovePeerConnection(int lid) {
  WebRTCInternals::GetInstance()->OnRemovePeerConnection(peer_pid(), lid);
}

void PeerConnectionTrackerHost::OnUpdatePeerConnection(
    int lid, const std::string& type, const std::string& value) {
  WebRTCInternals::GetInstance()->OnUpdatePeerConnection(
      peer_pid(),
      lid,
      type,
      value);
}

void PeerConnectionTrackerHost::OnAddStats(int lid,
                                           const base::ListValue& value) {
  WebRTCInternals::GetInstance()->OnAddStats(peer_pid(), lid, value);
}

void PeerConnectionTrackerHost::OnGetUserMedia(
    const std::string& origin,
    bool audio,
    bool video,
    const std::string& audio_constraints,
    const std::string& video_constraints) {
  WebRTCInternals::GetInstance()->OnGetUserMedia(render_process_id_,
                                                 peer_pid(),
                                                 origin,
                                                 audio,
                                                 video,
                                                 audio_constraints,
                                                 video_constraints);
}

}  // namespace content


text:
package org.jhotdraw.app.action.app;

import edu.umd.cs.findbugs.annotations.Nullable;
import org.jhotdraw.gui.*;
import org.jhotdraw.gui.Worker;
import org.jhotdraw.gui.event.*;
import org.jhotdraw.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.URI;
import org.jhotdraw.app.Application;
import org.jhotdraw.app.View;
import org.jhotdraw.app.action.AbstractApplicationAction;
import org.jhotdraw.gui.URIChooser;
import org.jhotdraw.net.URIUtil;

/**
 * Exits the application after letting the user review all unsaved views.
 *

 * This action is called when the user selects the Exit item in the Application
 * menu, or when the application receives a Quit event from Mac OS X Finder.
 * The menu item is automatically created by the application.
 *

 * This action is automatically created by the application and put into
 * the {@code ApplicationModel} before {@link org.jhotdraw.app.ApplicationModel#initApplication}
 * is called.
 *
 * @author  Werner Randelshofer
 * @version $Id: ExitAction.java 717 2010-11-21 12:30:57Z rawcoder $
 */
public class ExitAction extends AbstractApplicationAction {

    public final static String ID = "application.exit";
    private Component oldFocusOwner;
    private View unsavedView;

    /** Creates a new instance. */
    public ExitAction(Application app) {
        super(app);
        ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
        labels.configureAction(this, ID);
    }

    @Override
    public void actionPerformed(ActionEvent evt) {
        final Application app = getApplication();
        if (app.isEnabled()) {
            app.setEnabled(false);
            int unsavedViewsCount = 0;
            View documentToBeReviewed = null;
            URI unsavedURI = null;
            for (View p : app.views()) {
                if (p.hasUnsavedChanges()) {
                    if (p.isEnabled()) {
                        documentToBeReviewed = p;
                    }
                    unsavedURI = p.getURI();
                    unsavedViewsCount++;
                }
            }
            if (unsavedViewsCount > 0 && documentToBeReviewed == null) {
                // Silently abort, if no view can be reviewed.
                app.setEnabled(true);
                return;
            }

            final ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
            switch (unsavedViewsCount) {
                case 0: {
                    doExit();
                    break;
                }
                case 1: {
                    unsavedView = documentToBeReviewed;
                    oldFocusOwner = SwingUtilities.getWindowAncestor(unsavedView.getComponent()).getFocusOwner();
                    unsavedView.setEnabled(false);
                    JOptionPane pane = new JOptionPane(
                            "" + UIManager.getString("OptionPane.css")
                            + "" + labels.getFormatted("application.exit.doYouWantToSave.message",//
                            (unsavedURI == null) ? labels.getString("unnamedFile") : URIUtil.getName(unsavedURI)) + "
"
                            + labels.getString("application.exit.doYouWantToSave.details"),
                            JOptionPane.WARNING_MESSAGE);
                    Object[] options = {labels.getString("application.exit.saveOption"), labels.getString("application.exit.cancelOption"), labels.getString("application.exit.dontSaveOption")};
                    pane.setOptions(options);
                    pane.setInitialValue(options[0]);
                    pane.putClientProperty("Quaqua.OptionPane.destructiveOption", 2);
                    JSheet.showSheet(pane, unsavedView.getComponent(), new SheetListener() {

                    @Override
                        public void optionSelected(SheetEvent evt) {
                            Object value = evt.getValue();
                            if (value == null || value.equals(labels.getString("application.exit.cancelOption"))) {
                                unsavedView.setEnabled(true);
                                app.setEnabled(true);
                            } else if (value.equals(labels.getString("application.exit.dontSaveOption"))) {
                                doExit();
                                unsavedView.setEnabled(true);
                            } else if (value.equals(labels.getString("application.exit.saveOption"))) {
                                saveChanges();
                            }
                        }
                    });

                    break;
                }
                default: {
                    JOptionPane pane = new JOptionPane(
                            "" + UIManager.get("OptionPane.css")
                            + "" + labels.getFormatted("application.exit.doYouWantToReview.message", unsavedViewsCount) + "
"
                            + labels.getString("application.exit.doYouWantToReview.details"),
                            JOptionPane.QUESTION_MESSAGE);
                    Object[] options = {labels.getString("application.exit.reviewChangesOption"), labels.getString("application.exit.cancelOption"), labels.getString("application.exit.discardChangesOption")};
                    pane.setOptions(options);
                    pane.setInitialValue(options[0]);
                    pane.putClientProperty(
                            "Quaqua.OptionPane.destructiveOption", 2);
                    JDialog dialog = pane.createDialog(app.getComponent(), null);
                    Rectangle screenBounds = dialog.getGraphicsConfiguration().getBounds();
                    if (app.getComponent() == null || !screenBounds.contains(app.getComponent().getBounds())) {
                        // place dialog in center and in upper third of screen
                        dialog.setLocation((screenBounds.width - dialog.getWidth()) / 2, (screenBounds.height - dialog.getHeight()) / 3);
                    }
                    dialog.setVisible(true);
                    Object value = pane.getValue();
                    if (value == null || value.equals(labels.getString("application.exit.cancelOption"))) {
                        app.setEnabled(true);
                    } else if (value.equals(labels.getString("application.exit.discardChangesOption"))) {
                        doExit();
                        app.setEnabled(true);
                    } else if (value.equals(labels.getString("application.exit.reviewChangesOption"))) {
                        unsavedView = documentToBeReviewed;
                        reviewChanges();
                    }
                }
            }
        }
    }
    protected URIChooser getChooser(View view) {
        URIChooser chsr = (URIChooser) (view.getComponent()).getClientProperty("saveChooser");
        if (chsr == null) {
            chsr = getApplication().getModel().createSaveChooser(getApplication(), view);
            view.getComponent().putClientProperty("saveChooser", chsr);
        }
        return chsr;
    }

    protected void saveChanges() {
        View v = unsavedView;
        if (v.getURI() == null) {
            URIChooser chooser = getChooser(v);
            //int option = fileChooser.showSaveDialog(this);
            JSheet.showSaveSheet(chooser, v.getComponent(), new SheetListener() {

                @Override
                public void optionSelected(final SheetEvent evt) {
                    if (evt.getOption() == JFileChooser.APPROVE_OPTION) {
                        final URI uri = evt.getChooser().getSelectedURI();
                        saveToFile(uri, evt.getChooser());
                    } else {
                        unsavedView.setEnabled(true);
                        if (oldFocusOwner != null) {
                            oldFocusOwner.requestFocus();
                        }
                        getApplication().setEnabled(true);
                    }
                }
            });
        } else {
            saveToFile(v.getURI(), null);
        }
    }

    protected void reviewChanges() {
        if (unsavedView.isEnabled()) {
            final ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
            oldFocusOwner = SwingUtilities.getWindowAncestor(unsavedView.getComponent()).getFocusOwner();
            unsavedView.setEnabled(false);
            URI unsavedURI = unsavedView.getURI();
            JOptionPane pane = new JOptionPane(
                    "" + UIManager.getString("OptionPane.css")
                    + labels.getFormatted("application.exit.doYouWantToSave.message", //
                    (unsavedURI==null)?unsavedView.getTitle():URIUtil.getName(unsavedURI)),
                    JOptionPane.WARNING_MESSAGE);
            Object[] options = {labels.getString("application.exit.saveOption"), labels.getString("application.exit.cancelOption"), labels.getString("application.exit.dontSaveOption")};
            pane.setOptions(options);
            pane.setInitialValue(options[0]);
            pane.putClientProperty("Quaqua.OptionPane.destructiveOption", 2);
            JSheet.showSheet(pane, unsavedView.getComponent(), new SheetListener() {

                @Override
                public void optionSelected(SheetEvent evt) {
                    Object value = evt.getValue();
                    if (value == null || value.equals(labels.getString("application.exit.cancelOption"))) {
                        unsavedView.setEnabled(true);
                        getApplication().setEnabled(true);
                    } else if (value.equals(labels.getString("application.exit.dontSaveOption"))) {
                        getApplication().dispose(unsavedView);
                        reviewNext();
                    } else if (value.equals(labels.getString("application.exit.saveOption"))) {
                        saveChangesAndReviewNext();
                    }
                }
            });
        } else {
            getApplication().setEnabled(true);
        }
    }

    protected void saveChangesAndReviewNext() {
        final View v = unsavedView;
        if (v.getURI() == null) {
            URIChooser chooser = getChooser(v);
            JSheet.showSaveSheet(chooser, unsavedView.getComponent(), new SheetListener() {

                @Override
                public void optionSelected(final SheetEvent evt) {
                    if (evt.getOption() == URIChooser.APPROVE_OPTION) {
                        final URI uri = evt.getChooser().getSelectedURI();
                        saveToFileAndReviewNext(uri, evt.getChooser());
                    } else {
                        v.setEnabled(true);
                        if (oldFocusOwner != null) {
                            oldFocusOwner.requestFocus();
                        }
                        getApplication().setEnabled(true);
                    }
                }
            });
        } else {
            saveToFileAndReviewNext(v.getURI(), null);
        }
    }

    protected void reviewNext() {
        int unsavedViewsCount = 0;
        View documentToBeReviewed = null;
        for (View p : getApplication().views()) {
            if (p.hasUnsavedChanges()) {
                if (p.isEnabled()) {
                    documentToBeReviewed = p;
                }
                unsavedViewsCount++;
            }
        }
        if (unsavedViewsCount == 0) {
            doExit();
        } else if (documentToBeReviewed != null) {
            unsavedView = documentToBeReviewed;
            reviewChanges();
        } else {
            getApplication().setEnabled(true);
            //System.out.println("exit silently aborted");
        }
    }

    protected void saveToFile(final URI uri, @Nullable final URIChooser chooser) {
        final View v = unsavedView;
        v.execute(new Worker() {

            @Override
            protected Object construct() throws IOException {
                v.write(uri, chooser);
                return null;
            }

            @Override
            protected void done(Object value) {
                v.setURI(uri);
                doExit();
            }

            @Override
            protected void failed(Throwable error) {
                ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
                JSheet.showMessageSheet(v.getComponent(),
                        "" + UIManager.getString("OptionPane.css")
                        + "" + labels.format("file.save.couldntSave.message", URIUtil.getName(uri)) + "
"
                        + error,
                        JOptionPane.ERROR_MESSAGE);
            }

            @Override
            public void finished() {
                v.setEnabled(true);
                if (oldFocusOwner != null) {
                    oldFocusOwner.requestFocus();
                }
                getApplication().setEnabled(true);
            }
        });
    }

    protected void saveToFileAndReviewNext(final URI uri, @Nullable final URIChooser chooser) {
        final View v = unsavedView;
        v.execute(new Worker() {

            @Override
            protected Object construct() throws IOException {
                v.write(uri, chooser);
                return null;
            }

            @Override
            protected void done(Object value) {
                v.setURI(uri);
                getApplication().dispose(unsavedView);
                reviewNext();
            }

            @Override
            protected void failed(Throwable error) {
                ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
                JSheet.showMessageSheet(v.getComponent(),
                        "" + UIManager.getString("OptionPane.css")
                        + "" + labels.format("file.save.couldntSave.message", uri) + "
"
                        + error,
                        JOptionPane.ERROR_MESSAGE);
                v.setEnabled(true);
                if (oldFocusOwner != null) {
                    oldFocusOwner.requestFocus();
                }
                getApplication().setEnabled(true);
            }
        });
    }

    protected void doExit() {
        getApplication().destroy();
    }
}


text:
import io
import socket
import struct
import time
import picamera

# Connect a client socket to my_server:8000 (change my_server to the
# hostname of your server)
print 'PI Camera Client is connecting to computer server host 10.3.33.106...'
client_socket = socket.socket()
# client_socket.connect(('192.168.0.100', 8000))
# client_socket.connect(('192.168.0.103', 8000))
client_socket.connect(('192.168.43.66', 8000))  #GL home macbook ip
# Make a file-like object out of the connection
connection = client_socket.makefile('wb')
print 'Connected.  Start sending out images to server.'

while True:
    try:
        with picamera.PiCamera() as camera:
            camera.resolution = (320, 240)      # pi camera resolution
            # camera.resolution = (1280,960)      # pi camera X4
            camera.framerate = 10               # 10 frames/sec
            # camera.framerate = 2               # 10 frames/sec
            time.sleep(2)                       # give 2 secs for camera to initilize
            start = time.time()
            stream = io.BytesIO()

            # send jpeg format video BytesIO stream
            for foo in camera.capture_continuous(stream, 'jpeg', use_video_port = True):
                connection.write(struct.pack('<L', stream.tell()))
                connection.flush()
                stream.seek(0)
                connection.write(stream.read())
                if time.time() - start > 600:
                    break
                stream.seek(0)
                stream.truncate()
        connection.write(struct.pack('<L', 0))
    finally:
        connection.close()
        client_socket.close()


text:
using Clustering
using Images
using ImageView

function convert_colors(colors)
	converted = Array(Float64, 3, size(colors, 1))
	for i in 1:size(colors, 1)
		converted[:, i] = colors[i]
	end
	return converted
end

function cluster(image, initial_colors)
	image = permutedims(image, [2, 3, 1])
	pixels = convert(Array{Float64,2}, transpose(reshape(image, size(image, 1) * size(image, 2), size(image, 3))))
	result = kmeans(pixels, convert_colors(initial_colors); display=:none)
	colors = result.centers

	image = permutedims(image, [3, 1, 2])

	for i in 1:size(image, 2), j in 1:size(image, 3)
		index =	indmin(sum((colors .- image[:,i,j]) .^ 2, 1))
		image[:,i,j] = colors[:,index]
	end

	return image
end


text:
#ifndef GLXGRAPHICSWINDOW_H
#define GLXGRAPHICSWINDOW_H

#include "pandabase.h"

#include "x11GraphicsWindow.h"
#include "glxGraphicsPipe.h"
#include "graphicsWindow.h"
#include "buttonHandle.h"

/**
 * An interface to the glx system for managing GL windows under X.
 */
class glxGraphicsWindow : public x11GraphicsWindow {
public:
  glxGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe,
                    const std::string &name,
                    const FrameBufferProperties &fb_prop,
                    const WindowProperties &win_prop,
                    int flags,
                    GraphicsStateGuardian *gsg,
                    GraphicsOutput *host);
  virtual ~glxGraphicsWindow() {};

  virtual bool begin_frame(FrameMode mode, Thread *current_thread);
  virtual void end_frame(FrameMode mode, Thread *current_thread);
  virtual void end_flip();

protected:
  virtual void close_window();
  virtual bool open_window();

private:
  virtual void setup_colormap(GLXFBConfig fbconfig);
  virtual void setup_colormap(XVisualInfo *visual);

public:
  static TypeHandle get_class_type() {
    return _type_handle;
  }
  static void init_type() {
    x11GraphicsWindow::init_type();
    register_type(_type_handle, "glxGraphicsWindow",
                  x11GraphicsWindow::get_class_type());
  }
  virtual TypeHandle get_type() const {
    return get_class_type();
  }
  virtual TypeHandle force_init_type() {init_type(); return get_class_type();}

private:
  static TypeHandle _type_handle;
};

#endif


text:
using Discord;
using Discord.Commands;
using NadekoBot.Extensions;
using System;
using System.Linq;
using System.Threading.Tasks;
using NadekoBot.Common.Attributes;
using NadekoBot.Modules.Utility.Services;

namespace NadekoBot.Modules.Utility
{
    public partial class Utility
    {
        [Group]
        public class UnitConverterCommands : NadekoSubmodule<ConverterService>
        {
            [NadekoCommand, Usage, Description, Aliases]
            public async Task ConvertList()
            {
                var res = _service.Units.GroupBy(x => x.UnitType)
                               .Aggregate(new EmbedBuilder().WithTitle(GetText("convertlist"))
                                                            .WithColor(NadekoBot.OkColor),
                                          (embed, g) => embed.AddField(efb =>
                                                                         efb.WithName(g.Key.ToTitleCase())
                                                                         .WithValue(String.Join(", ", g.Select(x => x.Triggers.FirstOrDefault())
                                                                                .OrderBy(x => x)))));
                await Context.Channel.EmbedAsync(res);
            }
            [NadekoCommand, Usage, Description, Aliases]
            public async Task Convert(string origin, string target, decimal value)
            {
                var originUnit = _service.Units.Find(x => x.Triggers.Select(y => y.ToLowerInvariant()).Contains(origin.ToLowerInvariant()));
                var targetUnit = _service.Units.Find(x => x.Triggers.Select(y => y.ToLowerInvariant()).Contains(target.ToLowerInvariant()));
                if (originUnit == null || targetUnit == null)
                {
                    await ReplyErrorLocalized("convert_not_found", Format.Bold(origin), Format.Bold(target)).ConfigureAwait(false);
                    return;
                }
                if (originUnit.UnitType != targetUnit.UnitType)
                {
                    await ReplyErrorLocalized("convert_type_error", Format.Bold(originUnit.Triggers.First()), Format.Bold(targetUnit.Triggers.First())).ConfigureAwait(false);
                    return;
                }
                decimal res;
                if (originUnit.Triggers == targetUnit.Triggers) res = value;
                else if (originUnit.UnitType == "temperature")
                {
                    //don't really care too much about efficiency, so just convert to Kelvin, then to target
                    switch (originUnit.Triggers.First().ToUpperInvariant())
                    {
                        case "C":
                            res = value + 273.15m; //celcius!
                            break;
                        case "F":
                            res = (value + 459.67m) * (5m / 9m);
                            break;
                        default:
                            res = value;
                            break;
                    }
                    //from Kelvin to target
                    switch (targetUnit.Triggers.First().ToUpperInvariant())
                    {
                        case "C":
                            res = res - 273.15m; //celcius!
                            break;
                        case "F":
                            res = res * (9m / 5m) - 459.67m;
                            break;
                    }
                }
                else
                {
                    if (originUnit.UnitType == "currency")
                    {
                        res = (value * targetUnit.Modifier) / originUnit.Modifier;
                    }
                    else
                        res = (value * originUnit.Modifier) / targetUnit.Modifier;
                }
                res = Math.Round(res, 4);

                await Context.Channel.SendConfirmAsync(GetText("convert", value, (originUnit.Triggers.First()).SnPl(value.IsInteger() ? (int)value : 2), res, (targetUnit.Triggers.First() + "s").SnPl(res.IsInteger() ? (int)res : 2)));
            }
        }
    }
}


text:
module Codebreaker
  class Guess

    attr_reader :value

    def initialize value
      @value = value
    end

    def valid?
     if @value =~ /^[1-6]{4}$/

      true

     else

      false

     end
    end

  end
end


text:
# -*- coding: utf_8 -*-

import helloworld     # 製品コードインポート
from pyspec import *  # テストコードインポート

class HelloWorld_Behavior:
    @spec
    def generate_python(self):
        """PythonのHello Worldのテスト."""
        About(helloworld.generate("Python")).should_equal("print 'Hello World!'")

    @spec(expected=KeyError)
    def generate_invalid_language(self):
        """未登録の言語を設定すると、KeyErrorが発生する."""
        helloworld.generate("Ruby")

if __name__ == "__main__":
    run_test()


text:
package net.viservice.editor.ueditor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.baidu.ueditor.ActionEnter;
import com.baidu.ueditor.ConfigManager;
import com.baidu.ueditor.define.ActionMap;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.State;

public class UeditorActionEnter extends ActionEnter {

	private HttpServletRequest request = null;

	private String rootPath = null;
	private String contextPath = null;

	private String actionType = null;

	private ConfigManager configManager = null;

	private UeditorService ueditorService = null;

	public UeditorActionEnter(HttpServletRequest request, String rootPath, UeditorService ueditorService) {
		super(request, rootPath);

		this.request = request;
		this.rootPath = rootPath;
		this.actionType = request.getParameter("action");
		this.contextPath = request.getContextPath();
		this.configManager = ConfigManager.getInstance(this.rootPath, this.contextPath, request.getRequestURI());

		this.ueditorService = ueditorService;

	}

	@Override
	public String exec() {
		return super.exec();
	}

	@Override
	public String invoke() {

		if (actionType == null || !ActionMap.mapping.containsKey(actionType)) {
			return new BaseState(false, AppInfo.INVALID_ACTION).toJSONString();
		}

		if (this.configManager == null || !this.configManager.valid()) {
			return new BaseState(false, AppInfo.CONFIG_ERROR).toJSONString();
		}

		State state = null;

		int actionCode = ActionMap.getType(this.actionType);

		Map<String, Object> conf = null;

		switch (actionCode) {

			case ActionMap.CONFIG:
				return this.configManager.getAllConfig().toString();

			case ActionMap.UPLOAD_IMAGE:
			case ActionMap.UPLOAD_SCRAWL:
			case ActionMap.UPLOAD_VIDEO:
			case ActionMap.UPLOAD_FILE:
				conf = this.configManager.getConfig(actionCode);
				state = new UeditorUploader(request, conf, this.ueditorService).doExec();
				break;

			case ActionMap.CATCH_IMAGE:
				conf = configManager.getConfig(actionCode);
				String[] list = this.request.getParameterValues((String) conf.get("fieldName"));
				state = new UeditorImageHunter(conf, this.ueditorService).capture(list);
				break;

			case ActionMap.LIST_IMAGE:
			case ActionMap.LIST_FILE:
				conf = configManager.getConfig(actionCode);
				int start = this.getStartIndex();
				state = new UeditorFileManager(conf, this.ueditorService).listFile(start);
				break;

		}

		return state.toJSONString();

	}

}


text:
package org.radargun.stages.cache.background;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReferenceArray;

import org.radargun.logging.Log;
import org.radargun.logging.LogFactory;
import org.radargun.stages.cache.generators.KeyGenerator;
import org.radargun.traits.BasicOperations;
import org.radargun.traits.CacheListeners;
import org.radargun.traits.Debugable;
import org.radargun.utils.Utils;

/**
 * Log checkers control that all operations executed by stressors are persisted in the log values.
 * Each node checks all writes from all stressors, but there's not a one-to-one stressor-checker
 * relation. Instead, each node holds a pool of checker threads and a shared data structure
 * with records about each stressor. All records are iterated through in a round-robin fashion
 * by the checker threads.
 *
 * When the checkers are dead on particular node, this node cannot check the stressors. For some
 * scenarios this is limiting - therefore, stressors may be configured to unwind the log values
 * even if the old records are not checked. Then, it has to notify the checker about this action
 * via ignored_* key, to prevent it from failing the test.
 *
 * @see AbstractLogLogic
 * @see Stressor
 *
 * @author Radim Vansa <rvansa@redhat.com>
 */
public abstract class LogChecker extends Thread {
   protected static final Log log = LogFactory.getLog(LogChecker.class);
   protected static final boolean trace = log.isTraceEnabled();
   protected static final long UNSUCCESSFUL_CHECK_MIN_DELAY_MS = 10;
   protected static final String LAST_OPERATION_PREFIX = "stressor_";
   protected final KeyGenerator keyGenerator;
   protected final int slaveIndex;
   protected final long logCounterUpdatePeriod;
   protected final Pool pool;
   protected final BasicOperations.Cache basicCache;
   protected final Debugable.Cache debugableCache;
   protected volatile boolean terminate = false;

   public LogChecker(String name, BackgroundOpsManager manager, Pool logCheckerPool) {
      super(name);
      keyGenerator = manager.getKeyGenerator();
      slaveIndex = manager.getSlaveIndex();
      logCounterUpdatePeriod = manager.getLogLogicConfiguration().getCounterUpdatePeriod();
      pool = logCheckerPool;
      this.basicCache = manager.getBasicCache();
      this.debugableCache = manager.getDebugableCache();
   }

   public static String checkerKey(int checkerSlaveId, int slaveAndThreadId) {
      return String.format("checker_%d_%d", checkerSlaveId, slaveAndThreadId);
   }

   public static String ignoredKey(int checkerSlaveId, int slaveAndThreadId) {
      return String.format("ignored_%d_%d", checkerSlaveId, slaveAndThreadId);
   }

   public static String lastOperationKey(int slaveAndThreadId) {
      return String.format(LAST_OPERATION_PREFIX + "%d", slaveAndThreadId);
   }

   public void requestTerminate() {
      terminate = true;
   }

   @Override
   public void run() {
      int delayedKeys = 0;
      while (!terminate) {
         AbstractStressorRecord record = null;
         try {
            if (delayedKeys > pool.getTotalThreads()) {
               Thread.sleep(UNSUCCESSFUL_CHECK_MIN_DELAY_MS);
            }
            record = pool.take();
            if (System.currentTimeMillis() < record.getLastUnsuccessfulCheckTimestamp() + UNSUCCESSFUL_CHECK_MIN_DELAY_MS) {
               delayedKeys++;
               continue;
            }
            delayedKeys = 0;
            if (record.getLastUnsuccessfulCheckTimestamp() > Long.MIN_VALUE) {
               // the last check was unsuccessful -> grab lastOperation BEFORE the value to check if we've lost that
               Object last = basicCache.get(lastOperationKey(record.getThreadId()));
               if (last != null) {
                  record.setLastStressorOperation(((LastOperation) last).getOperationId());
               }
            }
            if (record.getOperationId() == 0) {
               Object last = basicCache.get(checkerKey(slaveIndex, record.getThreadId()));
               if (last != null) {
                  LastOperation lastCheck = (LastOperation) last;
                  record = newRecord(record, lastCheck.getOperationId(), lastCheck.getSeed());
               }
               Object ignored = basicCache.get(ignoredKey(slaveIndex, record.getThreadId()));
               if (ignored != null && record.getOperationId() <= (Long) ignored) {
                  log.debug(String.format("Ignoring operations %d - %d for thread %d", record.getOperationId(), ignored, record.getThreadId()));
                  while (record.getOperationId() <= (Long) ignored) {
                     record.next();
                  }
               }
               if (record.getOperationId() != 0) {
                  log.debug(String.format("Check for thread %d continues from operation %d",
                     record.getThreadId(), record.getOperationId()));
               }
            }
            if (trace) {
               log.trace(String.format("Checking operation %d for thread %d on key %d (%s)",
                     record.getOperationId(), record.getThreadId(), record.getKeyId(), keyGenerator.generateKey(record.getKeyId())));
            }
            boolean notification = record.hasNotification(record.getOperationId());
            Object value = findValue(record);
            boolean contains = containsOperation(value, record);
            if (notification && contains) {
               if (trace) {
                  log.trace(String.format("Found operation %d for thread %d", record.getOperationId(), record.getThreadId()));
               }
               if (record.getOperationId() % logCounterUpdatePeriod == 0) {
                  basicCache.put(checkerKey(slaveIndex, record.getThreadId()),
                        new LastOperation(record.getOperationId(), Utils.getRandomSeed(record.rand)));
               }
               record.next();
               record.setLastUnsuccessfulCheckTimestamp(Long.MIN_VALUE);
               pool.reportStoredOperation();
            } else {
               if (record.getLastStressorOperation() >= record.getOperationId()) {
                  // one more check to see whether some operations should not be ignored
                  Object ignored = basicCache.get(ignoredKey(slaveIndex, record.getThreadId()));
                  if (ignored != null && record.getOperationId() <= (Long) ignored) {
                     log.debug(String.format("Operations %d - %d for thread %d are ignored.", record.getOperationId(), ignored, record.threadId));
                     while (record.getOperationId() <= (Long) ignored) {
                        record.next();
                     }
                     continue;
                  }

                  if (!notification) {
                     log.error(String.format("Missing notification for operation %d for thread %d on key %d (%s), required for %d, notified for %s",
                           record.getOperationId(), record.getThreadId(), record.getKeyId(),
                           keyGenerator.generateKey(record.getKeyId()), record.requireNotify, record.notifiedOps));
                     pool.reportMissingNotification();
                  }
                  if (!contains) {
                     log.error(String.format("Missing operation %d for thread %d on key %d (%s) %s",
                           record.getOperationId(), record.getThreadId(), record.getKeyId(),
                           keyGenerator.generateKey(record.getKeyId()),
                           value == null ? " - entry was completely lost" : ""));
                     if (trace) {
                        log.trace("Not found in " + value);
                     }
                     pool.reportMissingOperation();
                     if (debugableCache != null) {
                        debugableCache.debugInfo();
                        debugableCache.debugKey(keyGenerator.generateKey(record.getKeyId()));
                        debugableCache.debugKey(keyGenerator.generateKey(~record.getKeyId()));
                     }
                  }
                  record.next();
               } else {
                  record.setLastUnsuccessfulCheckTimestamp(System.currentTimeMillis());
               }
            }
         } catch (Exception e) {
            log.error("Cannot check value " + record.getKeyId(), e);
         } finally {
            if (record == null) {
               try {
                  Thread.sleep(100);
               } catch (InterruptedException e) {
                  Thread.interrupted();
               }
            } else {
               pool.add(record);
            }
         }
      }
   }

   protected abstract AbstractStressorRecord newRecord(AbstractStressorRecord record, long operationId, long seed);

   protected abstract Object findValue(AbstractStressorRecord record) throws Exception;

   protected abstract boolean containsOperation(Object value, AbstractStressorRecord record);

   public static abstract class Pool implements CacheListeners.UpdatedListener, CacheListeners.CreatedListener {
      private final int totalThreads;
      private final AtomicReferenceArray<AbstractStressorRecord> allRecords;
      private final ConcurrentLinkedQueue<AbstractStressorRecord> records = new ConcurrentLinkedQueue<AbstractStressorRecord>();
      private final BackgroundOpsManager manager;
      private final AtomicLong missingOperations = new AtomicLong();
      private final AtomicLong missingNotifications = new AtomicLong();
      private final BasicOperations.Cache cache;
      private volatile long lastStoredOperationTimestamp = Long.MIN_VALUE;

      public Pool(int numThreads, int numSlaves, BackgroundOpsManager manager) {
         totalThreads = numThreads * numSlaves;
         allRecords = new AtomicReferenceArray<AbstractStressorRecord>(totalThreads);
         log.trace("Pool will contain " + allRecords.length() + records);
         this.manager = manager;
         this.cache = manager.getBasicCache();
      }

      protected void registerListeners() {
         if (!manager.getLogLogicConfiguration().isCheckNotifications()) {
            return;
         }
         CacheListeners listeners = manager.getListeners();
         if (listeners == null) {
            throw new IllegalArgumentException("Service does not support cache listeners");
         }
         Collection<CacheListeners.Type> supported = listeners.getSupportedListeners();
         if (!supported.containsAll(Arrays.asList(CacheListeners.Type.CREATED, CacheListeners.Type.UPDATED))) {
            throw new IllegalArgumentException("Service does not support required listener types; supported are: " + supported);
         }
         String cacheName = manager.getGeneralConfiguration().getCacheName();
         manager.getListeners().addCreatedListener(cacheName, this);
         manager.getListeners().addUpdatedListener(cacheName, this);
      }

      public long getMissingOperations() {
         return missingOperations.get();
      }

      public long getMissingNotifications() {
         return missingNotifications.get();
      }

      public void reportMissingOperation() {
         missingOperations.incrementAndGet();
      }

      public void reportMissingNotification() {
         missingNotifications.incrementAndGet();
      }

      public int getTotalThreads() {
         return totalThreads;
      }

      public void reportStoredOperation() {
         lastStoredOperationTimestamp = System.currentTimeMillis();
      }

      public long getLastStoredOperationTimestamp() {
         return lastStoredOperationTimestamp;
      }

      public AbstractStressorRecord take() {
         return records.poll();
      }

      public void add(AbstractStressorRecord record) {
         records.add(record);
      }

      public void addNew(AbstractStressorRecord record) {
         records.add(record);
         allRecords.set(record.getThreadId(), record);
      }

      public String waitUntilChecked(long timeout) {
         for (int i = 0; i < totalThreads; ++i) {
            AbstractStressorRecord record = allRecords.get(i);
            if (record == null) continue;
            try {
               LastOperation lastOperation = (LastOperation) cache.get(lastOperationKey(record.getThreadId()));
               if (lastOperation == null) {
                  log.trace("Thread " + record.getThreadId() + " has no recorded operation.");
               } else {
                  record.setLastStressorOperation(lastOperation.getOperationId());
               }
            } catch (Exception e) {
               log.error("Failed to read last operation key for thread " + record.getThreadId(), e);
            }
         }
         for (;;) {
            boolean allChecked = true;
            for (int i = 0; i < totalThreads; ++i) {
               AbstractStressorRecord record = allRecords.get(i);
               if (record == null) continue;
               if (record.getOperationId() <= record.getLastStressorOperation()) {
                  if (log.isTraceEnabled()) {
                     log.trace(String.format("Currently checked operation for thread %d is %d (key id %08X), last written is %d",
                           record.getThreadId(), record.getOperationId(), record.getKeyId(), record.getLastStressorOperation()));
                  }
                  allChecked = false;
                  break;
               }
            }
            if (lastStoredOperationTimestamp + timeout < System.currentTimeMillis()) {
               String error = "Waiting for checkers timed out after " + (System.currentTimeMillis() - lastStoredOperationTimestamp) + " ms";
               log.error(error);
               return error;
            }
            if (allChecked) {
               StringBuilder sb = new StringBuilder("All checks OK: ");
               for (int i = 0; i < totalThreads; ++i) {
                  AbstractStressorRecord record = allRecords.get(i);
                  if (record == null) continue;
                  sb.append(record.getThreadId()).append("# ")
                        .append(record.getOperationId()).append(" (")
                        .append(record.getLastStressorOperation()).append("), ");
               }
               log.debug(sb.toString());
               return null;
            }
            try {
               Thread.sleep(1000);
            } catch (InterruptedException e) {
               log.error("Interrupted waiting for checkers.", e);
               return e.toString();
            }
         }
      }

      protected void notify(int threadId, long operationId, Object key) {
         AbstractStressorRecord record = allRecords.get(threadId);
         record.notify(operationId, key);
      }

      protected void requireNotify(int threadId, long operationId) {
         AbstractStressorRecord record = allRecords.get(threadId);
         record.requireNotify(operationId);
      }

      protected void modified(Object key, Object value) {
         if (key instanceof String && ((String) key).startsWith(LAST_OPERATION_PREFIX)) {
            int threadId = Integer.parseInt(((String) key).substring(LAST_OPERATION_PREFIX.length()));
            LastOperation last = (LastOperation) value;
            requireNotify(threadId, last.getOperationId() + 1);
         }
      }
   }

   public static class LastOperation implements Serializable {
      private long operationId;
      private long seed;

      public LastOperation(long operationId, long seed) {
         this.operationId = operationId;
         this.seed = seed;
      }

      public long getOperationId() {
         return operationId;
      }

      public long getSeed() {
         return seed;
      }

      @Override
      public String toString() {
         return String.format("LastOperation{operationId=%d, seed=%016X}", operationId, seed);
      }
   }

   protected abstract static class AbstractStressorRecord {
      protected final Random rand;
      protected final int threadId;
      protected long currentKeyId;
      protected volatile long currentOp = -1;
      private long lastStressorOperation = -1;
      private long lastUnsuccessfulCheckTimestamp = Long.MIN_VALUE;
      private Set<Long> notifiedOps = new HashSet<Long>();
      private long requireNotify = Long.MAX_VALUE;

      public AbstractStressorRecord(long seed, int threadId, long operationId) {
         log.trace("Initializing record random with " + seed);
         this.rand = Utils.setRandomSeed(new Random(0), seed);
         this.threadId = threadId;
         this.currentOp = operationId;
      }

      public AbstractStressorRecord(Random rand, int threadId) {
         log.trace("Initializing record random with " + Utils.getRandomSeed(rand));
         this.rand = rand;
         this.threadId = threadId;
      }

      public abstract void next();

      public int getThreadId() {
         return threadId;
      }

      public long getLastStressorOperation() {
         return lastStressorOperation;
      }

      public void setLastStressorOperation(long lastStressorOperation) {
         this.lastStressorOperation = lastStressorOperation;
      }

      public long getLastUnsuccessfulCheckTimestamp() {
         return lastUnsuccessfulCheckTimestamp;
      }

      public void setLastUnsuccessfulCheckTimestamp(long lastUnsuccessfulCheckTimestamp) {
         this.lastUnsuccessfulCheckTimestamp = lastUnsuccessfulCheckTimestamp;
      }

      public long getKeyId() {
         return currentKeyId;
      }

      public long getOperationId() {
         return currentOp;
      }

      public synchronized void notify(long operationId, Object key) {
         if (operationId < currentOp || !notifiedOps.add(operationId)) {
            log.warn("Duplicit notification for operation " + operationId + " on key " + key);
         }
      }

      public synchronized void discardNotification(long operationId) {
         notifiedOps.remove(operationId);
         // temporary:
         for (long op : notifiedOps) {
            if (op < operationId) log.error("Old operation " + op + " in " + notifiedOps);
         }
      }

      public synchronized void requireNotify(long operationId) {
         if (operationId < requireNotify) {
            requireNotify = operationId;
         }
      }

      public synchronized boolean hasNotification(long operationId) {
         if (operationId < requireNotify) return true;
         return notifiedOps.contains(operationId);
      }
   }
}


text:
using content::BrowserThread;

namespace browser_sync {

PasswordDataTypeController::PasswordDataTypeController(
    ProfileSyncComponentsFactory* profile_sync_factory,
    Profile* profile)
    : NonUIDataTypeController(
          BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI),
          base::Bind(&ChromeReportUnrecoverableError),
          profile_sync_factory),
      profile_(profile) {
}

syncer::ModelType PasswordDataTypeController::type() const {
  return syncer::PASSWORDS;
}

syncer::ModelSafeGroup PasswordDataTypeController::model_safe_group()
    const {
  return syncer::GROUP_PASSWORD;
}

PasswordDataTypeController::~PasswordDataTypeController() {}

bool PasswordDataTypeController::PostTaskOnBackendThread(
      const tracked_objects::Location& from_here,
      const base::Closure& task) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (!password_store_.get())
    return false;
  return password_store_->ScheduleTask(task);
}

bool PasswordDataTypeController::StartModels() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK_EQ(MODEL_STARTING, state());
  password_store_ = PasswordStoreFactory::GetForProfile(
      profile_, Profile::EXPLICIT_ACCESS);
  return !!password_store_.get();
}

}  // namespace browser_sync


text:
package org.xdi.model.custom.script.type.session;

import java.util.Map;

import org.xdi.model.SimpleCustomProperty;

/**
 * Dummy implementation of interface ApplicationSessionType
 *
 * @author Yuriy Movchan Date: 12/30/2014
 */
public class DummyApplicationSessionType implements ApplicationSessionType {

    @Override
    public boolean init(Map<String, SimpleCustomProperty> configurationAttributes) {
        return true;
    }

    @Override
    public boolean destroy(Map<String, SimpleCustomProperty> configurationAttributes) {
        return true;
    }

    @Override
    public int getApiVersion() {
        return 1;
    }

    @Override
    public boolean endSession(Object httpRequest, Object authorizationGrant, Map<String, SimpleCustomProperty> configurationAttributes) {
        return false;
    }

}


text:
lang: en
title: Why black belt in judo do not equal a blue belt in BJJ ?
date: 2016-01-01 10:36 UTC
tags: opinion, en
cover: black-belt.jpg
---

As a former judo practitioner (black belt) I heard many different things on the belt I should get in BJJ:

 - If you have a black belt in Judo you automatically have a blue belt in BJJ.
 - I do not care what color of your Judo belt, you've just start BJJ so you'll be white.

READMORE

So first I will not lie, I'm still white belt in BJJ and I desperately want to get my blue belt.
However being blue belt in BJJ just because you have black belt in Judo is stupid and here is why:

## It's a different sport

The Gi are different, the techniques allowed are different.
Judo is highly focus on the stand up part, ground game exist but it's really different (I will detail this point later).
You can be a really good Judoka with lot of success without knowing shit on the ground.
Indeed if your throw is good, you can win all your fight without spending a second on the ground.
At worst if you know how to defend well, you'll get back to your feet to throw your next take down.

Personally ground game was my favorite part, but it not where you should focus to compete in Judo.

## Ground game in Judo is different

As I mentioned the rules are different. And it has an effect on what position you will work on the ground.
For instance, many ground technique in Judo start from the "turtle" position, because this is where you end up after a missed take down.

Because of the really short amount of time the pace is way faster.
In judo if you want to win on the ground you will have 30 seconds to finish it.
And pining somebody on his back for 25 sec is enough to win the fight.

In BJJ you have much more time and starting from the guard is much more likely to happen.
In Judo pulling the guard is not even an option because it will end up in loosing the fight.

## Judo will kill your BJJ

When I start to transition, many bad habit from Judo killed my BJJ session (even MMA in some cases).
The biggest problem is that Judokas don't mind exposing their back, and that's a terrible mistake (I learned it the hard way off course).
Also the leg lock is completely missing and the missing fear of it will make you an easy target.

## Judo will help your BJJ

However let's be honest BJJ and Judo are two side of the same coin.
The skill you will develop with Judo will also help you for the BJJ and in some specific case will give you an edge over pure BJJ practitioner.

Indeed a great balance first, you will be able to wrestle for the stand up part (pulling guard is nice but you can't do it forever). Also your control will be strong and if you can use the pressure and move in the same time your grappling level will be really strong.

## Two side of the same coin but two different side still

Because they are now two different sport and have different goal you can end up being really good in one sport and bad at the other.
However I think that this two sport belong to the art of grappling in general where you can also find wrestling, Sambo, catch wrestling ...

So even if don't have your blue belt in BJJ when you got your black belt in Judo.
I think you should be locking for something bigger, looking to be the best grappler possible :

 - Be able to throw the wrestler and the judoka
 - Submit the Jujitsu practitioner
 - Leg lock the Sambo fighter

To sum up just be a martial artist and only remember that the belt is only here to hold your Gi.


text:
.class public Lcn/com/smartdevices/bracelet/model/NavDrawerItem;
.super Ljava/lang/Object;

# instance fields
.field private count:Ljava/lang/String;

.field private icon:I

.field private isCounterVisible:Z

.field private title:Ljava/lang/String;

# direct methods
.method public constructor <init>()V
    .locals 1

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

    const-string v0, "0"

    iput-object v0, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->count:Ljava/lang/String;

    const/4 v0, 0x0

    iput-boolean v0, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->isCounterVisible:Z

    return-void
.end method

.method public constructor <init>(Ljava/lang/String;I)V
    .locals 1

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

    const-string v0, "0"

    iput-object v0, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->count:Ljava/lang/String;

    const/4 v0, 0x0

    iput-boolean v0, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->isCounterVisible:Z

    iput-object p1, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->title:Ljava/lang/String;

    iput p2, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->icon:I

    return-void
.end method

.method public constructor <init>(Ljava/lang/String;IZLjava/lang/String;)V
    .locals 1

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

    const-string v0, "0"

    iput-object v0, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->count:Ljava/lang/String;

    const/4 v0, 0x0

    iput-boolean v0, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->isCounterVisible:Z

    iput-object p1, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->title:Ljava/lang/String;

    iput p2, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->icon:I

    iput-boolean p3, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->isCounterVisible:Z

    iput-object p4, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->count:Ljava/lang/String;

    return-void
.end method

# virtual methods
.method public getCount()Ljava/lang/String;
    .locals 1

    iget-object v0, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->count:Ljava/lang/String;

    return-object v0
.end method

.method public getCounterVisibility()Z
    .locals 1

    iget-boolean v0, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->isCounterVisible:Z

    return v0
.end method

.method public getIcon()I
    .locals 1

    iget v0, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->icon:I

    return v0
.end method

.method public getTitle()Ljava/lang/String;
    .locals 1

    iget-object v0, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->title:Ljava/lang/String;

    return-object v0
.end method

.method public setCount(Ljava/lang/String;)V
    .locals 0

    iput-object p1, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->count:Ljava/lang/String;

    return-void
.end method

.method public setCounterVisibility(Z)V
    .locals 0

    iput-boolean p1, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->isCounterVisible:Z

    return-void
.end method

.method public setIcon(I)V
    .locals 0

    iput p1, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->icon:I

    return-void
.end method

.method public setTitle(Ljava/lang/String;)V
    .locals 0

    iput-object p1, p0, Lcn/com/smartdevices/bracelet/model/NavDrawerItem;->title:Ljava/lang/String;

    return-void
.end method


text:
'use strict';

module.exports = {
    toOrdinal: require('./toOrdinal'),
    toWords: require('./toWords'),
    toWordsOrdinal: require('./toWordsOrdinal')
};


text:
package edu.wpi.first.wpilibj.templates;

import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.Joystick;
import judge.util.JoystickButton;

/**
 * Controls the shooting mechanism
 *
 * @author (Mark Macerato)
 */
public class Shooter {

    private Joystick driver = new Joystick(2);
    private Joystick shooter = new Joystick(1);
    private Jaguar shooterBL = new Jaguar(2, 1);
    private Jaguar shooterBR = new Jaguar(2, 2);
    private Jaguar shooterML = new Jaguar(2, 3);
    private Jaguar shooterMR = new Jaguar(2, 4);
    private Jaguar shooterFL = new Jaguar(2, 5);
    private Jaguar shooterFR = new Jaguar(2, 6);
    private JoystickButton driver4 = new JoystickButton(driver, 4);
    private JoystickButton driver6 = new JoystickButton(driver, 6);
    private JoystickButton shooter4 = new JoystickButton(shooter, 4);
    private JoystickButton shooter6 = new JoystickButton(shooter, 6);
    private double setSpeed = 0.0;
    private DriverStation driverStation = new DriverStation();

    public void setAllMotors(double speed) {
        if (speed <= 0) {
            shooterFL.set(-speed);
            shooterFR.set(speed);
            shooterML.set(-speed);
            shooterMR.set(speed);
            shooterBL.set(-speed);
            shooterBR.set(speed);
        } else {
            shooterFL.set(-speed);
            shooterFR.set(speed);
            shooterML.set(-speed);
            shooterMR.set(speed);
            shooterBL.set(-speed);
            shooterBR.set(speed);
        }
    }

    public void shoot() {

        setSpeed = 0.5 * ((-1 * shooter.getThrottle()) + 1);

        if (driver4.IsPressed() || shooter4.IsPressed()) {
            setAllMotors(setSpeed);
        } else if (driver6.IsPressed() || shooter6.IsPressed()) {
            setAllMotors(setSpeed * -1);
        } else {
            setAllMotors(0.0);
        }

        driverStation.print("Speed is: " + setSpeed);
    }
}


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateProjectsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('projects', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('name')->unique();
			$table->string('description', 1000);
			$table->integer('mr');
			$table->integer('ir');
			$table->integer('pr');
			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('projects');
	}

}


text:
namespace mjkgb {

using namespace std;
using namespace llvm;
using namespace llvm::legacy;

extern "C" const char _binary_opcodes_bc_start[];
extern "C" const char _binary_opcodes_bc_end[];

class Compiler::impl {
public:
    impl()
      : opcodes_(),
        context_(),
        pm_(),
        mod_(nullptr),
        ee_(nullptr),
        gb_type_(nullptr),
        gb_type_ptr_(nullptr),
        opcode_type_(nullptr)
    {
        LLVMInitializeNativeTarget();
        size_t size = _binary_opcodes_bc_end - _binary_opcodes_bc_start;
        auto buffer = MemoryBuffer::getMemBuffer(StringRef{_binary_opcodes_bc_start, size}, "", false);

        mod_ = parseBitcodeFile(buffer, context_).get();
        ee_ = EngineBuilder(mod_).create();

        gb_type_ = mod_->getTypeByName("struct.mjkgb::GameboyImpl");
        gb_type_ptr_ = PointerType::getUnqual(gb_type_);
        opcode_type_= FunctionType::get(Type::getVoidTy(context_), { gb_type_ptr_ }, false);

        pm_.add(createVerifierPass());
        pm_.add(createCFGSimplificationPass());
        pm_.add(createPromoteMemoryToRegisterPass());
        pm_.add(createGlobalOptimizerPass());
        pm_.add(createGlobalDCEPass());
        pm_.add(createFunctionInliningPass());
        pm_.add(createStripSymbolsPass());

        opcodes_ = {
#define X(name, def, is_jump, cycles) mod_->getFunction(#name),
#include "opcode_map.in"
#include "cb_opcode_map.in"
#undef X
        };
    }

    uintptr_t compile(uint16_t address, const std::vector<uint8_t> &block)
    {
        auto name = "jit_" + to_string(address);
        auto func = Function::Create(opcode_type_, Function::ExternalLinkage, name, mod_);

        auto gb = static_cast<Value *>(func->arg_begin());
        gb->setName("gb");

        auto entry = BasicBlock::Create(context_, "entry", func);
        auto builder = IRBuilder<>{entry};

        auto is_cb = false;
        for (const auto &op : block) {
            builder.CreateCall(opcodes_[op + (is_cb ? 256 : 0)], gb);
            is_cb = op == 0xcb;
        }

        builder.CreateRetVoid();

        pm_.run(*mod_);

        return reinterpret_cast<uintptr_t>(ee_->getPointerToFunction(func));
    }

private:
    std::array<Function *, 512> opcodes_;

    LLVMContext context_;
    PassManager pm_;
    Module *mod_;
    ExecutionEngine *ee_;
    Type *gb_type_;
    Type *gb_type_ptr_;
    FunctionType *opcode_type_;
};

Compiler::Compiler()
  : pimpl_(new Compiler::impl)
{ }

Compiler::~Compiler()
{ }

uintptr_t Compiler::compile(uint16_t address, const std::vector<uint8_t> &block)
{
    return pimpl_->compile(address, block);
}

}


text:
[![Build Status](https://travis-ci.com/WTW-IM/es-components.svg?branch=master)](https://travis-ci.com/WTW-IM/es-components)
[![npm version](https://badge.fury.io/js/es-components.svg)](https://badge.fury.io/js/es-components)

## Documentation and Demos

[https://wtw-im.github.io/es-components/](https://wtw-im.github.io/es-components/)

## Installation and Usage

```shell
npm install --save es-components
```

`es-components` comes optimized for tree shaking. If your build tool does not support tree shaking please direct your imports towards `es-components/lib`.
You may use either direct file paths or destructure from the index file.

```js
// use this to keep the size of your bundles light
import Component from 'es-components/lib/path/to/component';
// or
import { Component } from 'es-components/lib';
```

### Using The UMD Bundle

Because ES Components needs a reference to `document.body` on startup, you must either include the `defer` attribute, or place the `<script>` tag somwhere within the `body` of your html page. Here we're showing it using the `defer` attribute.

```html
<!DOCTYPE html>
<head>
  <meta charset="UTF-8" />
  <title>My ES Components Site</title>
  <!-- These fonts are used by es-components -->
  <link rel="stylesheet" href="https://bdaim-webexcdn-p.azureedge.net/es-assets/icons.css" />
  <link rel="stylesheet" href="https://bdaim-webexcdn-p.azureedge.net/es-assets/source-sans-pro.css" />
  <!-- You must include React, ReactDOM, PropTypes and Styled Components. ES Components depends on those packages. -->
  <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
  <script crossorigin src="https://unpkg.com/prop-types@15/prop-types.js"></script>
  <script crossorigin src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>
  <script crossorigin defer src="https://unpkg.com/es-components/bundle/main.min.js"></script>
</head>

<body>
  <!-- My ES Components Site Body -->
</body>
```