text:
package com.faforever.client.game;

import com.faforever.client.domain.GameBean;
import com.faforever.client.fx.Controller;
import com.faforever.client.fx.DecimalCell;
import com.faforever.client.fx.IconCell;
import com.faforever.client.fx.JavaFxUtil;
import com.faforever.client.fx.StringCell;
import com.faforever.client.i18n.I18n;
import com.faforever.client.map.MapService;
import com.faforever.client.map.MapService.PreviewSize;
import com.faforever.client.player.PlayerService;
import com.faforever.client.preferences.PreferencesService;
import com.faforever.client.theme.UiService;
import com.faforever.commons.lobby.GameType;
import com.google.common.base.Joiner;
import javafx.beans.InvalidationListener;
import javafx.beans.binding.Bindings;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.collections.transformation.SortedList;
import javafx.css.PseudoClass;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.SortEvent;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.SortType;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Component
@RequiredArgsConstructor
public class GamesTableController implements Controller<Node> {

  private static final PseudoClass FRIEND_IN_GAME_PSEUDO_CLASS = PseudoClass.getPseudoClass("friendInGame");

  private final ObjectProperty<GameBean> selectedGame = new SimpleObjectProperty<>();
  private final MapService mapService;
  private final JoinGameHelper joinGameHelper;
  private final I18n i18n;
  private final UiService uiService;
  private final PreferencesService preferencesService;
  private final PlayerService playerService;
  public TableView<GameBean> gamesTable;
  public TableColumn<GameBean, Image> mapPreviewColumn;
  public TableColumn<GameBean, String> gameTitleColumn;
  public TableColumn<GameBean, PlayerFill> playersColumn;
  public TableColumn<GameBean, Number> averageRatingColumn;
  public TableColumn<GameBean, RatingRange> ratingRangeColumn;
  public TableColumn<GameBean, Map<String, String>> modsColumn;
  public TableColumn<GameBean, String> hostColumn;
  public TableColumn<GameBean, Boolean> passwordProtectionColumn;
  public TableColumn<GameBean, String> coopMissionName;
  private GameTooltipController gameTooltipController;
  private Tooltip tooltip;

  private final InvalidationListener tooltipShowingListener = observable -> {
    if (tooltip.isShowing()) {
      gameTooltipController.displayGame();
    } else {
      gameTooltipController.setGame(null);
    }
  };
  private final InvalidationListener selectedItemListener = observable -> JavaFxUtil.runLater(() -> selectedGame.setValue(gamesTable.getSelectionModel()
      .getSelectedItem()));

  public ObjectProperty<GameBean> selectedGameProperty() {
    return selectedGame;
  }

  public Node getRoot() {
    return gamesTable;
  }

  public void initializeGameTable(ObservableList<GameBean> games) {
    initializeGameTable(games, null, true);
  }

  public void initializeGameTable(ObservableList<GameBean> games, Function<String, String> coopMissionNameProvider, boolean listenToFilterPreferences) {
    gameTooltipController = uiService.loadFxml("theme/play/game_tooltip.fxml");
    tooltip = JavaFxUtil.createCustomTooltip(gameTooltipController.getRoot());
    JavaFxUtil.addListener(tooltip.showingProperty(), tooltipShowingListener);

    SortedList<GameBean> sortedList = new SortedList<>(games);
    sortedList.comparatorProperty().bind(gamesTable.comparatorProperty());
    gamesTable.setPlaceholder(new Label(i18n.get("games.noGamesAvailable")));
    gamesTable.setRowFactory(param1 -> gamesRowFactory());
    gamesTable.setItems(sortedList);

    applyLastSorting(gamesTable);
    gamesTable.setOnSort(this::onColumnSorted);

    passwordProtectionColumn.setCellValueFactory(param -> param.getValue().passwordProtectedProperty());
    passwordProtectionColumn.setCellFactory(param -> passwordIndicatorColumn());

    mapPreviewColumn.setCellFactory(param -> new MapPreviewTableCell(uiService));
    mapPreviewColumn.setCellValueFactory(param -> Bindings.createObjectBinding(
        () -> mapService.loadPreview(param.getValue().getMapFolderName(), PreviewSize.SMALL),
        param.getValue().mapFolderNameProperty()
    ));

    gameTitleColumn.setCellValueFactory(param -> param.getValue().titleProperty());
    gameTitleColumn.setCellFactory(param -> new StringCell<>(StringUtils::normalizeSpace));
    playersColumn.setCellValueFactory(param -> Bindings.createObjectBinding(
        () -> new PlayerFill(param.getValue().getNumActivePlayers(), param.getValue().getMaxPlayers()),
        param.getValue().teamsProperty())
    );
    playersColumn.setCellFactory(param -> playersCell());
    ratingRangeColumn.setCellValueFactory(param -> new SimpleObjectProperty<>(new RatingRange(param.getValue().getRatingMin(), param.getValue().getRatingMax())));
    ratingRangeColumn.setCellFactory(param -> ratingTableCell());
    hostColumn.setCellValueFactory(param -> param.getValue().hostProperty());
    hostColumn.setCellFactory(param -> new HostTableCell(playerService));
    modsColumn.setCellValueFactory(param -> param.getValue().simModsProperty());
    modsColumn.setCellFactory(param -> new StringCell<>(this::convertSimModsToContent));
    coopMissionName.setVisible(coopMissionNameProvider != null);

    if (averageRatingColumn != null) {
      averageRatingColumn.setCellValueFactory(param -> Bindings.createDoubleBinding(() -> param.getValue()
          .getAverageRating(), param.getValue().teamsProperty()));
      averageRatingColumn.setCellFactory(param -> new DecimalCell<>(
          new DecimalFormat("0"),
          number -> Math.round(number.doubleValue() / 100.0) * 100.0)
      );
    }

    if (coopMissionNameProvider != null) {
      coopMissionName.setCellFactory(param -> new StringCell<>(name -> name));
      coopMissionName.setCellValueFactory(param -> new SimpleObjectProperty<>(coopMissionNameProvider.apply(param.getValue().getMapFolderName())));
    }

    JavaFxUtil.addListener(gamesTable.getSelectionModel().selectedItemProperty(), selectedItemListener);

    //bindings do not work as that interferes with some bidirectional bindings in the TableView itself
    if (listenToFilterPreferences && coopMissionNameProvider == null) {
      JavaFxUtil.addAndTriggerListener(preferencesService.getPreferences().hideModdedGamesProperty(), observable -> modsColumn.setVisible(!preferencesService.getPreferences().isHideModdedGames()));
      JavaFxUtil.addAndTriggerListener(preferencesService.getPreferences().hidePrivateGamesProperty(), observable -> passwordProtectionColumn.setVisible(!preferencesService.getPreferences().isHidePrivateGames()));
    }

    selectFirstGame();
  }

  private void selectFirstGame() {
    if (!gamesTable.getItems().isEmpty()) {
      gamesTable.getSelectionModel().selectFirst();
    }
  }

  private void applyLastSorting(TableView<GameBean> gamesTable) {
    final Map<String, SortType> lookup = new HashMap<>(preferencesService.getPreferences().getGameTableSorting());
    final ObservableList<TableColumn<GameBean, ?>> sortOrder = gamesTable.getSortOrder();
    sortOrder.clear();
    gamesTable.getColumns().forEach(gameTableColumn -> {
      if (lookup.containsKey(gameTableColumn.getId())) {
        gameTableColumn.setSortType(lookup.get(gameTableColumn.getId()));
        sortOrder.add(gameTableColumn);
      }
    });
  }

  private void onColumnSorted(@NotNull SortEvent<TableView<GameBean>> event) {
    ObservableMap<String, SortType> gameListSorting = preferencesService.getPreferences().getGameTableSorting();

    gameListSorting.clear();
    event.getSource().getSortOrder()
        .forEach(column -> gameListSorting.put(column.getId(), column.getSortType()));

    preferencesService.storeInBackground();
  }

  @NotNull
  private String convertSimModsToContent(Map<String, String> simMods) {
    List<String> modNames = simMods.values().stream()
        .limit(2)
        .collect(Collectors.toList());

    if (simMods.size() > 2) {
      return i18n.get("game.mods.twoAndMore", modNames.get(0), simMods.size() - 1);
    }
    return Joiner.on(i18n.get("textSeparator")).join(modNames);
  }

  @NotNull
  private TableRow<GameBean> gamesRowFactory() {
    TableRow<GameBean> row = new TableRow<>() {
      @Override
      protected void updateItem(GameBean game, boolean empty) {
        super.updateItem(game, empty);
        if (empty || game == null) {
          setTooltip(null);
          pseudoClassStateChanged(FRIEND_IN_GAME_PSEUDO_CLASS, false);
        } else {
          setTooltip(tooltip);
          pseudoClassStateChanged(FRIEND_IN_GAME_PSEUDO_CLASS, playerService.areFriendsInGame(game)
              && game.getGameType() != GameType.COOP); // do not highlight coop games
        }
      }
    };
    row.setOnMouseClicked(event -> {
      if (event.getClickCount() == 2) {
        GameBean game = row.getItem();
        joinGameHelper.join(game);
      }
    });
    row.setOnMouseEntered(event -> {
      if (row.getItem() == null) {
        return;
      }
      GameBean game = row.getItem();
      gameTooltipController.setGame(game);
      if (tooltip.isShowing()) {
        gameTooltipController.displayGame();
      }
    });
    return row;
  }

  private TableCell<GameBean, Boolean> passwordIndicatorColumn() {
    return new IconCell<>(
        isPasswordProtected -> isPasswordProtected ? "lock-icon" : "");
  }

  private TableCell<GameBean, PlayerFill> playersCell() {
    return new StringCell<>(playerFill -> i18n.get("game.players.format",
        playerFill.getPlayers(), playerFill.getMaxPlayers()));
  }

  private TableCell<GameBean, RatingRange> ratingTableCell() {
    return new StringCell<>(ratingRange -> {
      if (ratingRange.getMin() == null && ratingRange.getMax() == null) {
        return "";
      }

      if (ratingRange.getMin() != null && ratingRange.getMax() != null) {
        return i18n.get("game.ratingFormat.minMax", ratingRange.getMin(), ratingRange.getMax());
      }

      if (ratingRange.getMin() != null) {
        return i18n.get("game.ratingFormat.minOnly", ratingRange.getMin());
      }

      return i18n.get("game.ratingFormat.maxOnly", ratingRange.getMax());
    });
  }

  public TableColumn<GameBean, Image> getMapPreviewColumn() {
    return mapPreviewColumn;
  }

  public TableColumn<GameBean, RatingRange> getRatingRangeColumn() {
    return ratingRangeColumn;
  }

  public void removeListeners() {
    JavaFxUtil.removeListener(tooltip.showingProperty(), tooltipShowingListener);
    JavaFxUtil.removeListener(gamesTable.getSelectionModel().selectedItemProperty(), selectedItemListener);
  }
}


text:
<!doctype html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Educa.io</title>
    <link rel="stylesheet" href="css/normalize.css" />
    <link rel="stylesheet" href="css/foundation.css" />
    <link rel="stylesheet" href="css/custom.css" />
    <link href='http://fonts.googleapis.com/css?family=Oswald:400,700,300' rel='stylesheet' type='text/css'>
      <link href='http://fonts.googleapis.com/css?family=Cabin:400,500' rel='stylesheet' type='text/css'>

educa.io

Categorías

Diseño

Animación

3D

Programación

Fotografía

Juegos

Aplicaciones

Inkscape

Blender

Gimp

{{curso.titulo}}

                Por: {{curso.autor}}

redpajama_set_name: RedPajamaGithub


text:
<title>InsertJSONMap</title>

InsertJSONMap()

Syntax

InsertJSONMap(JSONValue, Map())

Description

Insert the specified Map() into the given JSON value. The JSON value will be
changed to type #PB_JSON_Object.

Parameters

JSONValue

The JSON value. The previous content of the value will be changed to the
contant of the Map().

Map()

The map to insert into the JSON value.

Return value

None.

Example

  NewMap Colors()
  Colors("red")   = $0000FF
  Colors("green") = $00FF00
  Colors("blue")  = $FF0000

  If CreateJSON(0)
    InsertJSONMap(JSONValue(0), Colors())
    Debug ComposeJSON(0, #PB_JSON_PrettyPrint)
  EndIf

See Also

InsertJSONArray(), InsertJSONList(), InsertJSONStructure(),
ExtractJSONArray(), ExtractJSONList(), ExtractJSONMap(), ExtractJSONStructure(),

Supported OS
All

<- InsertJSONList() - Json Index - InsertJSONStructure() ->


text:
#include "config.h"
#include "JSText.h"

#include "Text.h"

using namespace JSC;

namespace WebCore {

JSValue toJSNewlyCreated(ExecState* exec, JSDOMGlobalObject* globalObject, Text* text)
{
    if (!text)
        return jsNull();

    return CREATE_DOM_NODE_WRAPPER(exec, globalObject, Text, text);
}

} // namespace WebCore


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="BitMap" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
	<brief_description>
		Boolean matrix.
	</brief_description>
	<description>
		A two-dimensional array of boolean values, can be used to efficiently store a binary matrix (every matrix element takes only one bit) and query the values using natural cartesian coordinates.
	</description>
	<tutorials>
	</tutorials>
	<methods>
		<method name="convert_to_image" qualifiers="const">
			<return type="Image" />
			<description>
				Returns an image of the same size as the bitmap and with a [enum Image.Format] of type [code]FORMAT_L8[/code]. [code]true[/code] bits of the bitmap are being converted into white pixels, and [code]false[/code] bits into black.
			</description>
		</method>
		<method name="create">
			<return type="void" />
			<param index="0" name="size" type="Vector2" />
			<description>
				Creates a bitmap with the specified size, filled with [code]false[/code].
			</description>
		</method>
		<method name="create_from_image_alpha">
			<return type="void" />
			<param index="0" name="image" type="Image" />
			<param index="1" name="threshold" type="float" default="0.1" />
			<description>
				Creates a bitmap that matches the given image dimensions, every element of the bitmap is set to [code]false[/code] if the alpha value of the image at that position is equal to [code]threshold[/code] or less, and [code]true[/code] in other case.
			</description>
		</method>
		<method name="get_bit" qualifiers="const">
			<return type="bool" />
			<param index="0" name="position" type="Vector2" />
			<description>
				Returns bitmap's value at the specified position.
			</description>
		</method>
		<method name="get_size" qualifiers="const">
			<return type="Vector2" />
			<description>
				Returns bitmap's dimensions.
			</description>
		</method>
		<method name="get_true_bit_count" qualifiers="const">
			<return type="int" />
			<description>
				Returns the amount of bitmap elements that are set to [code]true[/code].
			</description>
		</method>
		<method name="grow_mask">
			<return type="void" />
			<param index="0" name="pixels" type="int" />
			<param index="1" name="rect" type="Rect2" />
			<description>
				Applies morphological dilation or erosion to the bitmap. If [code]pixels[/code] is positive, dilation is applied to the bitmap. If [code]pixels[/code] is negative, erosion is applied to the bitmap. [code]rect[/code] defines the area where the morphological operation is applied. Pixels located outside the [code]rect[/code] are unaffected by [method grow_mask].
			</description>
		</method>
		<method name="opaque_to_polygons" qualifiers="const">
			<return type="Array" />
			<param index="0" name="rect" type="Rect2" />
			<param index="1" name="epsilon" type="float" default="2.0" />
			<description>
				Creates an [Array] of polygons covering a rectangular portion of the bitmap. It uses a marching squares algorithm, followed by Ramer-Douglas-Peucker (RDP) reduction of the number of vertices. Each polygon is described as a [PackedVector2Array] of its vertices.
				To get polygons covering the whole bitmap, pass:
				[codeblock]
				Rect2(Vector2(), get_size())
				[/codeblock]
				[code]epsilon[/code] is passed to RDP to control how accurately the polygons cover the bitmap: a lower [code]epsilon[/code] corresponds to more points in the polygons.
			</description>
		</method>
		<method name="resize">
			<return type="void" />
			<param index="0" name="new_size" type="Vector2" />
			<description>
				Resizes the image to [code]new_size[/code].
			</description>
		</method>
		<method name="set_bit">
			<return type="void" />
			<param index="0" name="position" type="Vector2" />
			<param index="1" name="bit" type="bool" />
			<description>
				Sets the bitmap's element at the specified position, to the specified value.
			</description>
		</method>
		<method name="set_bit_rect">
			<return type="void" />
			<param index="0" name="rect" type="Rect2" />
			<param index="1" name="bit" type="bool" />
			<description>
				Sets a rectangular portion of the bitmap to the specified value.
			</description>
		</method>
	</methods>
</class>


text:
using System;
using System.Collections;
using System.Text;
using Xunit;

namespace System.Collections.HashtableTests
{
    public class ContainsKeyTests
    {
        [Fact]
        public void TestContainKeyBasic()
        {
            StringBuilder sblMsg = new StringBuilder(99);

            Hashtable ht1 = null;

            string s1 = null;
            string s2 = null;

            int i = 0;

            ht1 = new Hashtable(); //default constructor
            Assert.False(ht1.ContainsKey("No_Such_Key"));

            // add few key-val pairs
            ht1 = new Hashtable();
            for (i = 0; i < 100; i++)
            {
                sblMsg = new StringBuilder(99);
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg = new StringBuilder(99);
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();
                ht1.Add(s1, s2);
            }

            for (i = 0; i < ht1.Count; i++)
            {
                sblMsg = new StringBuilder(99);
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                Assert.True(ht1.ContainsKey(s1));
            }

            //
            // [] Remove a key and then check
            //
            sblMsg = new StringBuilder(99);
            sblMsg.Append("key_50");
            s1 = sblMsg.ToString();

            ht1.Remove(s1); //removes "Key_50"

            //check whether the key is removed or not
            Assert.False(ht1.ContainsKey(s1));
        }
    }
}


text:
Test implementation of [TodoMVC](http://todomvc.com/) using:

- [React](https://facebook.github.io/react/)
- [Redux](http://redux.js.org/)
- [Jest](https://facebook.github.io/jest/)
- [webpack](https://webpack.github.io/)
- [TypeScript](http://www.typescriptlang.org/)

### Alternate Implementations
- [Vanilla React](https://github.com/markschabacker/todoMVC_react/tree/impl/no-redux)
- [Redux](https://github.com/markschabacker/todoMVC_react/tree/impl/redux)
- [Redux with Async Actions](https://github.com/markschabacker/todoMVC_react/tree/impl/redux-async)


text:
#ifndef WorkerWebSocketChannel_h
#define WorkerWebSocketChannel_h

#include "core/frame/ConsoleTypes.h"
#include "modules/websockets/WebSocketChannel.h"
#include "modules/websockets/WebSocketChannelClient.h"
#include "platform/heap/Handle.h"
#include "wtf/Assertions.h"
#include "wtf/Forward.h"
#include "wtf/OwnPtr.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
#include "wtf/text/WTFString.h"
#include <stdint.h>

namespace blink {

class BlobDataHandle;
class KURL;
class ExecutionContext;
class ExecutionContextTask;
class WebSocketChannelSyncHelper;
class WorkerGlobalScope;
class WorkerLoaderProxy;

class WorkerWebSocketChannel final : public WebSocketChannel {
    WTF_MAKE_NONCOPYABLE(WorkerWebSocketChannel);
public:
    static WebSocketChannel* create(WorkerGlobalScope& workerGlobalScope, WebSocketChannelClient* client, const String& sourceURL, unsigned lineNumber)
    {
        return new WorkerWebSocketChannel(workerGlobalScope, client, sourceURL, lineNumber);
    }
    ~WorkerWebSocketChannel() override;

    // WebSocketChannel functions.
    bool connect(const KURL&, const String& protocol) override;
    void send(const CString&) override;
    void send(const DOMArrayBuffer&, unsigned byteOffset, unsigned byteLength) override;
    void send(PassRefPtr<BlobDataHandle>) override;
    void sendTextAsCharVector(PassOwnPtr<Vector<char>>) override
    {
        ASSERT_NOT_REACHED();
    }
    void sendBinaryAsCharVector(PassOwnPtr<Vector<char>>) override
    {
        ASSERT_NOT_REACHED();
    }
    void close(int code, const String& reason) override;
    void fail(const String& reason, MessageLevel, const String&, unsigned) override;
    void disconnect() override; // Will suppress didClose().

    DECLARE_VIRTUAL_TRACE();

    class Bridge;
    // Allocated in the worker thread, but used in the main thread.
    class Peer final : public GarbageCollectedFinalized<Peer>, public WebSocketChannelClient {
        USING_GARBAGE_COLLECTED_MIXIN(Peer);
        WTF_MAKE_NONCOPYABLE(Peer);
    public:
        Peer(Bridge*, PassRefPtr<WorkerLoaderProxy>, WebSocketChannelSyncHelper*);
        ~Peer() override;

        // sourceURLAtConnection and lineNumberAtConnection parameters may
        // be shown when the connection fails.
        void initialize(const String& sourceURLAtConnection, unsigned lineNumberAtConnection, ExecutionContext*);

        void connect(const KURL&, const String& protocol);
        void sendTextAsCharVector(PassOwnPtr<Vector<char>>);
        void sendBinaryAsCharVector(PassOwnPtr<Vector<char>>);
        void sendBlob(PassRefPtr<BlobDataHandle>);
        void close(int code, const String& reason);
        void fail(const String& reason, MessageLevel, const String& sourceURL, unsigned lineNumber);
        void disconnect();

        DECLARE_VIRTUAL_TRACE();

        // WebSocketChannelClient functions.
        void didConnect(const String& subprotocol, const String& extensions) override;
        void didReceiveTextMessage(const String& payload) override;
        void didReceiveBinaryMessage(PassOwnPtr<Vector<char>>) override;
        void didConsumeBufferedAmount(uint64_t) override;
        void didStartClosingHandshake() override;
        void didClose(ClosingHandshakeCompletionStatus, unsigned short code, const String& reason) override;
        void didError() override;

    private:
        Member<Bridge> m_bridge;
        RefPtr<WorkerLoaderProxy> m_loaderProxy;
        Member<WebSocketChannel> m_mainWebSocketChannel;
        Member<WebSocketChannelSyncHelper> m_syncHelper;
    };

    // Bridge for Peer. Running on the worker thread.
    class Bridge final : public GarbageCollectedFinalized<Bridge> {
        WTF_MAKE_NONCOPYABLE(Bridge);
        USING_PRE_FINALIZER(Bridge, peerShouldBeDisconnected);
    public:
        Bridge(WebSocketChannelClient*, WorkerGlobalScope&);
        ~Bridge();
        // sourceURLAtConnection and lineNumberAtConnection parameters may
        // be shown when the connection fails.
        void initialize(const String& sourceURLAtConnection, unsigned lineNumberAtConnection);
        bool connect(const KURL&, const String& protocol);
        void send(const CString& message);
        void send(const DOMArrayBuffer&, unsigned byteOffset, unsigned byteLength);
        void send(PassRefPtr<BlobDataHandle>);
        void close(int code, const String& reason);
        void fail(const String& reason, MessageLevel, const String& sourceURL, unsigned lineNumber);
        void disconnect();

        // Returns null when |disconnect| has already been called.
        WebSocketChannelClient* client() { return m_client; }

        DECLARE_TRACE();

    private:
        // Returns false if shutdown event is received before method completion.
        bool waitForMethodCompletion(PassOwnPtr<ExecutionContextTask>);
        void peerShouldBeDisconnected();

        Member<WebSocketChannelClient> m_client;
        RefPtrWillBeMember<WorkerGlobalScope> m_workerGlobalScope;
        RefPtr<WorkerLoaderProxy> m_loaderProxy;
        Member<WebSocketChannelSyncHelper> m_syncHelper;
        Member<Peer> m_peer;
    };

private:
    WorkerWebSocketChannel(WorkerGlobalScope&, WebSocketChannelClient*, const String& sourceURL, unsigned lineNumber);

    Member<Bridge> m_bridge;
    String m_sourceURLAtConnection;
    unsigned m_lineNumberAtConnection;
};

} // namespace blink

#endif // WorkerWebSocketChannel_h


text:
using System.Linq;
using NUnit.Framework;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Game.Graphics;
using osu.Game.Graphics.UserInterfaceV2;
using osu.Game.Overlays;
using osu.Game.Overlays.Settings;

namespace osu.Game.Tests.Visual.UserInterface
{
    public class TestSceneRoundedButton : ThemeComparisonTestScene
    {
        private readonly BindableBool enabled = new BindableBool(true);

        protected override Drawable CreateContent()
        {
            return new FillFlowContainer
            {
                RelativeSizeAxes = Axes.Both,
                Children = new Drawable[]
                {
                    new RoundedButton
                    {
                        Width = 400,
                        Text = "Test button",
                        Anchor = Anchor.Centre,
                        Origin = Anchor.Centre,
                        Enabled = { BindTarget = enabled },
                    },
                    new SettingsButton
                    {
                        Text = "Test button",
                        Anchor = Anchor.Centre,
                        Origin = Anchor.Centre,
                        Enabled = { BindTarget = enabled },
                    },
                }
            };
        }

        [Test]
        public void TestDisabled()
        {
            AddToggleStep("toggle disabled", disabled => enabled.Value = !disabled);
        }

        [Test]
        public void TestBackgroundColour()
        {
            AddStep("set red scheme", () => CreateThemedContent(OverlayColourScheme.Red));
            AddAssert("rounded button has correct colour", () => Cell(0, 1).ChildrenOfType<RoundedButton>().First().BackgroundColour == new OsuColour().Blue3);
            AddAssert("settings button has correct colour", () => Cell(0, 1).ChildrenOfType<SettingsButton>().First().BackgroundColour == new OverlayColourProvider(OverlayColourScheme.Red).Highlight1);
        }
    }
}


text:
layout: page
title: Peak Music Party
date: 2016-05-24
author: Howard Sullivan
tags: weekly links, java
status: published
summary: Donec odio augue, pulvinar eu.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 10/03/2017
  endDate: 10/08/2017
  ctyhocn: DECFRHX
  groupCode: PMP
published: true
---
Sed accumsan, felis eu bibendum finibus, arcu nisl consequat lorem, sit amet scelerisque metus massa non nibh. Morbi at diam imperdiet, varius massa sit amet, iaculis leo. Cras sagittis interdum velit, eget auctor nisl dictum at. Suspendisse blandit nec erat nec tristique. Sed consequat fermentum dignissim. In hac habitasse platea dictumst. Duis accumsan posuere justo in finibus. Morbi aliquet sem diam, quis blandit dolor sodales ac. Proin quis lacus bibendum, vulputate erat id, fringilla nibh. Proin euismod gravida sapien ornare volutpat. Duis tristique purus eget massa ultrices consectetur.
Praesent semper venenatis dignissim. Quisque justo purus, dignissim eget turpis a, egestas maximus ante. Praesent euismod sem mi, vel venenatis enim efficitur eget. Praesent massa eros, hendrerit at cursus eget, feugiat a ex. Ut ipsum odio, suscipit nec lorem quis, sodales laoreet elit. Etiam ultrices urna ultricies, suscipit neque ullamcorper, gravida metus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

1 Vestibulum vehicula erat eget purus finibus, iaculis fringilla mauris scelerisque
1 Vestibulum id turpis at turpis laoreet cursus quis in ligula
1 Aliquam ut dolor sed ipsum porta sagittis
1 Fusce faucibus turpis id sodales porttitor
1 Praesent eu orci condimentum nisl blandit porttitor
1 Phasellus rutrum dui nec molestie fringilla.

Nulla eget est dui. Etiam erat est, egestas sodales dapibus ut, porttitor in libero. Aliquam fermentum nibh et dolor viverra aliquam. Curabitur aliquet eu augue non lobortis. Maecenas semper tellus massa, fringilla venenatis leo sodales ut. Mauris suscipit neque justo, in semper urna cursus sit amet. Mauris cursus diam pellentesque interdum ultrices.
Integer eu arcu lectus. Nulla nisi risus, consectetur quis egestas quis, lobortis quis lectus. Phasellus tempor, magna eu ultricies vehicula, ante augue vehicula velit, sed pretium risus arcu a enim. In hac habitasse platea dictumst. Duis feugiat gravida mauris, ut lacinia augue sollicitudin ut. Nulla et cursus odio, iaculis venenatis urna. Phasellus posuere arcu nec sem hendrerit imperdiet. Fusce tincidunt odio non purus lobortis, ac tempus dui dapibus. Integer euismod ultricies pellentesque.


text:
#include "pocl_cl.h"
#include "utlist.h"

CL_API_ENTRY cl_int CL_API_CALL
POname(clFlush)(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_0
{
  /* "clFlush only guarantees that all queued commands to command_queue
     will eventually be submitted to the appropriate device. There is no guarantee
     that they will be complete after clFlush returns." */
  /* This could be implemented as an asyc clFinish(), executing it in another
     thread? */
  return POname(clFinish) (command_queue);
}
POsym(clFlush)


text:
package com.medicapital.client.doctor.visit;

import java.util.Collection;
import com.google.gwt.event.shared.EventBus;
import com.medicapital.client.core.entities.EntitiesPresenter;
import com.medicapital.common.entities.VisitType;

public class VisitTypeListPresenter extends EntitiesPresenter<VisitType> {

	private final VisitTypeListView view;

	public VisitTypeListPresenter(VisitTypeListView view, EventBus eventBus) {
		super(VisitType.class, view, eventBus);
		this.view = view;
	}

	@Override
	protected void displayDataOnView(Collection<VisitType> data) {
		for (VisitType visitType : data) {
			view.display(visitType.getId(), visitType.getName(), visitType.getDuration());
		}
	}

}


text:
{-|
Copyright   : (c) Dave Laing, 2017
License     : BSD3
Maintainer  : dave.laing.80@gmail.com
Stability   : experimental
Portability : non-portable
-}
module Fragment.Pair.Ast (
    module X
  ) where

import Fragment.Pair.Ast.Type as X
import Fragment.Pair.Ast.Error as X
import Fragment.Pair.Ast.Pattern as X
import Fragment.Pair.Ast.Term as X


text:
import os
import sys
import argparse
import parse_weight

""" Log format for signatures
       0: 0x0000000000b4d3fa 0x000000000b839f08
       1: 0x0000000000b4d437 0x000000000b95ddff
       2: 0x0000000000b51f37 0x00000000045f81b7
       3: 0x0000000000b4d437 0x000000000b95ddd7
       4: 0x0000000000b4d437 0x000000000b964ef7
       5: 0x0000000000c91437 0x000000000b8e9d97
       6: 0x0000000000b4d437 0x000000000b95ddd7
       7: 0x0000000000b51c37 0x00000000045f81b7
       8: 0x0000000000b4d437 0x000000000b95ddd7
       9: 0x0000000000b4d437 0x0000000004609af7
      10: 0x0000000000c91737 0x000000000b8e9dbf
                      ...
  131070: 0x0000000000c91437 0x000000000b95ddd7
  131071: 0x0000000000b4d437 0x000000000b964ef7
 0x0000000000b4d3fa 0x000000000b839f08: 1
 0x0000000000b4d437 0x000000000317037f: 1
 0x0000000000b4d437 0x00000000031703f7: 31
                      ...
 0x0000000000ca3437 0x000000000b8e9e0f: 1
 0x0000000000ca3437 0x000000000b8e9e37: 1
 0x0000000000ca3437 0x000000000b948c7f: 1
 0x0000000000ca3437 0x000000000b94c497: 1
 0x0000000000ca3437 0x000000000b953517: 3
 0x0000000000ca3437 0x000000000b95ddd7: 2606
 0x0000000000ca3437 0x000000000b964e57: 81
 0x0000000000ca35b7 0x000000000b8df4d7: 2
Number of unique results 351 out of 131072
"""

""" Weights for parsing signatures (no indentation in real code)
Thread 0 Word 0
    Profile 0
    Profile 1
    ...
Thread 0 Word 1
  ...
Thread 1 Word 0
  ...
Thread 2 Word 0
  ...

For each profile element: "weight stride, # weights" (e.g., 4,5 => weights are 0, 4, 8, 12, 16)
"""

parser = argparse.ArgumentParser(description="Arguments for %s " % __file__)
parser.add_argument("--verbose", "-v", action="count", default=0)
parser.add_argument("--debug", "-d", action="store_true", default=False)
parser.add_argument("--signature-file", default=None)
parser.add_argument("--profile-file", default=None)
args = parser.parse_args()
assert(args.signature_file != None and args.profile_file != None)

verbosity = args.verbose

########################################################################
# Read ordered signature words
########################################################################
signatureFP = open(args.signature_file, "r")
signatureList = []
for line in signatureFP:
    if not line.startswith(" 0x"):
        continue
    tokens = line.split(":")
    signatureStrings = tokens[0].lstrip().split()
    signatures = []
    for string in signatureStrings:
        signatures.append(int(string, 16))
    signatureList.append(signatures)
signatureFP.close()

# Verify if the signatureList is fully ordered in ascending order
fullyOrdered = True
prevSignature = signatureList[0]
signatureLength = len(signatureList[0])
for signatureIdx in range(1,len(signatureList)):
    signature = signatureList[signatureIdx]
    assert(len(signature) == signatureLength)
    for wordIdx in range(signatureLength):
        if signature[wordIdx] > prevSignature[wordIdx]:
            break
        elif signature[wordIdx] < prevSignature[wordIdx]:
            print("Warning: prevSignature %s currSignature %s" % (prevSignature, signature))
            fullyOrdered = False
    prevSignature = signature
if (fullyOrdered):
    print("Info: signatures are fully ordered")
else:
    print("Info: signatrues are NOT ordered fully")

if (verbosity > 0):
    for signature in signatureList:
        for perThreadSignature in signature:
            sys.stdout.write(" 0x%X" % perThreadSignature)
        sys.stdout.write("\n")

########################################################################
# Read signature weights
########################################################################
returnDict = parse_weight.parseWeights(args.profile_file)
weightList = returnDict['weightList']
numThreads = returnDict['numThreads']
numWordsPerThread = returnDict['numWordsPerThread']

if (verbosity > 0):
    for weightWord in weightList:
        print(weightWord)

# Reordering weights
# NOTE: THIS SHOULD BE CAREFULLY UNCOMMENTED IN CONJUNCTION WITH OTHER FILES (codegen_common.py, ANALYSIS TOOLS)
"""
assert(len(weightList) == numThreads * numWordsPerThread)
newWeightList = [[] for i in range(numThreads * numWordsPerThread)]
for t in range(numThreads):
    for w in range(numWordsPerThread):
        idx = numThreads * (numWordsPerThread - 1 - w) + t
        newWeightList[idx] = weightList[t * numWordsPerThread + w]
weightList = newWeightList

if (verbosity > 0):
    for weightWord in weightList:
        print(weightWord)
"""

########################################################################
# Compute differences between two adjacent signatures
########################################################################
differenceList = []
numDiffLoadsList = []
if len(signatureList) > 1:
    signatureLength = len(signatureList[0])
    assert(len(weightList) == signatureLength)
    for signatureIdx in range(1, len(signatureList)):
        difference = []
        for wordIdx in range(signatureLength):
            difference.append(signatureList[signatureIdx][wordIdx] - signatureList[signatureIdx-1][wordIdx])
        differenceList.append(difference)
    for difference in differenceList:
        numDiffLoads = 0
        for wordIdx in range(signatureLength):
            num = 0
            currDiff = abs(difference[wordIdx])
            for weightTuple in reversed(weightList[wordIdx]):
                if (currDiff == 0):
                    break
                weight = weightTuple[0]
                possibilities = weightTuple[1]
                #print("currDiff %d weight %d possibilities %d" % (currDiff, weight, possibilities))
                if currDiff >= weight:
                    pathIdx = currDiff / weight
                    assert(pathIdx < possibilities)
                    currDiff -= pathIdx * weight
                    num += 1
            assert(currDiff == 0)
            numDiffLoads += num
        numDiffLoadsList.append(numDiffLoads)
else:
    print("Info: only 1 signature found")

if (verbosity > 0):
    assert(len(differenceList) == len(numDiffLoadsList))
    for idx in range(len(differenceList)):
        print("%s - %s" % (differenceList[idx], numDiffLoadsList[idx]))

sumDiffLoads = 0
for idx in range(len(numDiffLoadsList)):
    sumDiffLoads += numDiffLoadsList[idx]
print("Info: %d different loads from last graph" % sumDiffLoads)


text:
<?php

namespace SonarSoftware\CustomerPortalFramework\Models;

use InvalidArgumentException;

class BankAccount
{
    private $accountNumber;
    private $routingNumber;
    private $name;
    private $type;

    public function __construct($values)
    {
        $this->validateInput($values);
        $this->storeInput($values);
    }

    public function getAccountNumber()
    {
        return $this->accountNumber;
    }

    public function getRoutingNumber()
    {
        return $this->routingNumber;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getType()
    {
        return $this->type;
    }

    /**
     * @param $input
     */
    private function validateInput($input)
    {
        if (!is_array($input))
        {
            throw new InvalidArgumentException("Input must be an array.");
        }

        if (!isset($input['account_number']))
        {
            throw new InvalidArgumentException("account_number must be set.");
        }

        if (!isset($input['routing_number']))
        {
            throw new InvalidArgumentException("routing_number must be set.");
        }

        if (!isset($input['name']))
        {
            throw new InvalidArgumentException("name must be set.");
        }

        if (!isset($input['type']))
        {
            throw new InvalidArgumentException("type must be set.");
        }

        if (strlen($input['routing_number']) != 9)
        {
            throw new InvalidArgumentException("Routing number must be 9 digits.");
        }

        if (!in_array($input['type'],['checking','savings']))
        {
            throw new InvalidArgumentException("type must be one of 'checking' or 'savings'");
        }

        if (!is_numeric($input['account_number']))
        {
            throw new InvalidArgumentException("account_number must be numeric.");
        }

        if (!is_numeric($input['routing_number']))
        {
            throw new InvalidArgumentException("routing_number must be numeric.");
        }
    }

    /**
     * @param $input
     */
    private function storeInput($input)
    {
        $this->accountNumber = trim($input['account_number']);
        $this->routingNumber = trim($input['routing_number']);
        $this->name = trim($input['name']);
        $this->type = trim($input['type']);
    }
}


text:
package Sisimai::Bite::Email::Bigfoot;
use parent 'Sisimai::Bite::Email';
use feature ':5.10';
use strict;
use warnings;

my $Indicators = __PACKAGE__->INDICATORS;
my $StartingOf = { 'rfc822'  => ['Content-Type: message/partial'] };
my $MarkingsOf = { 'message' => qr/\A[ \t]+[-]+[ \t]*Transcript of session follows/ };

sub description { 'Bigfoot: http://www.bigfoot.com' }
sub scan {
    # Detect an error from Bigfoot
    # @param         [Hash] mhead       Message headers of a bounce email
    # @options mhead [String] from      From header
    # @options mhead [String] date      Date header
    # @options mhead [String] subject   Subject header
    # @options mhead [Array]  received  Received headers
    # @options mhead [String] others    Other required headers
    # @param         [String] mbody     Message body of a bounce email
    # @return        [Hash, Undef]      Bounce data list and message/rfc822 part
    #                                   or Undef if it failed to parse or the
    #                                   arguments are missing
    # @since v4.1.10
    my $class = shift;
    my $mhead = shift // return undef;
    my $mbody = shift // return undef;
    my $match = 0;

    # 'subject'  => qr/\AReturned mail: /,
    $match ||= 1 if rindex($mhead->{'from'}, '@bigfoot.com>') > -1;
    $match ||= 1 if grep { rindex($_, '.bigfoot.com ') > -1 } @{ $mhead->{'received'} };
    return undef unless $match;

    require Sisimai::RFC1894;
    my $fieldtable = Sisimai::RFC1894->FIELDTABLE;
    my $permessage = {};    # (Hash) Store values of each Per-Message field

    my $dscontents = [__PACKAGE__->DELIVERYSTATUS];
    my $rfc822part = '';    # (String) message/rfc822-headers part
    my $rfc822list = [];    # (Array) Each line in message/rfc822 part string
    my $blanklines = 0;     # (Integer) The number of blank lines
    my $readcursor = 0;     # (Integer) Points the current cursor position
    my $recipients = 0;     # (Integer) The number of 'Final-Recipient' header
    my $commandtxt = '';    # (String) SMTP Command name begin with the string '>>>'
    my $esmtpreply = '';    # (String) Reply from remote server on SMTP session
    my $v = undef;
    my $p = '';

    for my $e ( split("\n", $$mbody) ) {
        # Read each line between the start of the message and the start of rfc822 part.
        unless( $readcursor ) {
            # Beginning of the bounce message or message/delivery-status part
            if( $e =~ $MarkingsOf->{'message'} ) {
                $readcursor |= $Indicators->{'deliverystatus'};
                next;
            }
        }

        unless( $readcursor & $Indicators->{'message-rfc822'} ) {
            # Beginning of the original message part(message/rfc822)
            if( index($e, $StartingOf->{'rfc822'}->[0]) == 0 ) {
                $readcursor |= $Indicators->{'message-rfc822'};
                next;
            }
        }

        if( $readcursor & $Indicators->{'message-rfc822'} ) {
            # message/rfc822 or text/rfc822-headers part
            unless( length $e ) {
                last if ++$blanklines > 1;
                next;
            }
            push @$rfc822list, $e;

        } else {
            # message/delivery-status part
            next unless $readcursor & $Indicators->{'deliverystatus'};
            next unless length $e;

            if( my $f = Sisimai::RFC1894->match($e) ) {
                # $e matched with any field defined in RFC3464
                next unless my $o = Sisimai::RFC1894->field($e);
                $v = $dscontents->[-1];

                if( $o->[-1] eq 'addr' ) {
                    # Final-Recipient: rfc822; kijitora@example.jp
                    # X-Actual-Recipient: rfc822; kijitora@example.co.jp
                    if( $o->[0] eq 'final-recipient' ) {
                        # Final-Recipient: rfc822; kijitora@example.jp
                        if( $v->{'recipient'} ) {
                            # There are multiple recipient addresses in the message body.
                            push @$dscontents, __PACKAGE__->DELIVERYSTATUS;
                            $v = $dscontents->[-1];
                        }
                        $v->{'recipient'} = $o->[2];
                        $recipients++;

                    } else {
                        # X-Actual-Recipient: rfc822; kijitora@example.co.jp
                        $v->{'alias'} = $o->[2];
                    }
                } elsif( $o->[-1] eq 'code' ) {
                    # Diagnostic-Code: SMTP; 550 5.1.1 <userunknown@example.jp>... User Unknown
                    $v->{'spec'} = $o->[1];
                    $v->{'diagnosis'} = $o->[2];

                } else {
                    # Other DSN fields defined in RFC3464
                    next unless exists $fieldtable->{ $o->[0] };
                    $v->{ $fieldtable->{ $o->[0] } } = $o->[2];

                    next unless $f == 1;
                    $permessage->{ $fieldtable->{ $o->[0] } } = $o->[2];
                }
            } else {
                # The line does not begin with a DSN field defined in RFC3464
                if( substr($e, 0, 1) ne ' ' ) {
                    #    ----- Transcript of session follows -----
                    # >>> RCPT TO:<destinaion@example.net>
                    # <<< 553 Invalid recipient destinaion@example.net (Mode: normal)
                    if( $e =~ /\A[>]{3}[ ]+([A-Z]{4})[ ]?/ ) {
                        # >>> DATA
                        $commandtxt = $1;

                    } elsif( $e =~ /\A[<]{3}[ ]+(.+)\z/ ) {
                        # <<< Response
                        $esmtpreply = $1;
                    }
                } else {
                    # Continued line of the value of Diagnostic-Code field
                    next unless index($p, 'Diagnostic-Code:') == 0;
                    next unless $e =~ /\A[ \t]+(.+)\z/;
                    $v->{'diagnosis'} .= ' '.$1;
                }
            }
        } # End of message/delivery-status
    } continue {
        # Save the current line for the next loop
        $p = $e;
    }
    return undef unless $recipients;

    for my $e ( @$dscontents ) {
        # Set default values if each value is empty.
        $e->{'lhost'} ||= $permessage->{'rhost'};
        map { $e->{ $_ } ||= $permessage->{ $_ } || '' } keys %$permessage;

        $e->{'diagnosis'} =  Sisimai::String->sweep($e->{'diagnosis'});
        $e->{'command'} ||= $commandtxt || '';
        $e->{'command'} ||= 'EHLO' if $esmtpreply;
        $e->{'agent'}     = __PACKAGE__->smtpagent;
    }
    $rfc822part = Sisimai::RFC5322->weedout($rfc822list);
    return { 'ds' => $dscontents, 'rfc822' => $$rfc822part };
}

1;
__END__

=encoding utf-8

=head1 NAME

Sisimai::Bite::Email::Bigfoot - bounce mail parser class for C<Bigfoot>.

=head1 SYNOPSIS

    use Sisimai::Bite::Email::Bigfoot;

=head1 DESCRIPTION

Sisimai::Bite::Email::Bigfoot parses a bounce email which created by C<Bigfoot>.
Methods in the module are called from only Sisimai::Message.

=head1 CLASS METHODS

=head2 C<B<description()>>

C<description()> returns description string of this module.

    print Sisimai::Bite::Email::Bigfoot->description;

=head2 C<B<smtpagent()>>

C<smtpagent()> returns MTA name.

    print Sisimai::Bite::Email::Bigfoot->smtpagent;

=head2 C<B<scan(I<header data>, I<reference to body string>)>>

C<scan()> method parses a bounced email and return results as a array reference.
See Sisimai::Message for more details.

=head1 AUTHOR

azumakuniyuki

=head1 COPYRIGHT

Copyright (C) 2014-2018 azumakuniyuki, All rights reserved.

=head1 LICENSE

This software is distributed under The BSD 2-Clause License.

=cut


text:
package org.elasticsearch.xpack.analytics.action;

import org.elasticsearch.Version;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.test.AbstractWireSerializingTestCase;
import org.elasticsearch.xpack.core.common.stats.EnumCounters;
import org.elasticsearch.xpack.core.analytics.action.AnalyticsStatsAction;

import static org.hamcrest.Matchers.equalTo;

public class AnalyticsStatsActionNodeResponseTests extends AbstractWireSerializingTestCase<AnalyticsStatsAction.NodeResponse> {

    @Override
    protected Writeable.Reader<AnalyticsStatsAction.NodeResponse> instanceReader() {
        return AnalyticsStatsAction.NodeResponse::new;
    }

    @Override
    protected AnalyticsStatsAction.NodeResponse createTestInstance() {
        String nodeName = randomAlphaOfLength(10);
        DiscoveryNode node = new DiscoveryNode(nodeName, buildNewFakeTransportAddress(), Version.CURRENT);
        EnumCounters<AnalyticsStatsAction.Item> counters = new EnumCounters<>(AnalyticsStatsAction.Item.class);
        for (AnalyticsStatsAction.Item item : AnalyticsStatsAction.Item.values()) {
            if (randomBoolean()) {
                counters.inc(item, randomLongBetween(0, 1000));
            }
        }
        return new AnalyticsStatsAction.NodeResponse(node, counters);
    }

    public void testItemEnum() {
        int i = 0;
        // We rely on the ordinals for serialization, so they shouldn't change between version
        assertThat(AnalyticsStatsAction.Item.BOXPLOT.ordinal(), equalTo(i++));
        assertThat(AnalyticsStatsAction.Item.CUMULATIVE_CARDINALITY.ordinal(), equalTo(i++));
        assertThat(AnalyticsStatsAction.Item.STRING_STATS.ordinal(), equalTo(i++));
        assertThat(AnalyticsStatsAction.Item.TOP_METRICS.ordinal(), equalTo(i++));
        assertThat(AnalyticsStatsAction.Item.T_TEST.ordinal(), equalTo(i++));
        assertThat(AnalyticsStatsAction.Item.MOVING_PERCENTILES.ordinal(), equalTo(i++));
        assertThat(AnalyticsStatsAction.Item.NORMALIZE.ordinal(), equalTo(i++));
        assertThat(AnalyticsStatsAction.Item.RATE.ordinal(), equalTo(i++));
        assertThat(AnalyticsStatsAction.Item.MULTI_TERMS.ordinal(), equalTo(i++));
        // Please add tests for newly added items here
        assertThat(AnalyticsStatsAction.Item.values().length, equalTo(i));
    }
}


text:
@interface JCEventTableViewCell : SWTableViewCell <SWTableViewCellDelegate>

@property (strong, nonatomic) PFObject *currentEvent;
@property (strong, nonatomic) IBOutlet UIImageView *eventImageView;
@property (strong, nonatomic) IBOutlet UILabel *titleLable;
@property (strong, nonatomic) IBOutlet UILabel *dateLabel;

@end


text:
<?php
/*
    Eonza
    (c) 2015 Novostrim, OOO. http://www.eonza.org
    License: MIT
*/

function upd2to3()
{
    $db = DB::getInstance();

    $db->query( "CREATE TABLE IF NOT EXISTS `".ENZ_ONEMANY."` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `idcolumn` smallint(5) unsigned NOT NULL,
  `iditem` int(10) unsigned NOT NULL,
  `idmulti` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `idcolumn` (`idcolumn`,`iditem`),
  KEY `idcolumn_2` (`idcolumn`,`idmulti`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;" );
}


text: There will be more content


text:
KAChartView
===========

Line and Bar chart for iOS 7.0+ and Mac OS X 10.9+

#Features

- Fast.
- Customizable (line color, fill color (line chart), axis color, does show axises, x axis labels and their attributes)
- Uses preferred numbers (r10 series) to calculate and scale the graph automatically.
- Scales to any frame.

#### How To Use
	// Initialize the KAChartView
	KAChartView * first = [[KAChartView alloc] initWithFrame:CGRectMake(0, 0, 320, 200) andType:KAChartViewTypeLine];

	// Create and add the data set
	[first addDataSets:@[[[KADataSet alloc] initWithValues:[self randomizedPoints:[self generateRandomArrayOfLength:7 withNumbersBetween:0 andTop:200]] withColor:[UIColor greenColor] andFillColor:[UIColor colorWithRed:0 green:1.0 blue:0.0 alpha:0.1]]]];

	// Set your axis label attributes
	first.axisLabelAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:10], NSForegroundColorAttributeName: [UIColor lightGrayColor]};

	// Set boolean to allow the axis lines to be drawn
	[first setDoesDrawAxisLines:YES];

![alt tag](https://raw.github.com/Pearapps/KAChartView/master/chart.png)

![alt tag](https://raw.github.com/Pearapps/KAChartView/master/chart1.png)

![alt tag](https://raw.github.com/Pearapps/KAChartView/master/chart2.png)

What's Next:
- The 'buffer' needs to be flexible to accommodate huge y axis values, while retaining right aligned y axis labels.
- API and code cleansing. (Yes it has gotten messy, and I apologize - I think KAChartView is on it's 5th in-place rewrite, and so stuff gets dirty.)


text:
'use strict'

const { prepareAmount } = require('bfx-api-node-util')
const argFromCLI = require('../util/arg_from_cli')
const { RESTv2 } = require('../../index')
const { args: { apiKey, apiSecret }, debug, debugTable } = require('../util/setup')

async function execute () {
  const rest = new RESTv2({
    apiKey,
    apiSecret,
    transform: true
  })
  const symbol = argFromCLI(0, 'fUSD')

  debug('fetching funding credits for %s', symbol)

  const fcs = await rest.fundingCredits(symbol)

  if (fcs.length === 0) {
    debug('none available')
  } else {
    debugTable({
      headers: ['Symbol', 'Amount', 'Status', 'Rate', 'Period', 'Renew'],
      rows: fcs.map(fc => [
        fc.symbol, prepareAmount(fc.amount), fc.status, fc.rate * 100,
        fc.period, fc.renew ? 'Y' : 'N'
      ])
    })
  }
}

execute()


text:
package net.juniorbl.jtoyracing.entity.vehicle;

import net.juniorbl.jtoyracing.enums.ResourcesPath;
import net.juniorbl.jtoyracing.util.ModelUtil;

import com.jme.math.Vector3f;
import com.jme.scene.Node;
import com.jmex.physics.DynamicPhysicsNode;
import com.jmex.physics.Joint;
import com.jmex.physics.PhysicsSpace;
import com.jmex.physics.RotationalJointAxis;
import com.jmex.physics.geometry.PhysicsSphere;
import com.jmex.physics.material.Material;

/**
 * Wheel of a vehicle. It reacts to some speed by calculating the interaction between its own body
 * and the floor (done by JMonkeyEngine).
 *
 * @version 1.0 Aug 23, 2007
 * @author Carlos Luz Junior
 */
public class Wheel extends Node {
	private static final long serialVersionUID = 8702035354026675358L;
	private static final float TIRE_SCALE = 1.5f;
	private static final float WHEEL_SCALE = .4f;
	private static final float MASS = 4;
	private static final float TRACTION_ACCELERATION = 150;
	private static final float TRACTION_BREAK_REVERSE_ACCELERATION = 250;
	private static final float STEER_ACCELERATION = 30;
	private static final float MAX_STEER_ROTATION = 0.3f;
	private DynamicPhysicsNode wheel;
	private RotationalJointAxis tractionAxis;
	private RotationalJointAxis steerAxis;

	public Wheel(DynamicPhysicsNode wheelBase, Vector3f location) {
		createWheel(wheelBase, location);
		Joint tireBaseJoint = createBaseTireJoint(wheelBase.getSpace(), wheelBase);
		createSteerAxis(tireBaseJoint);
		createTractionAxis(tireBaseJoint);
		this.attachChild(wheel);
	}

	private void createWheel(DynamicPhysicsNode wheelBase, Vector3f location) {
		wheel = wheelBase.getSpace().createDynamicNode();
		wheel.setLocalTranslation(wheelBase.getLocalTranslation().add(location));
		PhysicsSphere tire = wheel.createSphere("tire");
		tire.setLocalScale(TIRE_SCALE);
		wheel.generatePhysicsGeometry();
		wheel.attachChild(ModelUtil.convertOBJToStatial(ResourcesPath.MODELS_PATH + "obj/whell.obj"));
		wheel.setMass(MASS);
		wheel.setMaterial(Material.RUBBER);
		wheel.setLocalScale(WHEEL_SCALE);
	}

	/**
	 * Creates a traction axis. It responds the traction action in the wheel.
	 */
	private void createTractionAxis(Joint tireBaseJoint) {
		tractionAxis = tireBaseJoint.createRotationalAxis();
		tractionAxis.setDirection(Vector3f.UNIT_X);
		tractionAxis.setRelativeToSecondObject(true);
		tractionAxis.setAvailableAcceleration(TRACTION_ACCELERATION);
	}

	/**
	 * Creates a steer axis. It responds the steer action in the wheel.
	 */
	private void createSteerAxis(Joint tireBaseJoint) {
		steerAxis = tireBaseJoint.createRotationalAxis();
		steerAxis.setDirection(Vector3f.UNIT_Y);
		steerAxis.setAvailableAcceleration(STEER_ACCELERATION);
		unsteer();
	}

	/**
	 * Creates a joint which connects the base and the tire.
	 */
	private Joint createBaseTireJoint(PhysicsSpace physicsSpace, DynamicPhysicsNode wheelBase) {
		Joint tireBaseJoint = physicsSpace.createJoint();
		tireBaseJoint.attach(wheelBase, wheel);
		tireBaseJoint.setAnchor(wheel.getLocalTranslation().subtract(wheelBase.getLocalTranslation()));
		return tireBaseJoint;
	}

	public final void accelerate(float desiredVelocity) {
		boolean breakOrReverse = desiredVelocity < 0;
		if (breakOrReverse) {
			tractionAxis.setAvailableAcceleration(TRACTION_BREAK_REVERSE_ACCELERATION);
		} else {
			tractionAxis.setAvailableAcceleration(TRACTION_ACCELERATION);
		}
		tractionAxis.setDesiredVelocity(desiredVelocity);
	}

	public final void stop() {
		tractionAxis.setDesiredVelocity(0);
	}

	public final void steer(float desiredDirection) {
		steerAxis.setDesiredVelocity(desiredDirection);
		steerAxis.setPositionMaximum(MAX_STEER_ROTATION);
		steerAxis.setPositionMinimum(-MAX_STEER_ROTATION);
	}

	public final void unsteer() {
		steerAxis.setDesiredVelocity(0);
		steerAxis.setPositionMaximum(0);
		steerAxis.setPositionMinimum(0);
	}
}


text:
package com.alibaba.excel.metadata.data;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.poi.ss.usermodel.CellStyle;

/**
 * wirte cell data
 *
 * @author Jiaju Zhuang
 */
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
public class WriteCellData<T> extends CellData<T> {
    /**
     * Support only when writing.{@link CellDataTypeEnum#DATE}
     */
    private LocalDateTime dateValue;

    /**
     * rich text.{@link CellDataTypeEnum#RICH_TEXT_STRING}
     */
    private RichTextStringData richTextStringDataValue;
    /**
     * image
     */
    private List<ImageData> imageDataList;
    /**
     * comment
     */
    private CommentData commentData;
    /**
     * hyper link
     */
    private HyperlinkData hyperlinkData;

    /**
     * style
     */
    private WriteCellStyle writeCellStyle;

    /**
     * If originCellStyle is empty, one will be created.
     * If both writeCellStyle and originCellStyle exist, copy from writeCellStyle to originCellStyle.
     */
    private CellStyle originCellStyle;

    public WriteCellData(String stringValue) {
        this(CellDataTypeEnum.STRING, stringValue);
    }

    public WriteCellData(CellDataTypeEnum type) {
        super();
        setType(type);
    }

    public WriteCellData(CellDataTypeEnum type, String stringValue) {
        super();
        if (type != CellDataTypeEnum.STRING && type != CellDataTypeEnum.ERROR) {
            throw new IllegalArgumentException("Only support CellDataTypeEnum.STRING and  CellDataTypeEnum.ERROR");
        }
        if (stringValue == null) {
            throw new IllegalArgumentException("StringValue can not be null");
        }
        setType(type);
        setStringValue(stringValue);
    }

    public WriteCellData(BigDecimal numberValue) {
        super();
        if (numberValue == null) {
            throw new IllegalArgumentException("DoubleValue can not be null");
        }
        setType(CellDataTypeEnum.NUMBER);
        setNumberValue(numberValue);
    }

    public WriteCellData(Boolean booleanValue) {
        super();
        if (booleanValue == null) {
            throw new IllegalArgumentException("BooleanValue can not be null");
        }
        setType(CellDataTypeEnum.BOOLEAN);
        setBooleanValue(booleanValue);
    }

    public WriteCellData(Date dateValue) {
        super();
        if (dateValue == null) {
            throw new IllegalArgumentException("DateValue can not be null");
        }
        setType(CellDataTypeEnum.DATE);
        this.dateValue = LocalDateTime.ofInstant(dateValue.toInstant(), ZoneId.systemDefault());
    }

    public WriteCellData(LocalDateTime dateValue) {
        super();
        if (dateValue == null) {
            throw new IllegalArgumentException("DateValue can not be null");
        }
        setType(CellDataTypeEnum.DATE);
        this.dateValue = dateValue;
    }

    public WriteCellData(byte[] image) {
        super();
        if (image == null) {
            throw new IllegalArgumentException("Image can not be null");
        }
        setType(CellDataTypeEnum.EMPTY);
        this.imageDataList = ListUtils.newArrayList();
        ImageData imageData = new ImageData();
        imageData.setImage(image);
        imageDataList.add(imageData);
    }

    /**
     * Return a style, if is empty, create a new
     *
     * @return not null.
     */
    public WriteCellStyle getOrCreateStyle() {
        if (this.writeCellStyle == null) {
            this.writeCellStyle = new WriteCellStyle();
        }
        return this.writeCellStyle;
    }
}


text:
%% Multiple Workstations In Series
% The contents of the *MultipleWorkstationsInSeries* folder within the *ProductionLineModels* folder concern certain
% results from queueing theory applied to the analysis of a production line.  Of interest here is a "linking equation"
% (equations 8.10-8.11 in Hopp & Spearman, ed. 2) to characterize the departure process of one workstation, which may be
% the arrival process to the next.  This approximation enables extending single-workstation analytical approximations
% for _Work-In-Process_, _Cycle Time_, and _Throughput_ to production lines built of multiple workstations in series.
%
% A natural extension, not implemented at the time of writing, is to implement analytical results for the thinning of a
% Poisson process.  Should the departure process from a single workstation be approximately a Poisson process, then
% single-workstation analytical approximations for Work-In-Process, Cycle Time, and Throughput could also be extended to
% production lines built of multiple workstations _with parallel branches_.
%
% One contribution in this section is an implementation of these analytical formulas, and an additional contribution
% concerns simulation, specifically a simulation generator to assemble production lines of single workstation library
% blocks in series.
%
% Most importantly, a small number of DEMO scripts is included showing how to use the analytical formulas, the
% simulation model generator, and both to compare their results.  Each DEMO script is a usage example, an illustration
% of what is possible, an idea for a lab experiment.  The collection is certainly not exhaustive, and it is hoped that
% they will inspire users to create more, plus transcribe the good ones into carefully-defined lab experiments for
% education.  The remainder of this overview summarizes what the included DEMO scripts do.

%% Analytical Approximation:  Multiple Workstations in Series
% The following demo uses the closed-form queueing theory approximations from Hopp & Spearman,
% chapter 8, plus the linking equation to characterize a single workstation's departure process.
% Multiple workstations are arranged in series, all with a low processing time variability,
% _except one with very high variability_.  Of interest is how the relative position of the high-
% variability workstation (e.g. first, middle, last) affects the overall system performance measures
% of work-in-process, cycle time, and throughput.  The expected result is the farther upstream the
% high-variability workstation resides, the more damaging it is on overall system performance
% measures.
%
% Parameters which can be changed by a user include interarrival time mean & variability, processing
% time means (one subplot for each) and variability (both the small SCV value for all workstations
% except one, and the large SCV value for the one aberrant workstation), the number of workstations
% in series, and the number of servers at each workstation.
DEMO_QTheory_SweepLargeSCV_MultipleSerialWorkstationsThCtWip

%% Analytical Approximation vs Simulation:  Multiple Workstations in Series
% The following demo compares queueing theory approximations and discrete-event simulation.  It
% evaluates the performance measures work-in-process, cycle time, and throughput for multiple
% workstations in series in two different ways: (1) Using closed-form queueing theory approximations
% from Hopp & Spearman, including the linking equation to characterize each workstation's departure
% process, and (2) Using discrete-event simulation.
%
% Analytical approximations and simulation are compared for an increasing number of workstations in
% series (two, then three, then four, ...).  Evaluation is also over a range of utilizations (with
% each workstation having the same value), because the linking equation is a function of utilization
% and the goal is to evaluate the linking equation's fidelity.
%
% Parameters which can be changed by a user include interarrival time distribution, mean, and
% variability, processing time distribution, means (one subplot for each), and variability, the type
% of single workstations assembled in series (plain vanilla, with preemptive failures, with non-
% preemptive setups, with batching), and each workstation's queue capacity and number of servers.
%
% UPDATE:  The _PARALLEL_ version of this demo supercedes the _SERIAL_ version.  It should produce
% exactly the same results, just much faster.  It introduces parallelization by replacing several
% nested FOR loops with a single PARFOR loop, which by default will start and use as many background
% MATLAB sessions as your processor has cores.

%DEMO_QTvsSim_SweepNWks_MultipleInSeriesThCtWipU_SERIAL
DEMO_QTvsSim_SweepNWks_MultipleInSeriesThCtWipU_PARALLEL


text:
<?php
if(!isset($_SESSION['accountType']))
{
    echo 'You are not logged in';
    header( "refresh:3;url=../index" );
    exit();
}
$accountType=$_SESSION['accountType'];
if($accountType=="Faculty1"||$accountType=="Faculty2"||$accountType=="Staff")
{}
else
{echo 'You are not a Regular Employee';
header( "refresh:3;url=../index" );  }
?>


text:
cask 'mysql-utilities' do
  version '1.5.6'
  sha256 '2553ae12323abe28ab3161ebdb6aff991fbb738dc6ef03946c0fae86aadac230'

  url "http://dev.mysql.com/get/Downloads/MySQLGUITools/mysql-utilities-#{version}-osx10.9.dmg"
  name 'MySQL Utilities'
  homepage 'https://dev.mysql.com/downloads/utilities/'
  license :gpl

  depends_on :macos => '<= :yosemite'

  pkg "mysql-utilities-#{version}.pkg"

  uninstall :pkgutil => 'com.oracle.mysql.utilities'
end


text:
package org.wso2.siddhi.core.query.input.stream.state;

import org.wso2.siddhi.core.query.processor.Processor;

/**
 * Created on 12/17/14.
 */
public interface PostStateProcessor extends Processor {

    public int getStateId();

    public void setNextStatePreProcessor(PreStateProcessor nextStatePerProcessor);

    public void setNextEveryStatePerProcessor(PreStateProcessor nextEveryStatePerProcessor);

    public void setCallbackPreStateProcessor(CountPreStateProcessor callbackPreStateProcessor);

    public PostStateProcessor cloneProcessor(String key);

}


text:
using System;
using System.Linq.Expressions;
using System.Reflection;

namespace GraphClimber
{
    internal class MethodCallMutator : IMethodMutator
    {
        private readonly IMethodMapper _methodMapper;
        private readonly bool _routed;
        private readonly Type _processorType;

        public MethodCallMutator(Type processorType, IMethodMapper methodMapper, bool routed)
        {
            _methodMapper = methodMapper;
            _routed = routed;
            _processorType = processorType;
        }

        public Expression Mutate(Expression oldExpression, Expression processor, Expression owner, IStateMember member, Expression descriptor)
        {
            MethodInfo methodToCall =
                _methodMapper.GetMethod(_processorType, member, member.MemberType, _routed);

            MethodCallExpression callProcessor =
                Expression.Call(processor, methodToCall, descriptor);

            Expression result = callProcessor;

            return result;
        }
    }
}


text:
/**
 * Bootstraps the application and makes the ROUTER_PROVIDERS and the APP_BASE_HREF available to it.
 * @see https://angular.io/docs/ts/latest/api/platform-browser-dynamic/index/bootstrap-function.html
 */
import { enableProdMode } from '@angular/core';
// The browser platform with a compiler
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

// The app module
import { AppModule } from './app.module';

if (String('<%= BUILD_TYPE %>') === 'prod') { enableProdMode(); }

platformBrowserDynamic().bootstrapModule(AppModule/*, options*/);


text:
package com.simplaapliko.shym.auth.rx.googleauth;

public class GoogleApiServiceDisconnectedException extends GoogleApiConnectionSuspendedException {}


text:
'use strict';

import PreFilteredSearchBuilder from './PreFilteredSearchBuilder'
import FieldFinder from '../../util/searchingFields/FieldFinder'

const BASE_URL = '/entities';
/**
 * Defined a search over Devices
 * @example ogapi.devicesSearchBuilder()
 */
export default class DevicesSearchBuilder extends PreFilteredSearchBuilder {
    /**
     *	@param {!InternalOpenGateAPI} parent - Instance of our InternalOpenGateAPI
     */
    constructor(parent) {
        super(parent, {}, new FieldFinder(parent, BASE_URL));
        this._url = BASE_URL;
    }

    /**
     * The response will only have a summary information
     * @example
     *	ogapi.devicesSearchBuilder().summary()
     * @return {DevicesSearchBuilder}
     */
    summary() {
        this._url = this._url + '/summary';

        return this;
    }

    _buildFilter() {
        let finalFilter = {
            "and": [{
                "exists": {
                    "provision.device.identifier": true
                }
            }]
        };

        if (this._builderParams.filter && Object.keys(this._builderParams.filter).length > 0) {
            let filter = this._builderParams.filter;
            if (typeof filter._filterTemplate !== "undefined") {
                //return filter._filterTemplate;
                finalFilter.and.push(filter._filterTemplate.filter);
            } else {
                finalFilter.and.push(filter);
            }
        }

        return {
            filter: finalFilter
        };
    }

    /**
     * The search request will have this group by
     * @example
     * @param {!(object)} group
     * @return {DevicesSearchBuilder}
     */
    group(group) {
        this._builderParams.group = (group || {});
        return this;
    }
}


text:
<?= t('Actions') ?>

    <?= $this->form->select(
            'user_id',
            $users,
            $filter,
            array(),
            array('data-redirect-url="'.$this->url->href('projectuser', $this->app->getRouterAction(), array('user_id' => 'USER_ID')).'"', 'data-redirect-regex="USER_ID"'),
            'chosen-select select-auto-redirect'
        ) ?>

        <li <?= $this->app->checkMenuSelection('projectuser', 'managers') ?>>
            <?= $this->url->link(t('Project managers'), 'projectuser', 'managers', $filter) ?>

        <li <?= $this->app->checkMenuSelection('projectuser', 'members') ?>>
            <?= $this->url->link(t('Project members'), 'projectuser', 'members', $filter) ?>

        <li <?= $this->app->checkMenuSelection('projectuser', 'opens') ?>>
            <?= $this->url->link(t('Open tasks'), 'projectuser', 'opens', $filter) ?>

        <li <?= $this->app->checkMenuSelection('projectuser', 'closed') ?>>
            <?= $this->url->link(t('Closed tasks'), 'projectuser', 'closed', $filter) ?>

        <?= $this->hook->render('template:project-user:sidebar') ?>


text:
package org.kie.server.testing;

import java.io.Serializable;

import org.apache.commons.lang3.builder.CompareToBuilder;
import org.optaplanner.core.api.score.constraint.ConstraintMatch;

public abstract class AbstractPersistable implements Serializable, Comparable<AbstractPersistable> {

    protected Long id;

    protected AbstractPersistable() {
    }

    protected AbstractPersistable(long id) {
        this.id = id;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    /**
     * Used by the GUI to sort the {@link ConstraintMatch} list
     * by {@link ConstraintMatch#getJustificationList()}.
     * @param other never null
     * @return comparison
     */
    public int compareTo(AbstractPersistable other) {
        return new CompareToBuilder()
                .append(getClass().getName(), other.getClass().getName())
                .append(id, other.id)
                .toComparison();
    }

    public String toString() {
        return getClass().getName().replaceAll(".*\\.", "") + "-" + id;
    }

}


text:
class HomeController < ApplicationController
  def index
    if signed_in?
      redirect_to current_user
    else
      @likes = Like.order(:created_at).includes(:user).page(params[:page] ||= 1)
      render :index
    end
  end
end


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>translate.filters.checks.StandardUnitChecker</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

Translate Toolkit

        Package translate ::
        Package filters ::
        Module checks ::
        Class StandardUnitChecker

[hide private]

[frames] | no frames]

Class StandardUnitChecker

source code

  <map id="uml_class_diagram_for_translat_18" name="uml_class_diagram_for_translat_18">
<area shape="rect" href="translate.filters.checks.UnitChecker-class.html#preconditions" title="translate.filters.checks.UnitChecker.preconditions" alt="" coords="17,28,567,47"/>
<area shape="rect" href="translate.filters.checks.UnitChecker-class.html#__init__" title="x.__init__(...) initializes x; see x.__class__.__doc__ for signature" alt="" coords="17,49,567,68"/>
<area shape="rect" href="translate.filters.checks.UnitChecker-class.html#getfilters" title="returns dictionary of available filters, including/excluding those in the  given lists" alt="" coords="17,68,567,87"/>
<area shape="rect" href="translate.filters.checks.UnitChecker-class.html#setconfig" title="sets the accelerator list" alt="" coords="17,87,567,105"/>
<area shape="rect" href="translate.filters.checks.UnitChecker-class.html#setsuggestionstore" title="Sets the filename that a checker should use for evaluating suggestions." alt="" coords="17,105,567,124"/>
<area shape="rect" href="translate.filters.checks.UnitChecker-class.html#filtervariables" title="filter out variables from str1" alt="" coords="17,124,567,143"/>
<area shape="rect" href="translate.filters.checks.UnitChecker-class.html#removevariables" title="remove variables from str1" alt="" coords="17,143,567,161"/>
<area shape="rect" href="translate.filters.checks.UnitChecker-class.html#filteraccelerators" title="filter out accelerators from str1" alt="" coords="17,161,567,180"/>
<area shape="rect" href="translate.filters.checks.UnitChecker-class.html#filteraccelerators_by_list" title="filter out accelerators from str1" alt="" coords="17,180,567,199"/>
<area shape="rect" href="translate.filters.checks.UnitChecker-class.html#filterwordswithpunctuation" title="replaces words with punctuation with their unpunctuated equivalents" alt="" coords="17,199,567,217"/>
<area shape="rect" href="translate.filters.checks.UnitChecker-class.html#filterxml" title="filter out XML from the string so only text remains" alt="" coords="17,217,567,236"/>
<area shape="rect" href="translate.filters.checks.UnitChecker-class.html#run_test" title="Runs the given test on the given unit." alt="" coords="17,236,567,255"/>
<area shape="rect" href="translate.filters.checks.UnitChecker-class.html#run_filters" title="run all the tests in this suite, return failures as testname,  message_or_exception" alt="" coords="17,255,567,273"/>
<area shape="rect" href="translate.filters.checks.UnitChecker-class.html" title="Parent Checker class which does the checking based on functions available in derived classes." alt="" coords="16,11,568,275"/>
<area shape="rect" href="translate.filters.checks.StandardUnitChecker-class.html#isfuzzy" title="Check if the unit has been marked fuzzy." alt="" coords="219,329,365,348"/>
<area shape="rect" href="translate.filters.checks.StandardUnitChecker-class.html#isreview" title="Check if the unit has been marked review." alt="" coords="219,348,365,367"/>
<area shape="rect" href="translate.filters.checks.StandardUnitChecker-class.html#nplurals" title="Checks for the correct number of noun forms for plural translations." alt="" coords="219,367,365,385"/>
<area shape="rect" href="translate.filters.checks.StandardUnitChecker-class.html#hassuggestion" title="Checks if there is at least one suggested translation for this unit." alt="" coords="219,385,365,404"/>
<area shape="rect" href="translate.filters.checks.StandardUnitChecker-class.html" title="The standard checks for common checks on translation units." alt="" coords="217,304,367,405"/>
</map>

The standard checks for common checks on translation units.

        Instance Methods
        [hide private]

          isfuzzy(self,
        unit)

      Check if the unit has been marked fuzzy.

            source code

          isreview(self,
        unit)

      Check if the unit has been marked review.

            source code

          nplurals(self,
        unit)

      Checks for the correct number of noun forms for plural translations.

            source code

          hassuggestion(self,
        unit)

      Checks if there is at least one suggested translation for this unit.

            source code

Inherited from UnitChecker:
      __init__,
      filteraccelerators,
      filteraccelerators_by_list,
      filtervariables,
      filterwordswithpunctuation,
      filterxml,
      getfilters,
      removevariables,
      run_filters,
      run_test,
      setconfig,
      setsuggestionstore

Inherited from object:
      __delattr__,
      __getattribute__,
      __hash__,
      __new__,
      __reduce__,
      __reduce_ex__,
      __repr__,
      __setattr__,
      __str__

        Class Variables
        [hide private]

Inherited from UnitChecker:
      preconditions

        Properties
        [hide private]

Inherited from object:
      __class__

         Home

         Trees

         Indices

         Help

Translate Toolkit

    Generated by Epydoc 3.0.1 on Wed Mar  3 16:36:08 2010

      http://epydoc.sourceforge.net


text:
Implementation for Convolutional Neural Networks for Sentence Classification of [Kim (2014)](https://arxiv.org/abs/1408.5882) with PyTorch and Torchtext.

## Model Type

- rand: All words are randomly initialized and then modified during training.
- static: A model with pre-trained vectors from [word2vec](https://code.google.com/archive/p/word2vec/). All words -- including the unknown ones that are initialized with zero -- are kept static and only the other parameters of the model are learned.
- non-static: Same as above but the pretrained vectors are fine-tuned for each task.
- multichannel: A model with two sets of word vectors. Each set of vectors is treated as a 'channel' and each filter is applied to both channels, but gradients are back-propagated only through one of the channels. Hence the model is able to fine-tune one set of vectors while keeping the other static. Both channels are initialized with word2vec.# text-classification-cnn
Implementation for Convolutional Neural Networks for Sentence Classification of [Kim (2014)](https://arxiv.org/abs/1408.5882) with PyTorch.

## Quick Start

To run the model on [SST-1] dataset on [multichannel](Model Type), just run the following code.

```
python train.py --mode multichannel
```

The file will be saved in

```
saves/best_model.pt
```

To test the model, you can use the following command.

```
python main.py --trained_model saves/best_model.pt --mode multichannel
```

## Dataset and Embeddings

Dataset is in data dir. You can set your own path in *SST1.py* and *args.py* for data and embeddings.
We experiment the model on the following three datasets.

- SST-1: Keep the original splits and train with phrase level dataset and test on sentence level dataset.

For **word2vec.sst-1.pt** is a subset of word2vector. We just select the word appearing in the SST-1 dataset and generate this file with the **vector_preprocess.py**. You can select these from any kind of word embedding text file and generate in following format.

```
word vector_in_one_line
```

and then run
```
python vector_preprocess.py file_in embed.pt
```
Here you can get *embed.pt* for the embedding file. Remember change the argument in *args.py* file with your own embedding.

## Setting

Adadelta is used for training.

## Training Time

For training time, when

```
torch.backends.cudnn.deterministic = True
```

is specified, the training will be ~3h because deterministic cnn algorithm is used (accuracy v.s. speed).

Other option is that

```
torch.backends.cudnn.enabled = False
```
but this will take ~6-7x training time.

## Results

Deterministic Algorithm for CNN.

| Dev Accuracy on SST-1 |     rand      |    static    |   non-static  |  multichannel |
|:--------------------------:|:-----------:|:-----------:|:-------------:|:---------------:|
| My-Implementation      | 42.597639| 48.773842| 48.864668   | 49.046322  |

| Test Accuracy on SST-1|      rand      |    static    |    non-static |  multichannel |
|:--------------------------:|:-----------:|:-----------:|:-------------:|:---------------:|
| Kim-Implementation    | 45.0            | 45.5        | 48.0             | 47.4                 |
| My- Implementation    | 39.683258  | 45.972851| 48.914027|  47.330317       |

## TODO

- More experiments on SST-2 and subjectivity
- Parameters tuning


text:
package com.google.gerrit.server.account;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.common.collect.Iterables;
import com.google.common.io.ByteSource;
import com.google.gerrit.common.errors.InvalidSshKeyException;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.extensions.restapi.RawInput;
import com.google.gerrit.extensions.restapi.Response;
import com.google.gerrit.extensions.restapi.RestModifyView;
import com.google.gerrit.reviewdb.client.AccountSshKey;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.account.AddSshKey.Input;
import com.google.gerrit.server.account.GetSshKeys.SshKeyInfo;
import com.google.gerrit.server.ssh.SshKeyCache;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.ResultSet;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;

@Singleton
public class AddSshKey implements RestModifyView<AccountResource, Input> {
  public static class Input {
    public RawInput raw;
  }

  private final Provider<CurrentUser> self;
  private final Provider<ReviewDb> dbProvider;
  private final SshKeyCache sshKeyCache;

  @Inject
  AddSshKey(Provider<CurrentUser> self, Provider<ReviewDb> dbProvider,
      SshKeyCache sshKeyCache) {
    this.self = self;
    this.dbProvider = dbProvider;
    this.sshKeyCache = sshKeyCache;
  }

  @Override
  public Response<SshKeyInfo> apply(AccountResource rsrc, Input input)
      throws AuthException, BadRequestException, OrmException, IOException {
    if (self.get() != rsrc.getUser()
        && !self.get().getCapabilities().canAdministrateServer()) {
      throw new AuthException("not allowed to add SSH keys");
    }
    return apply(rsrc.getUser(), input);
  }

  public Response<SshKeyInfo> apply(IdentifiedUser user, Input input)
      throws BadRequestException, OrmException, IOException {
    if (input == null) {
      input = new Input();
    }
    if (input.raw == null) {
      throw new BadRequestException("SSH public key missing");
    }

    ResultSet<AccountSshKey> byAccountLast =
        dbProvider.get().accountSshKeys().byAccountLast(user.getAccountId());
    AccountSshKey last = Iterables.getOnlyElement(byAccountLast, null);
    int max = last == null ? 0 : last.getKey().get();

    final RawInput rawKey = input.raw;
    String sshPublicKey = new ByteSource() {
      @Override
      public InputStream openStream() throws IOException {
        return rawKey.getInputStream();
      }
    }.asCharSource(UTF_8).read();

    try {
      AccountSshKey sshKey =
          sshKeyCache.create(new AccountSshKey.Id(
              user.getAccountId(), max + 1), sshPublicKey);
      dbProvider.get().accountSshKeys().insert(Collections.singleton(sshKey));
      sshKeyCache.evict(user.getUserName());
      return Response.<SshKeyInfo>created(new SshKeyInfo(sshKey));
    } catch (InvalidSshKeyException e) {
      throw new BadRequestException(e.getMessage());
    }
  }
}


text:
"""
Created on Thu Aug 24 15:31:03 2017

@author: clancien
"""

try:
	import ConfigParser

except ImportError:

	import configparser as ConfigParser

import os
import pandas
import re

import logging
from logging.handlers import RotatingFileHandler
import sys

class Vega():

    def __init__(self):

        config = ConfigParser.ConfigParser()
        config.readfp(open('../../configuration.ini','r'))

        self.logFile = config.get('Error', 'logFile')
        self.vega = config.get('Download', 'gene2vega')
        self.gene = config.get('Convert', 'Vega_gene')
        self.transcript = config.get('Convert', 'Vega_transcript')
        self.protein = config.get('Convert', 'Vega_protein')

        ##Panda read _protein(same for all) as function and not as string so raise error
        ##To bypass this error we create for each file a new variable to store the path as string

        self.filename_vega = str(self.vega)
        self.filename_gene = str(self.gene)
        self.filename_transcript = str(self.transcript)
        self.filename_protein = str(self.protein)

        self.size=1000000 #panda will read by chunksize here 1 million line by 1 million line

        # Store column index we need
        self.index_entrez = None
        self.index_gene = None
        self.index_transcript = None
        self.index_protein = None

        self.dataframe = list
        self.finalDataFrame=None

        self.logger=None
        self.formatter=None
        self.file_handler=None

        self.path_exist()
        self.init_log()
        self.create_index()

    def path_exist(self):
        """ Check if dir exist if not we create the path

        string = dir/subdir/subsubdir
        string.rsplit('/',1)[0]
        ==> return dir/subdir/ """

        if not os.path.isdir(self.gene.rsplit('/',1)[0]):
            os.makedirs(self.gene.rsplit('/', 1)[0])

    def init_log(self):

         # création de l'objet logger qui va nous servir à écrire dans les logs
        self.logger = logging.getLogger()
        # on met le niveau du logger à DEBUG, comme ça il écrit tout
        self.logger.setLevel(logging.DEBUG)

        # création d'un formateur qui va ajouter le temps, le niveau
        # de chaque message quand on écrira un message dans le log
        self.formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')
        # création d'un handler qui va rediriger une écriture du log vers
        # un fichier en mode 'append', avec 1 backup et une taille max de 1Mo

        self.file_handler = RotatingFileHandler(self.logFile, 'a', 1000000, 1)
        # on lui met le niveau sur DEBUG, on lui dit qu'il doit utiliser le formateur
        # créé précédement et on ajoute ce handler au logger
        self.file_handler.setLevel(logging.DEBUG)
        self.file_handler.setFormatter(self.formatter)
        self.logger.addHandler(self.file_handler)

    def create_index(self):

        with open(self.filename_vega , 'r') as infile:

            header_line = next(infile)
            header_line = header_line.split('\t')

            self.index_entrez = header_line.index('GeneID')
            self.index_gene = header_line.index('Vega_gene_identifier')
            self.index_transcript = header_line.index('Vega_rna_identifier')
            self.index_protein = header_line.index('Vega_protein_identifier\n')

    def get_Gene(self):

        try:

            self.dataframe=[]

            for df in pandas.read_csv(self.filename_vega, header=0, sep="\t", usecols=[self.index_entrez, self.index_gene], dtype='str', chunksize=self.size):

                df.columns = ['EGID','BDID']

                self.dataframe.append(df[
                                            (df['EGID'].str.match('^[0-9]+$', flags=re.IGNORECASE))  &
                                            (df['BDID'].str.match('^[O][T][T][D][A][R][G]([0-9]+)$', flags=re.IGNORECASE))

                                        ])
        except:

            self.logger.warning("Error - vega.py - getVega_gene - loop over file")
            self.logger.warning("Exception at the line : {}".format(sys.exc_info()[-1].tb_lineno))
            self.logger.warning(sys.exc_info())

        else:

            try:

                pandas.concat(self.dataframe).drop_duplicates(['EGID', 'BDID'], keep='first').to_csv(self.filename_gene, header=None, index=None, sep='\t', mode='w')

            except:

                self.logger.warning("Error - vega.py - getVega_gene - write File")
                self.logger.warning("Exception at the line : {}".format(sys.exc_info()[-1].tb_lineno))

    def get_Transcript(self):

        try:

            self.dataframe=[]

            for df in pandas.read_csv(self.filename_vega, header=0, sep="\t", usecols=[self.index_entrez, self.index_transcript], dtype='str', chunksize=self.size):

                df.columns = ['EGID','BDID']

                self.dataframe.append(df[
                                            (df['EGID'].str.match('^[0-9]+$', flags=re.IGNORECASE))  &
                                            (df['BDID'].str.match('^[O][T][T][D][A][R][T]([0-9]+)$', flags=re.IGNORECASE))

                                        ])

        except:

            self.logger.warning("Error - vega.py - getVega_transcript - loop over file")
            self.logger.warning("Exception at the line : {}".format(sys.exc_info()[-1].tb_lineno))
            self.logger.warning(sys.exc_info())

        else:

            try:

                pandas.concat(self.dataframe).drop_duplicates(['EGID', 'BDID'], keep='first').to_csv(self.filename_transcript, header=None, index=None, sep='\t', mode='w')

            except:

                self.logger.warning("Error - vega.py - getVega_transcript - write File")
                self.logger.warning("Exception at the line : {}".format(sys.exc_info()[-1].tb_lineno))

    def get_Protein(self):

        try:

            self.dataframe=[]

            for df in pandas.read_csv(self.filename_vega, header=0, sep="\t", usecols=[self.index_entrez, self.index_protein], dtype='str', chunksize=self.size):

                df.columns = ['EGID','BDID']

                self.dataframe.append(df[
                                            (df['EGID'].str.match('^[0-9]+$', flags=re.IGNORECASE))  &
                                            (df['BDID'].str.match('^[O][T][T][D][A][R][P]([0-9]+)$', flags=re.IGNORECASE))

                                        ])
        except:

            self.logger.warning("Error - vega.py - getVega_protein - loop over file")
            self.logger.warning("Exception at the line : {}".format(sys.exc_info()[-1].tb_lineno))
            self.logger.warning(sys.exc_info())

        else:

            try:

                pandas.concat(self.dataframe).drop_duplicates(['EGID', 'BDID'], keep='first').to_csv(self.filename_protein, header=None, index=None, sep='\t', mode='w')

            except:

                self.logger.warning("Error - vega.py - getVega_protein - write File")
                self.logger.warning("Exception at the line : {}".format(sys.exc_info()[-1].tb_lineno))

if __name__ == '__main__':

    Vega().get_Gene()
    Vega().get_Transcript()
    Vega().get_Protein


text:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title>Teruskan Tagihan-SubBag</title>
    </head>
    <body>
        <?php include 'headloader.php'; ?>
        <?php include 'scriptloader.php'; ?>
    </body>
</html>


text:
using Newtonsoft.Json;
using System.Collections.Generic;

namespace BorderlessAlphaWin
{
    internal class TagList
    {
        public TagList()
        {
            Tags = new List<Tag>();
        }

        [JsonProperty("Tags")]
        public List<Tag> Tags
        {
            get; set;
        }
    }
}


text:
<title/>
Message classes


text:
#import <UIKit/UIKit.h>

@class IoTTimingSelection;

@protocol IoTTimingSelectionDelegate <NSObject>
@optional

/**
 * @brief 选中后的事件
 * @param value 0-34 分别对应 1-24,25 关闭
 */
- (void)IoTTimingSelectionDidConfirm:(IoTTimingSelection *)selection withValue:(NSInteger)value;

@end

@interface IoTTimingSelection : UIViewController

- (id)initWithTitle:(NSString *)title delegate:(id <IoTTimingSelectionDelegate>)delegate currentValue:(NSInteger)value;
- (void)show:(BOOL)animated;
- (void)hide:(BOOL)animated;

@end


text:
layout: page
permalink: /faqs/
title: "Frequently asked questions"
date: 2016-08-26
last_modified_at: 2018-02-19T09:56:45-05:00
excerpt: "Because no one likes to repeat things here's a compilation of answers to questions I'm often asked."
---

Did I leave something out that you were looking for an answer to? Feel free to reach out and [ask me](/contact/).

{% assign other_faqs = site.faqs | where: "type", "other" | sort: "order" %}
{% assign paper_faqs = site.faqs | where: "type", "paper" | sort: "order" %}

{% for faq in other_faqs %}

{{ faq.title }}

{% endfor %}

## iPad Art

{% for faq in paper_faqs %}

{{ faq.title }}

{% endfor %}


text:
opal_filter "Kernel" do
  fails "Kernel.Array does not call #to_a on an Array" #something funky with the spec itself
  fails "Kernel#Array does not call #to_a on an Array" #something funky with the spec itself

  fails "Kernel.String raises a TypeError if #to_s does not exist"
  fails "Kernel.String raises a TypeError if respond_to? returns false for #to_s"
  fails "Kernel.String raises a TypeError if #to_s is not defined, even though #respond_to?(:to_s) returns true"
  fails "Kernel.String calls #to_s if #respond_to?(:to_s) returns true"
  fails "Kernel#String raises a TypeError if #to_s does not exist"
  fails "Kernel#String raises a TypeError if respond_to? returns false for #to_s"
  fails "Kernel#String raises a TypeError if #to_s is not defined, even though #respond_to?(:to_s) returns true"
  fails "Kernel#String calls #to_s if #respond_to?(:to_s) returns true"

  fails "Kernel.Float returns a Float for Complex with only a real part"
  fails "Kernel.Float raises a RangeError when passed a Complex argument"
  fails "Kernel#Float returns a Float for Complex with only a real part"
  fails "Kernel#Float raises a RangeError when passed a Complex argument"
end


text:
{% extends "layout.html" %}
{% block body %}
<title>Where would you… a urban activity survey</title>

Where would you…

In my master thesis, I want to understand how people live
	differently in various cities and measure how places are similar or
	not. But to evaluate my results, I need information from inhabitants
	and thus your help is precious.

You will be presented with a map and a series of {{ total|safe }}
	activities.  For each one, please draw where you would do it.

            <form id="choose">

Start by picking the city most familiar to you (if you have lived
            elsewhere than Helsinki, I would love to hear from it)
			<select id="pick" autofocus>
				<option value="fake" selected="selected"> </option>
				{% for city in cities %}
                {% if city.short == 'moscow' %}
                <optgroup label="Europe, North">
                {% elif city.short == 'london' %}
                </optgroup><optgroup label="Europe, Middle">
                {% elif city.short == 'rome' %}
                </optgroup><optgroup label="Europe, South">
                {% elif city.short == 'newyork' %}
                 </optgroup><optgroup label="USA, East">
                {% elif city.short == 'chicago' %}
                </optgroup><optgroup label="USA, Middle">
                {% elif city.short == 'sanfrancisco' %}
                </optgroup><optgroup label="USA, West">
                {% endif %}
				<option value="{{ city.short }}">{{ city.long }}</option>
                {% if city.short == 'seattle' %}
                </optgroup>
                {% endif %}
				{% endfor %}
            </select>. Then, let's seehow it works.
</form>

{% endblock %}