text:
---
id: api-reference-relay-mutation
title: Relay.Mutation
layout: docs
category: API Reference
permalink: docs/api-reference-relay-mutation.html
next: api-reference-relay-proptypes
---

Relay makes use of GraphQL mutations; operations that enable us to mutate data on the client and server. To create a mutation for use in our app, we subclass `Relay.Mutation` and implement, at minimum, the four abstract methods listed below.

## Overview

*Properties*

static fragments

      Declare this mutation's data dependencies here

static initialVariables

      A default set of variables to make available to this mutation's fragment builders

static prepareVariables

      A method to modify the variables based on the runtime environment, previous variables, or the meta route

*Methods*

constructor(props)

abstract getConfigs()

abstract getFatQuery()

abstract getMutation()

abstract getVariables()

static getFragment(fragmentName[, variableMapping])

getCollisionKey()

getFiles()

getOptimisticConfigs()

getOptimisticResponse()

## Properties

### fragments (static property)

```
static fragments: RelayMutationFragments<$Enum<Tp>>

// Type of RelayMutationFragments
type RelayMutationFragments<Tk> = {
  [key: Tk]: FragmentBuilder;
};

// Type of FragmentBuilder
type FragmentBuilder = (variables: Variables) => RelayConcreteNode;
```

We declare our mutations' data dependencies here, just as we would with a container. This is particularly useful to ensure that a set of fields we might want to use in this mutation's optimistic response have been fetched.

#### Example

```{2-9}
class LikeStoryMutation extends Relay.Mutation {
  static fragments = {
    story: () => Relay.QL`
      fragment on Story {
        likers { count },
        viewerDoesLike,
      }
    `,
  };
  getOptimisticResponse() {
    // this.props.story.likers.count and this.props.story.viewerDoesLike
    // are guaranteed to have been fetched since we've declared
    // them to be part of this mutation's data dependencies above.
    return { /* ... */ };
  }
}
```

See also:
[Mutations > Fragment variables](guides-mutations.html#fragment-variables) and
[Mutations > Optimistic updates](guides-mutations.html#optimistic-updates)

### initialVariables (static property)

```
static initialVariables: {[name: string]: mixed};
```

The defaults we specify here will become available to our fragment builders:

#### Example

```
class ChangeTodoStatusMutation extends Relay.Mutation {
  static initialVariables = {orderby: 'priority'};
  static fragments = {
    todos: () => Relay.QL`
      # The variable defined above is available here as $orderby
      fragment on User { todos(orderby: $orderby) { ... } }
    `,
  };
  /* ... */
}
```

See also:
[Mutations > Fragment variables](guides-mutations.html#fragment-variables)

### prepareVariables (static property)

```
static prepareVariables: ?(
  prevVariables: {[name: string]: mixed},
  route: RelayMetaRoute,
) => {[name: string]: mixed}

// Type of `route` argument
type RelayMetaRoute = {
  name: string;
}
```

If we provide to a mutation a method that conforms to the signature described above, it will be given the opportunity to modify the fragment builders' variables, based on the previous variables (or the `initialVariables` if no previous ones exist), the meta route, and the runtime environment. Whatever variables this method returns will become available to this mutation's fragment builders.

#### Example

```
class BuySongMutation extends Relay.Mutation {
  static initialVariables = {format: 'mp3'};
  static prepareVariables = (prevVariables) => {
    var overrideVariables = {};
    var formatPreference = localStorage.getItem('formatPreference');
    if (formatPreference) {
      overrideVariables.format = formatPreference;  // Lossless, hopefully
    }
    return {...prevVariables, overrideVariables};
  };
  /* ... */
}
```

See also:
[Mutations > Fragment variables](guides-mutations.html#fragment-variables)

## Methods

### constructor

Create a mutation instance using the `new` keyword, optionally passing it some props.

#### Example

```
var bookFlightMutation = new BuyPlaneTicketMutation({airport: 'yvr'});
Relay.Store.update(bookFlightMutation);
```

### getConfigs (abstract method)

```
abstract getConfigs(): Array<{[key: string]: mixed}>
```

Implement this required method to give Relay instructions on how to use the response payload from each mutation to update the client-side store.

#### Example

```
class BuySongMutation extends Relay.Mutation {
  getFatQuery() {
    return Relay.QL`
      fragment on BuySongMutationPayload {
        collection {
          songs {
            count,
            edges,
          }
          totalRunTime,
        },
        viewer {
          hasPurchasedMusic,
        },
      }
    `,
  }
}
```

See also: [Mutations > Mutator configuration](guides-mutations.html#mutator-configuration)

### getFatQuery (abstract method)

```
abstract getFatQuery(): GraphQL.Fragment
```

Implement this required method to design a 'fat query' – one that represents every field in your data model that could change as a result of this mutation.

#### Example

```
class BuySongMutation extends Relay.Mutation {
  getFatQuery() {
    return Relay.QL`
      fragment on Collection {
        songs {
          count,
          edges,
        },
        totalRunTime,
      }
    `,
  }
}
```

See also:
[Mutations > The fat query](guides-mutations.html#the-fat-query)

### getMutation (abstract method)

```
abstract getMutation(): GraphQL.Mutation
```

Implement this required method to return a GraphQL mutation operation that represents the mutation to be performed.

#### Example

```
class LikeStoryMutation extends Relay.Mutation {
  getMutation() {
    return this.props.story.viewerDoesLike
      ? return Relay.QL`mutation {unlikeStory}`
      : return Relay.QL`mutation {likeStory}`;
  }
}
```

### getVariables (abstract method)

```
abstract getVariables(): {[name: string]: mixed}
```

Implement this required method to prepare variables to be used as input to the mutation.

#### Example

```
class DestroyShipMutation extends Relay.Mutation {
  getVariables() {
    return {
      // Assume that the server exposes a `destroyShip` mutation
      // that accepts a `shipIDToDestroy` variable as input:
      shipIDToDestroy: this.props.ship.id,
    };
  }
}
```

> Warning
>
> The term 'variables' here refers to the input to the server-side mutation, **not** to the variables made available to this mutation's fragment builders.

### getFragment (static method)

```
static getFragment(
  fragmentName: $Enum<Tp>,
  variableMapping?: Variables
): RelayFragmentReference

// Type of the variableMapping argument
type Variables = {[name: string]: mixed};
```

Gets a fragment reference for use in a parent's query fragment.

#### Example

```{8}
class StoryComponent extends React.Component {
  /* ... */
  static fragments = {
    story: () => Relay.QL`
      fragment on Story {
        id,
        text,
        ${LikeStoryMutation.getFragment('story')},
      }
    `,
  };
}
```

You can also pass variables to the mutation's fragment builder from the outer fragment that contains it.

```{8-11}
class Movie extends React.Component {
  /* ... */
  static fragments = {
    movie: () => Relay.QL`
      fragment on Movie {
        posterImage(lang: $lang) { url },
        trailerVideo(format: $format, lang: $lang) { url },
        ${RentMovieMutation.getFragment('movie', {
          format: variables.format,
          lang: variables.lang,
        })},
      }
    `,
  };
}
```

> Hint
>
> In that last example, think of `$format` and `variables.format` as the same value.

### getCollisionKey

```
getCollisionKey(): ?string
```

Implement this method to return a collision key. Relay will send any mutations having the same collision key to the server serially and in-order.

#### Example

```
class LikeStoryMutation extends Relay.Mutation {
  getCollisionKey() {
    // Give the same key to like mutations that affect the same story
    return `like_${this.props.story.id}`;
  }
}
```

### getFiles

```
getFiles(): ?FileMap

// Type of the FileMap object
type FileMap = {[key: string]: File};
```

Implement this method to return a map of `File` objects to upload as part of a mutation.

#### Example

```
class AttachDocumentMutation extends Relay.Mutation {
  getFiles() {
    return {
      file: this.props.file,
    };
  }
}
class FileUploader extends React.Component {
  handleSubmit() {
    var fileToAttach = this.refs.fileInput.files.item(0);
    Relay.Store.update(
      new AttachDocumentMutation({file: fileToAttach})
    );
  }
}
```

### getOptimisticConfigs

```
getOptimisticConfigs(): Array<{[key: string]: mixed}>
```

Implement this method in cases where the mutator configuration needed to handle the optimistic response need be different than the one that handles the server response.

See also: [Relay.Mutation::getConfigs()](#getconfigs-abstract-method)

### getOptimisticResponse

```
getOptimisticResponse(): ?{[key: string]: mixed}
```

Implement this method to craft an optimistic response having the same shape as the server response payload. This optimistic response will be used to preemptively update the client cache before the server returns, giving the impression that the mutation completed instantaneously.

#### Example

```
class LikeStoryMutation extends Relay.Mutation {
  getOptimisticResponse() {
    return {
      story: {
        id: this.props.story.id,
        likers: {
          count: this.props.story.likers.count + 1,
        },
        viewerDoesLike: !this.props.story.viewerDoesLike,
      },
    };
  }
}
```

See also: [Mutations > Optimistic updates](guides-mutations.html#optimistic-updates)


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:orientation="horizontal"
    android:paddingEnd="6dip"
    android:gravity="center_vertical"
    >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="@android:dimen/app_icon_size"
        android:layout_height="@android:dimen/app_icon_size"
        android:layout_gravity="center_vertical"
        android:scaleType="centerInside"
        android:contentDescription="@null"
        />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dip"
        android:layout_marginBottom="8dip"
        android:orientation="vertical"
        android:gravity="left|center_vertical"
        android:layout_weight="1">

        <TextView android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:ellipsize="marquee"
            android:fadingEdge="horizontal" />

        <TextView android:id="@+id/description"
            android:visibility="gone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dip"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="?android:attr/textColorSecondary"
            android:maxLines="4" />

    </LinearLayout>

    <CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginEnd="16dip"
        android:layout_marginStart="16dip"
        android:focusable="false"
        android:clickable="false" />

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Specialized;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace Repo2.SDK.WPF45.UserControls
{
    /// <summary>
    /// Extended TabControl which saves the displayed item so you don't get the performance hit of
    /// unloading and reloading the VisualTree when switching tabs
    /// </summary>
    /// <remarks>
    /// Based on example from http://stackoverflow.com/a/9802346, which in turn is based on
    /// http://www.pluralsight-training.net/community/blogs/eburke/archive/2009/04/30/keeping-the-wpf-tab-control-from-destroying-its-children.aspx
    /// with some modifications so it reuses a TabItem's ContentPresenter when doing drag/drop operations
    /// </remarks>
    [TemplatePart(Name = "PART_ItemsHolder", Type = typeof(Panel))]
    public class NonReloadingTabControl : TabControl
    {
        private Panel itemsHolderPanel;

        public NonReloadingTabControl()
        {
            // This is necessary so that we get the initial databound selected item
            ItemContainerGenerator.StatusChanged += ItemContainerGeneratorStatusChanged;

            Loaded += async (a, b) =>
            {
                if (Items.Count == 0) return;
                await Task.Delay(1);
                SelectedIndex = 0;
            };
        }

        /// <summary>
        /// If containers are done, generate the selected item
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void ItemContainerGeneratorStatusChanged(object sender, EventArgs e)
        {
            if (ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
            {
                ItemContainerGenerator.StatusChanged -= ItemContainerGeneratorStatusChanged;
                UpdateSelectedItem();
            }
        }

        /// <summary>
        /// Get the ItemsHolder and generate any children
        /// </summary>
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            itemsHolderPanel = GetTemplateChild("PART_ItemsHolder") as Panel;
            UpdateSelectedItem();
        }

        /// <summary>
        /// When the items change we remove any generated panel children and add any new ones as necessary
        /// </summary>
        /// <param name="e">The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
        protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
        {
            base.OnItemsChanged(e);

            if (itemsHolderPanel == null)
                return;

            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Reset:
                    itemsHolderPanel.Children.Clear();
                    break;

                case NotifyCollectionChangedAction.Add:
                case NotifyCollectionChangedAction.Remove:
                    if (e.OldItems != null)
                    {
                        foreach (var item in e.OldItems)
                        {
                            var cp = FindChildContentPresenter(item);
                            if (cp != null)
                                itemsHolderPanel.Children.Remove(cp);
                        }
                    }

                    // Don't do anything with new items because we don't want to
                    // create visuals that aren't being shown

                    UpdateSelectedItem();
                    break;

                case NotifyCollectionChangedAction.Replace:
                    throw new NotImplementedException("Replace not implemented yet");
            }
        }

        protected override void OnSelectionChanged(SelectionChangedEventArgs e)
        {
            base.OnSelectionChanged(e);
            UpdateSelectedItem();
        }

        private void UpdateSelectedItem()
        {
            if (itemsHolderPanel == null)
                return;

            // Generate a ContentPresenter if necessary
            var item = GetSelectedTabItem();
            if (item != null)
                CreateChildContentPresenter(item);

            // show the right child
            foreach (ContentPresenter child in itemsHolderPanel.Children)
                child.Visibility = ((child.Tag as TabItem).IsSelected) ? Visibility.Visible : Visibility.Collapsed;
        }

        private ContentPresenter CreateChildContentPresenter(object item)
        {
            if (item == null)
                return null;

            var cp = FindChildContentPresenter(item);

            if (cp != null)
                return cp;

            var tabItem = item as TabItem;
            cp = new ContentPresenter
            {
                Content = (tabItem != null) ? tabItem.Content : item,
                ContentTemplate = this.SelectedContentTemplate,
                ContentTemplateSelector = this.SelectedContentTemplateSelector,
                ContentStringFormat = this.SelectedContentStringFormat,
                Visibility = Visibility.Collapsed,
                Tag = tabItem ?? (this.ItemContainerGenerator.ContainerFromItem(item))
            };
            itemsHolderPanel.Children.Add(cp);
            return cp;
        }

        private ContentPresenter FindChildContentPresenter(object data)
        {
            if (data is TabItem)
                data = (data as TabItem).Content;

            if (data == null)
                return null;

            if (itemsHolderPanel == null)
                return null;

            foreach (ContentPresenter cp in itemsHolderPanel.Children)
            {
                if (cp.Content == data)
                    return cp;
            }

            return null;
        }

        protected TabItem GetSelectedTabItem()
        {
            var selectedItem = SelectedItem;
            if (selectedItem == null)
                return null;

            var item = selectedItem as TabItem ?? ItemContainerGenerator.ContainerFromIndex(SelectedIndex) as TabItem;

            return item;
        }
    }
}


text:
class OmniboxPopupModelObserver;
class OmniboxPopupView;

namespace gfx {
class Image;
}

class OmniboxPopupModel {
 public:
  // See selected_line_state_ for details.
  enum LineState {
    NORMAL = 0,
    KEYWORD
  };

  OmniboxPopupModel(OmniboxPopupView* popup_view, OmniboxEditModel* edit_model);
  ~OmniboxPopupModel();

  // Computes the maximum width, in pixels, that can be allocated for the two
  // parts of an autocomplete result, i.e. the contents and the description.
  static void ComputeMatchMaxWidths(int contents_width,
                                    int separator_width,
                                    int description_width,
                                    int available_width,
                                    bool allow_shrinking_contents,
                                    int* contents_max_width,
                                    int* description_max_width);

  // Returns true if the popup is currently open.
  bool IsOpen() const;

  OmniboxPopupView* view() const { return view_; }

  // Returns the AutocompleteController used by this popup.
  AutocompleteController* autocomplete_controller() const {
    return edit_model_->autocomplete_controller();
  }

  const AutocompleteResult& result() const {
    return autocomplete_controller()->result();
  }

  size_t hovered_line() const { return hovered_line_; }

  // Call to change the hovered line.  |line| should be within the range of
  // valid lines (to enable hover) or kNoMatch (to disable hover).
  void SetHoveredLine(size_t line);

  size_t selected_line() const { return selected_line_; }

  LineState selected_line_state() const { return selected_line_state_; }

  // Call to change the selected line.  This will update all state and repaint
  // the necessary parts of the window, as well as updating the edit with the
  // new temporary text.  |line| will be clamped to the range of valid lines.
  // |reset_to_default| is true when the selection is being reset back to the
  // default match, and thus there is no temporary text (and no
  // |manually_selected_match_|). If |force| is true then the selected line will
  // be updated forcibly even if the |line| is same as the current selected
  // line.
  // NOTE: This assumes the popup is open, and thus both old and new values for
  // the selected line should not be kNoMatch.
  void SetSelectedLine(size_t line, bool reset_to_default, bool force);

  // Called when the user hits escape after arrowing around the popup.  This
  // will change the selected line back to the default match and redraw.
  void ResetToDefaultMatch();

  // Immediately updates and opens the popup if necessary, then moves the
  // current selection down (|count| > 0) or up (|count| < 0), clamping to the
  // first or last result if necessary.  If |count| == 0, the selection will be
  // unchanged, but the popup will still redraw and modify the text in the
  // OmniboxEditModel.
  void Move(int count);

  // If the selected line has both a normal match and a keyword match, this can
  // be used to choose which to select.  This allows the user to toggle between
  // normal and keyword mode with tab/shift-tab without rerunning autocomplete
  // or disturbing other popup state, which in turn is an important part of
  // supporting the use of tab to do both tab-to-search and
  // tab-to-traverse-dropdown.
  //
  // It is an error to call this when the selected line does not have both
  // matches (or there is no selection).
  void SetSelectedLineState(LineState state);

  // Called when the user hits shift-delete.  This should determine if the item
  // can be removed from history, and if so, remove it and update the popup.
  void TryDeletingCurrentItem();

  // If |match| is from an extension, returns the extension icon; otherwise
  // returns an empty Image.
  gfx::Image GetIconIfExtensionMatch(const AutocompleteMatch& match) const;

  // Returns true if the destination URL of the match is bookmarked.
  bool IsStarredMatch(const AutocompleteMatch& match) const;

  // The match the user has manually chosen, if any.
  const AutocompleteResult::Selection& manually_selected_match() const {
    return manually_selected_match_;
  }

  // Invoked from the edit model any time the result set of the controller
  // changes.
  void OnResultChanged();

  // Add and remove observers.
  void AddObserver(OmniboxPopupModelObserver* observer);
  void RemoveObserver(OmniboxPopupModelObserver* observer);

  // Stores the image in a local data member and schedules a repaint.
  void SetAnswerBitmap(const SkBitmap& bitmap);
  const SkBitmap& answer_bitmap() const { return answer_bitmap_; }

  // The token value for selected_line_, hover_line_ and functions dealing with
  // a "line number" that indicates "no line".
  static const size_t kNoMatch;

 private:
  SkBitmap answer_bitmap_;

  OmniboxPopupView* view_;

  OmniboxEditModel* edit_model_;

  // The line that's currently hovered.  If we're not drawing a hover rect,
  // this will be kNoMatch, even if the cursor is over the popup contents.
  size_t hovered_line_;

  // The currently selected line.  This is kNoMatch when nothing is selected,
  // which should only be true when the popup is closed.
  size_t selected_line_;

  // If the selected line has both a normal match and a keyword match, this
  // determines whether the normal match (if NORMAL) or the keyword match
  // (if KEYWORD) is selected.
  LineState selected_line_state_;

  // The match the user has manually chosen, if any.
  AutocompleteResult::Selection manually_selected_match_;

  // Observers.
  base::ObserverList<OmniboxPopupModelObserver> observers_;

  DISALLOW_COPY_AND_ASSIGN(OmniboxPopupModel);
};

#endif  // COMPONENTS_OMNIBOX_BROWSER_OMNIBOX_POPUP_MODEL_H_


text:
package org.azolla.p.james.panel;

import com.google.common.base.Strings;
import org.azolla.l.ling.i18n.I18N0;
import org.azolla.l.ling.io.File0;
import org.azolla.l.ling.lang.String0;
import org.azolla.l.ling.net.Url0;
import org.azolla.l.ling.util.Date0;
import org.azolla.l.ling.util.Log0;
import org.azolla.l.sunny.dlg.Msg;
import org.azolla.l.sunny.layout.GBC;
import org.azolla.l.sunny.task.UITasks;
import org.azolla.p.james.bo.ExcelSheetBo;
import org.azolla.p.james.bo.JamesBo;
import org.azolla.p.james.startup.Startup;
import org.azolla.p.james.util.ExcelParser;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.text.MessageFormat;
import java.util.concurrent.Callable;

/**
 * The coder is very lazy, nothing to write for this class
 *
 * @author sk@azolla.org
 * @since ADK1.0
 */
public class JamesPanel extends JPanel
{
    public static final int W = 600;
    public static final int H = 100;

    JTextField pathTextField          = new JTextField();
    JButton    selectButton           = new JButton(I18N0.i18n(this.getClass()).get("Select"));
    JButton    downloadTemplateButton = new JButton(I18N0.i18n(this.getClass()).get("DownloadTemplate"));
    JButton    generateSqlButton      = new JButton(I18N0.i18n(this.getClass()).get("GenerateSql"));

    private JamesPanel()
    {
        super();
        initUI();
        initListener();
    }

    public static final JamesPanel single()
    {
        return SigletonHolder.instance;
    }

    private void initListener()
    {
        selectButton.addActionListener((e) -> {
            JFileChooser jFileChooser = createJFileChooser();
            int result = jFileChooser.showOpenDialog(JamesPanel.single());
            if (result == JFileChooser.APPROVE_OPTION)
            {
                pathTextField.setText(jFileChooser.getSelectedFile().getAbsolutePath());
            }
        });

        downloadTemplateButton.addActionListener((e) -> {
            JFileChooser jFileChooser = createJFileChooser();
            int result = jFileChooser.showSaveDialog(JamesPanel.single());
            if (result == JFileChooser.APPROVE_OPTION)
            {
                if (File0.copy(File0.newFile(Url0.getURL(I18N0.i18n(this.getClass()).get("TEMPLATE_NAME")).getPath()), jFileChooser.getSelectedFile()))
                {
                    Msg.info(JamesPanel.single(), I18N0.i18n(this.getClass()).get("MSG_OPERATION_SUCCESSFULLY"));
                }
                else
                {
                    Msg.error(JamesPanel.single(), I18N0.i18n(this.getClass()).get("MSG_OPERATION_FAILED"));
                }
            }
        });

        generateSqlButton.addActionListener((e) -> {
            File currentFile = null;
            if (!Strings.isNullOrEmpty(pathTextField.getText()))
            {
                currentFile = File0.newFile(pathTextField.getText());
            }
            if (currentFile != null && currentFile.exists())
            {
                final File finalCurrentFile = currentFile;
                try
                {
                    UITasks.createUITask(null, new Callable<Object>()
                    {
                        @Override
                        public Object call() throws Exception
                        {
                            Startup.refreshTitle(I18N0.i18n(this.getClass()).get("ING_PROCESS"));
                            JamesBo.single().clear();

                            ExcelParser.SIGLETON.parseJamesExcel(finalCurrentFile);
                            ExcelParser.SIGLETON.parseJamesDB(finalCurrentFile);
                            for (ExcelSheetBo excelSheetBo : JamesBo.single().getStringExcelSheetBoMap().values())
                            {
                                ExcelParser.SIGLETON.parseJamesData(finalCurrentFile, excelSheetBo);
                            }
                            JamesBo.single().validate();
                            JamesBo.single().convert();
                            File folder = File0.newFile(finalCurrentFile.getParentFile(), Date0.DATATIME());
                            folder.mkdirs();
                            JamesBo.single().generateSql(folder);
                            if (JamesBo.single().hasError())
                            {
                                JamesBo.single().recordError(folder);
                            }
                            return true;
                        }
                    }).execute();
                }
                catch (Exception exp)
                {
                    Log0.error(this.getClass(), exp.toString(), exp);
                    Msg.error(JamesPanel.single(), exp.toString());
                }
                finally
                {
                    Startup.refreshTitle(I18N0.i18n(this.getClass()).get("version"));
                }
            }
            else
            {
                Msg.error(JamesPanel.single(), MessageFormat.format(I18N0.i18n(this.getClass()).get("FMT_CANNOT_FIND"), pathTextField.getText()));
            }
        });
    }

    private JFileChooser createJFileChooser()
    {
        JFileChooser jFileChooser = new JFileChooser();
        jFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jFileChooser.setFileFilter(new FileNameExtensionFilter(I18N0.i18n(this.getClass()).get("FILE_DESC_EXCEL"), new String[]{I18N0.i18n(this.getClass()).get("FILE_SUFFIX_XLSX")}));
        File currentFile = null;
        if (!Strings.isNullOrEmpty(pathTextField.getText()))
        {
            currentFile = File0.newFile(pathTextField.getText());
        }
        if (currentFile != null && currentFile.exists())
        {
            jFileChooser.setCurrentDirectory(currentFile);
        }
        else
        {
            jFileChooser.setCurrentDirectory(File0.newFile(Url0.getURL(String0.SLASH).getPath()));
        }
        return jFileChooser;
    }

    private void initUI()
    {
        //do nothing
        setLayout(new GridBagLayout());
//        setBackground(new Color(192, 192, 192, 192));

        JLabel selectPathButtion = new JLabel(I18N0.i18n(this.getClass()).get("SelectPath"));
        add(selectPathButtion, GBC.grid(0, 0, 1, 1).weight(0, 0).anchor(GBC.EAST).fill(GBC.NONE).insets(8, 8, 1, 1));

        pathTextField.setEditable(false);
//        pathTextField.setFocusable(false);
        add(pathTextField, GBC.grid(1, 0, 8, 1).weight(8, 0).anchor(GBC.CENTER).fill(GBC.BOTH).insets(8, 1, 1, 1));

        add(selectButton, GBC.grid(9, 0, 1, 1).weight(0, 0).anchor(GBC.WEST).fill(GBC.NONE).insets(8, 1, 1, 8));

        add(new JPanel(), GBC.grid(0, 1, 4, 1).weight(4, 0).anchor(GBC.CENTER).fill(GBC.HORIZONTAL).insets(1, 8, 8, 1));
        add(downloadTemplateButton, GBC.grid(4, 1, 1, 1).weight(0, 0).anchor(GBC.EAST).fill(GBC.NONE).insets(1, 1, 8, 1));

        add(generateSqlButton, GBC.grid(5, 1, 1, 1).weight(0, 0).anchor(GBC.WEST).fill(GBC.NONE).insets(1, 1, 8, 1));
        add(new JPanel(), GBC.grid(6, 1, 3, 1).weight(3, 0).anchor(GBC.CENTER).fill(GBC.HORIZONTAL).insets(1, 1, 8, 1));
        add(new JPanel(), GBC.grid(9, 1, 1, 1).weight(0, 0).anchor(GBC.CENTER).fill(GBC.NONE).insets(1, 1, 8, 8));

    }

    private static class SigletonHolder
    {
        private static final JamesPanel instance = new JamesPanel();
    }
}


text:
define(
  ["dojo/_base/declare",
    "dojo/_base/lang",
    "dojo/_base/array",
    "dojo/text!./EditFields.html",
    'dijit/_TemplatedMixin',
    'jimu/BaseWidgetSetting',
    'jimu/dijit/SimpleTable',
    "jimu/dijit/Popup"
  ],
  function(
    declare,
    lang,
    array,
    template,
    _TemplatedMixin,
    BaseWidgetSetting,
    Table,
    Popup) {
    return declare([BaseWidgetSetting, _TemplatedMixin], {
      baseClass: "jimu-widget-edit-setting-fields",
      templateString: template,
      _layerInfo: null,

      postCreate: function() {
        this.inherited(arguments);
        this.nls = lang.mixin(this.nls, window.jimuNls.common);
        this._initFieldsTable();
        this._setFiedsTabele(this._layerInfo.fieldInfos);
      },

      popupEditPage: function() {
        var fieldsPopup = new Popup({
          titleLabel: this.nls.configureFields,
          width: 640,
          maxHeight: 600,
          autoHeight: true,
          content: this,
          buttons: [{
            label: this.nls.ok,
            onClick: lang.hitch(this, function() {
              this._resetFieldInfos();
              fieldsPopup.close();
            })
          }, {
            label: this.nls.cancel,
            classNames: ['jimu-btn-vacation'],
            onClick: lang.hitch(this, function() {
              fieldsPopup.close();
            })
          }],
          onClose: lang.hitch(this, function() {
          })
        });
      },

      _initFieldsTable: function() {
        var fields2 = [{
          name: 'visible',
          title: this.nls.display,
          type: 'checkbox',
          'class': 'display'
        }, {
          name: 'isEditable',
          title: this.nls.edit,
          type: 'checkbox',
          'class': 'editable'
        }, {
          name: 'fieldName',
          title: this.nls.editpageName,
          type: 'text'
        }, {
          name: 'label',
          title: this.nls.editpageAlias,
          type: 'text',
          editable: true
        }, {
          name: 'actions',
          title: this.nls.actions,
          type: 'actions',
          actions: ['up', 'down'],
          'class': 'actions'
        }];
        var args2 = {
          fields: fields2,
          selectable: false,
          style: {
            'height': '300px',
            'maxHeight': '300px'
          }
        };
        this._fieldsTable = new Table(args2);
        this._fieldsTable.placeAt(this.fieldsTable);
        this._fieldsTable.startup();
      },

      _setFiedsTabele: function(fieldInfos) {
        array.forEach(fieldInfos, function(fieldInfo) {
          this._fieldsTable.addRow({
            fieldName: fieldInfo.fieldName,
            isEditable: fieldInfo.isEditable,
            label: fieldInfo.label,
            visible: fieldInfo.visible
          });

        }, this);

        // Bind 'onChange' events for visble and isEditable.
        setTimeout(lang.hitch(this, function() {
          array.forEach(this._fieldsTable.fields, function(field) {
            if(field.name === 'visible') {
              field.onChange = lang.hitch(this, this._onDisplayFieldChanged);
            } else if(field.name === 'isEditable') {
              field.onChange = lang.hitch(this, this._onIsEditableFieldChanged);
            }
          }, this);
        }), 300);
      },

      _onDisplayFieldChanged: function(tr) {
        var rowData = this._fieldsTable.getRowData(tr);
        var display = rowData.visible;
        if(!display && rowData.isEditable) {
          rowData.isEditable = false;
          this._fieldsTable.editRow(tr, rowData);
        }
      },

      _onIsEditableFieldChanged: function(tr) {
        var rowData = this._fieldsTable.getRowData(tr);
        var isEditable  = rowData.isEditable;
        if(isEditable && !rowData.visible) {
          rowData.visible = true;
          this._fieldsTable.editRow(tr, rowData);
        }
      },

      _resetFieldInfos: function() {
        var newFieldInfos = [];
        var fieldsTableData =  this._fieldsTable.getData();
        array.forEach(fieldsTableData, function(fieldData) {
          newFieldInfos.push({
            "fieldName": fieldData.fieldName,
            "label": fieldData.label,
            "isEditable": fieldData.isEditable,
            "visible": fieldData.visible
          });
        });

        this._layerInfo.fieldInfos = newFieldInfos;
      }

    });
  });


text:
<?php
namespace SubscriptionProduct\Controller;

use Application\Controller\BaseController;
use SubscriptionProduct\Service\SubscriptionProductServiceInterface;
use Zend\View\Model\ViewModel;
use Subscription\Service\SubscriptionServiceInterface;

class ViewController extends BaseController
{
    /**
     *
     * @var SubscriptionProductServiceInterface
     */
    protected $service;

    /**
     *
     * @var SubscriptionServiceInterface
     */
    protected $subscriptionService;

    /**
     *
     * @param SubscriptionProductServiceInterface $service
     * @param SubscriptionServiceInterface $subscriptionService
     */
    public function __construct(SubscriptionProductServiceInterface $service, SubscriptionServiceInterface $subscriptionService)
    {
        $this->service = $service;

        $this->subscriptionService = $subscriptionService;
    }

    /**
     *
     * {@inheritDoc}
     * @see \Zend\Mvc\Controller\AbstractActionController::indexAction()
     */
    public function indexAction()
    {
        $id = $this->params()->fromRoute('subscriptionProductId');

        $entity = $this->service->get($id);

        if(! $entity) {
            $this->flashMessenger()->addErrorMessage('Subscription Product not found');

            return $this->redirect()->toRoute('subscription-index', array('clientId' => $this->clientId));
        }

        $subscriptionEntity = $this->subscriptionService->get($entity->getSubscriptionId());

        // trigger event
        $this->getEventManager()->trigger('subscriptionProductView', $this, array(
            'authId' => $this->identity()->getAuthId(),
            'historyUrl' => $this->getRequest()->getUri(),
            'subscriptionProductEntity' => $entity,
        ));

        return new ViewModel(array(
            'entity' => $entity,
            'subscriptionEntity' => $subscriptionEntity
        ));
    }
}


text:
{% load i18n %}

		{% trans "Browser Error" %}

			{% trans "close" %}

			{% trans "Recommended Browser Alert" %}

				{% trans "Dear Sir or Madam," %}

				{% trans "Our tests indicate that you are currently using a browser that does not support complex navigation. We highly recommend that you switch to one of the browsers below in order to take full advantage of the Nigeria MDGs Information System." %}

					Mozilla Firefox

					Google Chrome

				{% trans "Thank You," %}

				{% trans "The NMIS Support Team" %}


text:
sap.ui.define(['./library', "../core/library", '../core/ListItemBase'], function(ui5strapBs3Lib, ui5strapCoreLib, ListItemBase){

	"use strict";

	/**
	 * Constructor for a new ListGroupItem instance.
	 *
	 * @param {string} [sId] ID for the new control, generated automatically if no ID is given
	 * @param {object} [mSettings] Initial settings for the new control
	 *
	 * @class
	 * Control for creating items for ListGroup controls.
	 * @extends pks.ui5strap.core.ControlBase
	 *
	 * @author Jan Philipp Knoeller
	 * @version 1.0.2-SNAPSHOT
	 *
	 * @constructor
	 * @public
	 * @alias pks.ui5strap.bs3.ListGroupItem
	 *
	 */
	var ListGroupItem = ListItemBase.extend("pks.ui5strap.bs3.ListGroupItem", /** @lends pks.ui5strap.bs3.ListGroupItem.prototype */ {
		metadata : {

			// ---- object ----
			defaultAggregation : "content",

			// ---- control specific ----
			library : "pks.ui5strap.bs3",
			properties : {
				text : {
					type:"string",
					defaultValue:""
				},
				parse : {
					type : "boolean",
					defaultValue : false
				},
				contentPlacement : {
					type:"pks.ui5strap.core.ContentPlacement",
					defaultValue : ui5strapCoreLib.ContentPlacement.Start
				},
				badge : {
					type:"string",
					defaultValue : ""
				},
				icon : {
					type:"string",
					defaultValue : ""
				},
				severity : {
					type: "pks.ui5strap.bs3.Severity",
					defaultValue: ui5strapBs3Lib.Severity.None
				}
			}
		}
	});

	/**
	 * Returns the style prefix of this control.
	 * @override
	 * @protected
	 */
	ListGroupItem.prototype._getStyleClassPrefix = function(){
		return "ui5strapListGroupItem";
	};

	return ListGroupItem;
});


text:
namespace KnowledgeSpreadSystem.Web.Areas.Administration.ViewModels.University
{
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;

    using KnowledgeSpreadSystem.Models;
    using KnowledgeSpreadSystem.Web.Areas.Administration.ViewModels.Base;
    using KnowledgeSpreadSystem.Web.Infrastructure.Mapping;

    public class UniversityViewModel : AdminViewModel, IMapFrom<University>, ISimpleView<SimpleViewModel>
    {
        [HiddenInput(DisplayValue = false)]
        public int? Id { get; set; }

        [Required]
        [MinLength(3)]
        [MaxLength(30)]
        public string Name { get; set; }

        [MinLength(20)]
        [MaxLength(700)]
        public string About { get; set; }

    }
}


text:
require 'spec_helper'

describe AWSCloudSearch::SearchRequest do
  let(:search_req) { AWSCloudSearch::SearchRequest.new }

  context "#add_facet_top_n" do
    it "should raise ArgumentError when param is not an Integer" do
      expect { search_req.add_facet_top_n("fieldname", "string") }.to raise_error(ArgumentError)
    end
  end

  context "#add_t" do
    it "should raise ArgumentError when range beginning and end are nil" do
      expect {search_req.add_t("fieldname", nil, nil)}.to raise_error(ArgumentError)
    end

    it "should raise ArgumentError when t_from or t_to are not Integers" do
      expect {search_req.add_t("fieldname", "string", 10)}.to raise_error(ArgumentError)
      expect {search_req.add_t("fieldname", 10, "string")}.to raise_error(ArgumentError)
      expect {search_req.add_t("fieldname", "string", "string")}.to raise_error(ArgumentError)
    end
  end

  context "#to_hash" do
    it "should return an empty hash" do
      search_req.to_hash.should eq({})
    end
  end

end


text:
namespace blink {

class ScriptState;
class SerializedScriptValue;

CORE_EXPORT void v8ConstructorAttributeGetter(
    v8::Local<v8::Name> propertyName,
    const v8::PropertyCallbackInfo<v8::Value>&);

CORE_EXPORT v8::Local<v8::Value> v8Deserialize(
    v8::Isolate*,
    PassRefPtr<SerializedScriptValue>);

// ExceptionToRejectPromiseScope converts a possible exception to a reject
// promise and returns the promise instead of throwing the exception.
//
// Promise-returning DOM operations are required to always return a promise
// and to never throw an exception.
// See also http://heycam.github.io/webidl/#es-operations
class CORE_EXPORT ExceptionToRejectPromiseScope {
  STACK_ALLOCATED();

 public:
  ExceptionToRejectPromiseScope(const v8::FunctionCallbackInfo<v8::Value>& info,
                                ExceptionState& exceptionState)
      : m_info(info),
        m_exceptionState(exceptionState) {}
  ~ExceptionToRejectPromiseScope() {
    if (!m_exceptionState.hadException())
      return;

    // As exceptions must always be created in the current realm, reject
    // promises must also be created in the current realm while regular promises
    // are created in the relevant realm of the context object.
    ScriptState* scriptState = ScriptState::forFunctionObject(m_info);
    v8SetReturnValue(m_info, m_exceptionState.reject(scriptState).v8Value());
  }

 private:
  const v8::FunctionCallbackInfo<v8::Value>& m_info;
  ExceptionState& m_exceptionState;
};

}  // namespace blink

#endif  // GeneratedCodeHelper_h


text:
namespace PhysBAM
{

template<class T> class LIST_ARRAY;

namespace STRING_UTILITIES
{

std::string Stripped_Whitespace (const std::string& str);

inline void Strip_Whitespace (std::string& str)
{
	str = Stripped_Whitespace (str);
}

bool Is_Number (const std::string& str); // integer or floating point
int Compare_Strings (const std::string &str1, const std::string &str2, bool case_sensitive = true);
std::string toupper (const std::string& str);
std::string string_sprintf (const char* format, ...);
std::string string_vsprintf (const char* format, va_list ap);
bool Parse_Integer_Range (const std::string& str, LIST_ARRAY<int>& integer_list);

// integer list format: [range],[range],[range],... where each [range] is either a single <number> or <number>-<number>, e.g. "1-3,4,7,10-11"
bool Parse_Integer_List (const std::string& str, LIST_ARRAY<int>& integer_list);

template<class T> inline bool String_To_Value (const std::string& str, T& value) // assumes operator>> defined
{
	std::istringstream string_stream (str);
	return (string_stream >> value) != 0;
}

//#####################################################################
}
}
#endif


text:
function SavePieces(%mod,%file)
{
if (!$PatchApplied)
{
error("Error: Requires the Ghost Patch to be applied.");
return 1;
}
if (!$Saver::Mod[%mod])
{
error("Error: No such HASH cache for '"@%mod@"'.");
return 1;
}

%count = ServerConnection.getcount();

if (!$Saver::QuietSave)
echo("Got Command Target Set Count: "@%count@"");

%data = "";

new fileobject(Ghoster);
Ghoster.openforwrite("buildings/"@%file@"");
Ghoster.writeline("//Saved with Dark Dragon DX's clientside Geometry Copier version 0.1b.");
Ghoster.writeline("//Saved on "@$MissionName@" - "@ServerConnection.getAddress()@" at "@formattimestring("mm-dd-yy, hh:nn A")@".");
Ghoster.writeline(" ");

for (%i = 0; %i < %count; %i++)
{
%obj = ServerConnection.getobject(%i);

if (%obj.getClassName() $= "StaticShape")
{
%db = %obj.getdatablock();
%db.Save("temp.txt");
%hash = GetFileCRC("temp.txt");

if (!$Saver::QuietSave)
echo("Got StaticShape, '"@%obj@"'. Hash: '"@%hash@"'.");

if ($Saver::DataBlockName[%hash,%mod] !$= "" && $Saver::DataBlockName[%hash,%mod] !$= "IGNORE") //Got a match, write up the save data.
{
%db = $Saver::DataBlockName[%hash,%mod];
%dat = "%building = new staticshape(){ Datablock = \x22"@%db@"\x22; Position = \x22"@%obj.getposition()@"\x22; Scale = \x22"@%obj.getscale()@"\x22; Rotation = \x22"@%obj.getRotation()@"\x22; Team = 1; PowerFreq = 1; OwnerGUID =  \x22NULL\x22; HasSlided = false; ToggleType = 0; Collision = true; LVL = 0; }; %building.setRotation(%building.rotation); AddToDeployGroup(%building);\n";
%data = %data SPC %dat;
}
else
if (!$Saver::QuietSave && $Saver::DataBlockName[%hash,%mod] !$= "IGNORE") warn("Warning: No valid HASH for object: '"@%obj@"' Datablock: '"@%db@"' Hash: '"@%hash@"'");

}

}
if (!$Saver::QuietSave)
warn("Clientside geometry successfully copied to file 'Buildings/"@%file@"'");

if ($Saver::DeleteTemp)
DeleteFile("temp.txt");

Ghoster.WriteLine(%data);
Ghoster.close();
Ghoster.delete();

for (%i = 0; %i < $PositionCount; %i++)
{
$PieceNum[$Piece[%i]] = false;
$Piece[%i] = "";
}

$PieceCount = 0;

return 1;
}

//<--Useful Functions-->\\
function GhostPatch()
{

if ($PatchApplied)
{
error("Error: Ghost patch already applied.");
return;
}

$PatchApplied = true;
memPatch("58B26D", "cc9c");
memPatch("4376B7", "9090");
memPatch("43745D", "9090");
memPatch("42E938", "9090");
memPatch("5E2EEC", "9090");
memPatch("602AF3", "9090");
memPatch("58C24C", "9090");
memPatch("6B40D0", "9090");
memPatch("5E34B6", "9090909090909090909090909090909090909090909090909090");
error("**ClientSide Ghost Patch Applied**");
}

function DoRayCast(%tobj,%typemask)
{
if (!$PatchApplied)
{
error("Error: Requires the Ghost Patch to be applied.");
return;
}
%pos          = %tobj.getEyeTransform();
%vec          = %tobj.getEyeVector();
%targetpos    = vectoradd(%pos,vectorscale(%vec,100));
%obj          = containerraycast(%pos,%targetpos,%typemask,%tobj);
%obj          = getword(%obj,0);
return %obj;
}

function MatchPlayers()
{
if (!$PatchApplied)
{
error("Error: Requires the Ghost Patch to be applied.");
return;
}

%count = CommandTargetSet.getcount();
%clcount = PlayerListGroup.getcount();

for (%i = 0; %i < %count; %i++)
{
%obj = CommandTargetSet.getobject(%i);
%target = %obj.gettarget();

for (%j = 0; %j < %clcount; %j++)
{
%cl = PlayerListGroup.getobject(%j);

if (%cl.targetid == %target)
{
%obj.client = %cl;
%cl.player = %obj;
}
}
}

}

function plnametocid(%name)
{
    %count = PlayerListGroup.getCount(); //counts total clients
    for(%i = 0; %i < %count; %i++)  //loops till all clients are accounted for
        {
        %obj = PlayerListGroup.getObject(%i);  //gets the clientid based on the ordering hes in on the list
        %nametest = %obj.name;  //pointless step but i didnt feel like removing it....
        %nametest = strlwr(%nametest);  //make name lowercase
        %name = strlwr(%name);  //same as above, for the other name
        if(strstr(%nametest,%name) != -1)  //is all of name test used in name
            return %obj;  //if so return the clientid and stop the function
    }
    return 0;  //if none fits return 0 and end function
}

function SimObject::getRotation(%obj)
{
     getRotation(%obj);
}

function getRotation(%obj)
{
    return getWords(%obj.getTransform(), 3, 6);
}

//<--Metallic Hashes Begin-->\\

//Electronics cannot save
$Saver::DataBlockName["2012656601","Metallic"] = "IGNORE"; //Inventory Station

//Deployed Spine
$Saver::DataBlockName["144964343","Metallic"] = "DeployedSpine";
//Medium Spine
$Saver::DataBlockName["-189383052","Metallic"] = "DeployedMSpine";
//Wood Spine
$Saver::DataBlockName["517055503","Metallic"] = "DeployedWoodSpine";
//BackPack
$Saver::DataBlockName["-1386081207","Metallic"] = "DeployedCrate0";
//Small Containment
$Saver::DataBlockName["-896399297","Metallic"] = "DeployedCrate1";
//Large ContainMent
$Saver::DataBlockName["-1143999356","Metallic"] = "DeployedCrate2";
//Compressor
$Saver::DataBlockName["2020443910","Metallic"] = "DeployedCrate3";
//Tubes
$Saver::DataBlockName["-","Metallic"] = "DeployedCrate4";
//Quantum Battery
$Saver::DataBlockName["-","Metallic"] = "DeployedCrate5";
//Proton Accelerator
$Saver::DataBlockName["-","Metallic"] = "DeployedCrate6";
//Cargo Crate
$Saver::DataBlockName["-","Metallic"] = "DeployedCrate7";
//Magnetic Cooler
$Saver::DataBlockName["-","Metallic"] = "DeployedCrate8";
//Recycle Unit
$Saver::DataBlockName["-","Metallic"] = "DeployedCrate9";
//Fuel Canister
$Saver::DataBlockName["-","Metallic"] = "DeployedCrate10";
//Wooden T2 Box
$Saver::DataBlockName["-","Metallic"] = "DeployedCrate11";
//Plasma Router
$Saver::DataBlockName["-","Metallic"] = "DeployedCrate12";
//Blast Floor
$Saver::DataBlockName["-471679053","Metallic"] = "DeployedFloor";
//Blast Wall
$Saver::DataBlockName["-575903304","Metallic"] = "DeployedWall";
//Metallic Door
$Saver::DataBlockName["-189383052","Metallic"] = "DeployedDoor";

$Saver::Mod["Metallic"] = true;

//<--Configuration Variables Begin-->\\
$Saver::QuietSave = false;
$Saver::DeleteTEMP = true;


text:
package action;

import entity.Book;
import entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import service.MailService;
import service.UserHttpService;
import service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by reeco_000 on 2015/4/18.
 */

@Controller
@RequestMapping("/user")
@EnableWebMvc
public class UserAction {

    private MailService mailService;

    private UserHttpService userHttpService;

    private UserService userService;

    private List<Book> books = new ArrayList<Book>();

    //private User user = new User();

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setUserHttpService(UserHttpService userHttpService) {
        this.userHttpService = userHttpService;
    }

    @Autowired
    public void setMailService(MailService mailService) {
        this.mailService = mailService;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/login")
    public String login(HttpServletRequest request, RedirectAttributes redirectAttributes) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        request.getSession().setAttribute("sUser", user);
        Boolean check = userHttpService.login(username, password);
        if (check) {
            if (!books.isEmpty())
                books.clear();
            books = userHttpService.getBooks(username, password);
            setBooks(books);
            request.getSession().setAttribute("books", books);
            return "redirect:/user/book";
        } else {
            System.out.println("密码错误");
            redirectAttributes.addFlashAttribute("message", "账号或者密码错误,请检查");
            return "redirect:/";
        }

    }

    @RequestMapping(method = RequestMethod.POST, value = "/add")
    public String add(HttpServletRequest request, RedirectAttributes redirectAttributes) {
        String pattern = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
        String email = request.getParameter("email");
        Boolean emailCheck = Pattern.compile(pattern).matcher(email).matches();
        if(!emailCheck){
            redirectAttributes.addFlashAttribute("message", "请输入正确的邮箱格式");
            return "redirect:/user/book";
        }
        User user = (User) request.getSession().getAttribute("sUser");
        user.setEmail(email);
        user.setFlag(1);
        user.setTest_email(0);
        Boolean temp = userService.isEmail(email);
        if (temp) {
            redirectAttributes.addFlashAttribute("message", "邮箱已被注册");
            return "redirect:/user/book";
        } else {

            temp = userService.isExist(user.getUsername());
            if (temp) {
                redirectAttributes.addFlashAttribute("already", "此用户名已经注册");
                return "redirect:/user/book";
            }
            userService.addUser(user, books);
            mailService.sendTestMailByGun(books, email);
            redirectAttributes.addFlashAttribute("succ", "注册成功,不出意外您将收到一封测试邮件,若是QQ用户,请检查您的垃圾箱");

            return "redirect:/user/book";
        }
    }

    public void setBooks(List<Book> books) {
        this.books = books;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/book")
    public String bookList() {
        return "book";
    }
}


text:
class Fee::BasicFeePresenter < Fee::BaseFeePresenter
  def should_be_displayed?
    return true unless claim.agfs_reform?
    return true unless FEE_CODES_RESTRICTED_DISPLAY.include?(code)
    OFFENCE_CATEGORIES_WITHOUT_RESTRICTED_DISPLAY.include?(offence_category_number)
  end

  def display_extra_fees?
    return false if claim.discontinuance?
    should_be_displayed?
  end

  def display_amount?
    # TODO: this is not really ideal, but right now I
    # can't see any other way to achieve this specific
    # requirement :/
    return true unless claim.agfs_reform?
    return false if FEE_CODES_WITHOUT_AMOUNT.include?(code)
    true
  end

  def display_help_text?
    return false unless claim.agfs_reform?
    OFFENCE_CATEGORIES_WITHOUT_RESTRICTED_DISPLAY.include?(offence_category_number)
  end

  def activate_js_block?
    !display_help_text?
  end

  def fee_calc_class
    { BAPPE: 'js-fee-calculator-ppe', BANPW: 'js-fee-calculator-pw' }[unique_code.to_sym]
  end

  private

  FEE_CODES_WITH_PROMPT_TEXT = %w[BAF SAF PPE].freeze
  FEE_CODES_WITHOUT_AMOUNT = %w[PPE].freeze
  FEE_CODES_RESTRICTED_DISPLAY = %w[PPE].freeze
  OFFENCE_CATEGORIES_WITHOUT_RESTRICTED_DISPLAY = [6, 9].freeze

  def code
    fee.fee_type.code
  end

  def unique_code
    fee.fee_type.unique_code
  end

  def claim
    fee.claim
  end

  def offence_category_number
    claim&.offence&.offence_category&.number
  end
end


text:
'use strict';

var graphite = require('./graphite');

function GraphiteAdapter(config) {
    graphite.init(config);

    return {
        name: 'graphite',
        read: require('./read'),
        write: require('./write')
    };
}

module.exports = GraphiteAdapter;


text:
package gov.va.escreening.service;

import gov.va.escreening.dto.DropDownObject;
import gov.va.escreening.entity.DashboardAlert;
import gov.va.escreening.entity.DashboardAlertType;
import gov.va.escreening.repository.DashboardAlertRepository;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class DashboardAlertServiceImpl implements DashboardAlertService
{

	@Autowired
	DashboardAlertRepository alertRepo;

	@Autowired
	EventService eventService;

	@Override
	public List<DropDownObject> getAll() {
		List<DashboardAlert> all = alertRepo.findAll();

		List<DropDownObject> result = new ArrayList<>(all.size());
		for(DashboardAlert a : all)
		{
			result.add(new DropDownObject(a.getDashboardAlertId().toString(),
					a.getName()));
		}
		return result;
	}

	@Override
	public void updateAlertType(Integer id, String name) {
		if(id == null)
		{
			DashboardAlert a = new DashboardAlert();
			a.setName(name);
			a.setMessage(name);
			a.setDashboardAlertType(new DashboardAlertType(1));
			a.setDateCreated(Calendar.getInstance().getTime());
			alertRepo.create(a);
			eventService.updateDashboardAlertEvent(a);
		}
		else
		{
			DashboardAlert a = alertRepo.findOne(id);
			if(a != null)
			{
				if(a.getName() == null || !a.getName().equals(name))
				{
					a.setName(name);
					a.setMessage(name);
					alertRepo.update(a);
					eventService.updateDashboardAlertEvent(a);
				}
			}
			else
			{
				throw new IllegalArgumentException("Dashboard Alert does not exist");
			}
		}

	}

	@Override
	public void deleteAlertType(int id) {
		alertRepo.deleteById(id);
	}

	@Override
	public DropDownObject getAlertType(int id) {
		DashboardAlert a = alertRepo.findOne(id);
		return new DropDownObject(a.getDashboardAlertId().toString(), a.getName());
	}

}


text:
/**
 * PeticionController.js
 *
 * @description ::
 * @docs        :: http://sailsjs.org/#!documentation/controllers
 */

var _ = require('lodash');

module.exports = {
	getAll: function(req, res) {
		Peticion.find().populateAll().exec(function(err,models){
			res.json(models)
		});
	},

	getOne: function(req, res) {
		Peticion.findOne({id:req.param('id')}).populate('respuestas').exec(function(err, model) {
			Peticion.subscribe(req.socket, model);
			res.json(model);
		})
	},

	create: function(req, res) {
		var peticion = {
			to: req.body.to,
			content: req.body.content,
			comparativo: req.body.comparativo,
		};

		Peticion.create(peticion).exec(function(err, savedPeticion){
			Comparativo.findOne(peticion.comparativo).exec(function(err, comparativo){

				if(err) return res.serverError(err)
				if(!comparativo) return res.notFound()

				var eventLog  = {
					obra: comparativo.obra,
					comparativo: comparativo.id,
					comparativoName: comparativo.title,
					service: 'peticion',
					action: 'create',
					objectName: peticion.to.name,
					objectId: savedPeticion.id,
					subjectName: req.user.first_name + ' '+ req.user.last_name,
					subjectId: req.user.id
				}
				EventLogService.log(eventLog);
			})
			if(req.body.sendmail){
				Mail.sendPeticion(savedPeticion.id, function(err, sended){
				})
			}
			return res.json(savedPeticion);

		});
	},

	destroy: function (req, res) {
		var id = req.param('id');
		if (!id) {
			return res.badRequest('No id provided.');
		}

		// Otherwise, find and destroy the model in question
		Peticion.findOne(id).exec(function(err, model) {
			if (err) {
				return res.serverError(err);
			}
			if (!model) {
				return res.notFound();
			}

			Peticion.destroy(id, function(err) {
				if (err) {
					return res.serverError(err);
				}

				Peticion.publishDestroy(model.id);
				return res.json(model);
			});
		});
	},

	send: function(req, res) {
		Mail.sendPeticion(req.body.id, function(err, sended){

		})
	}

};


text:
How to compile L-SMASH and L-SMASH Works with Visual Studio 2013
------------------------------------------

###Requirements:

-   Microsoft Visual Studio 2013 (Express was not tested, but should work)
-   [MSYS2](http://sourceforge.net/projects/msys2/files/Base/)

###Preparation:

-   Install Visual Studio 2013
-   Extract **MSYS2** somewhere (**C:\msys2** will refer to that location)
-   Go to **C:\msys2\usr\bin** and rename **link.exe** to **link.exe.bak** (this is important, otherwise it *will* conflict with MSVC's **link.exe**)
-   Create a "work directory" (**C:\work** will refer to that location)
-   Go to **C:\msys2** and double click **msys2_shell.bat**, wait for it to configure itself, close and open it again
-   Install the necessary packages by typing:
    -   For the x86 build:
        ```
pacman -Sy
pacman -S --needed make autoconf autogen diffutils git p7zip patch perl python2 ruby subversion yasm wget mingw-w64-i686-gcc mingw-w64-i686-gettext mingw-w64-i686-crt-git mingw-w64-i686-libtool mingw-w64-i686-libjpeg-turbo mingw-w64-i686-libpng mingw-w64-i686-libxml2 mingw-w64-i686-tools-git mingw-w64-i686-glib2 mingw-w64-i686-pkgconf mingw-w64-i686-cmake-git
        ```

    -   For the x64 build **(Optional)**:
        ```
pacman -Sy
pacman -S --needed mingw-w64-x86_64-gcc mingw-w64-x86_64-gettext mingw-w64-x86_64-crt-git mingw-w64-x86_64-libtool mingw-w64-x86_64-libjpeg-turbo mingw-w64-x86_64-libpng mingw-w64-x86_64-libxml2 mingw-w64-x86_64-tools-git mingw-w64-x86_64-glib2 mingw-w64-x86_64-pkgconf mingw-w64-x86_64-cmake-git
        ```

-   Type: ```cd "C:\work"```
-   For **ffmpeg** you have a few options:
    -  Check out the latest code by typing: ```git clone git://source.ffmpeg.org/ffmpeg.git```
    -  Download the [latest code](https://www.ffmpeg.org/releases/ffmpeg-snapshot.tar.bz2)
    -  Download the [latest stable version](https://www.ffmpeg.org/download.html) (rename the folder to **ffmpeg** after extracting)

-   Get the latest **L-SMASH** code by typing: ```git clone https://github.com/l-smash/l-smash.git```

-   Get the latest **L-SMASH Works** code by typing: ```git clone https://github.com/VFR-maniac/L-SMASH-Works.git```

-   Close the **MSYS2** prompt

###Building L-SMASH:

1.  Building for x86:
    -   Go to **C:\msys2** and double click **mingw32_shell.bat**
    -   Type ```cd "c:\work\ffmpeg"```
    -   Type ```mkdir build32 && cd build32```
    -   Type ```../configure --prefix=/mingw32/local --extra-ldflags='-static' --target-os=mingw32 --arch=i686 --enable-avresample --disable-programs --disable-doc --disable-swresample --disable-encoders --disable-hwaccels --disable-filters --disable-debug```
    -   Type ```make && make install```
    -   Type ```cd "C:\work\l-smash"```
    -   Type ```mkdir build32 && cd build32```
    -   Type ```../configure --prefix=/mingw32/local --extra-ldflags='-static'```
    -   Type ```make && make install```
    -   Close the **MINGW32** prompt

2.  Building for x64 **(Optional)**:
    -   Go to **C:\msys2** and double click **mingw64_shell.bat**
    -   Type ```cd "c:\work\ffmpeg"```
    -   Type ```mkdir build64 && cd build64```
    -   Type ```../configure --prefix=/mingw64/local  --extra-ldflags='-static' --target-os=mingw32 --arch=x86_64 --enable-avresample --disable-programs --disable-doc --disable-swresample --disable-encoders --disable-hwaccels --disable-filters --disable-debug```
    -   Type ```make && make install```
    -   Type ```cd "C:\work\l-smash"```
    -   Type ```mkdir build64 && cd build64```
    -   Type ```../configure --prefix=/mingw64/local --extra-ldflags='-static'```
    -   Type ```make && make install```
    -   Close the **MINGW64** prompt

###Building L-SMASH Works (AviUtl & VapourSynth plugins):

1.  Building for x86:
    -   Go to **C:\msys2** and double click **mingw32_shell.bat**
    -   Type ```cd "c:\work\L-SMASH-Works\AviUtl"```
    -   Type ```mkdir build32```
    -   Type ```PKG_CONFIG_PATH=/mingw32/local/lib/pkgconfig ./configure --prefix=/mingw32/local --extra-ldflags='-static'```
    -   Type ```make```
    -   Type ```mv lwcolor.auc build32 && mv lwmuxer.auf build32 && mv lwdumper.auf build32 && mv lwinput.aui build32```
    -   Type ```make distclean```
    -   Type ```cd "c:\work\L-SMASH-Works\VapourSynth"```
    -   Type ```mkdir build32```
    -   Type ```PKG_CONFIG_PATH=/mingw32/local/lib/pkgconfig ./configure --prefix=/mingw32/local --extra-ldflags='-static'```
    -   Type ```make```
    -   Type ```mv vslsmashsource.dll build32```
    -   Type ```make distclean```
    -   Close the **MINGW32** prompt

2.  Building for x64 **(Optional)**:
    -   Go to **C:\msys2** and double click **mingw64_shell.bat**
    -   Type ```cd "c:\work\L-SMASH-Works\VapourSynth"```
    -   Type ```mkdir build64```
    -   Type ```PKG_CONFIG_PATH=/mingw64/local/lib/pkgconfig ./configure --prefix=/mingw64/local --extra-ldflags='-static'```
    -   Type ```make```
    -   Type ```mv vslsmashsource.dll build64```
    -   Type ```make distclean```
    -   Close the **MINGW64** prompt

###Building L-SMASH (for AviSynth plugin):

Unfortunately, I don't know how to solve some linking errors regarding the **ffmpeg** libraries built by mingw (or if they *can* be solved), so I'm taking the route that works, and compiling everything again.

1.  Building for x86:
    -   Open **Visual Studio 2013 -> Visual Studio Tools -> VS2013 x86 Native Tools Command Prompt**
    -   Type ```C:\msys2\mingw32_shell.bat```
    -   Type ```cd "c:\work\ffmpeg"```
    -   Type ```mkdir build32-msvc && cd build32-msvc```
    -   Type ```../configure --toolchain=msvc --prefix=/mingw32/local-msvc --enable-avresample --disable-programs --disable-doc --disable-swresample --disable-encoders --disable-hwaccels --disable-filters --disable-debug```
    -   Type ```make && make install```
    -   Type ```cd "C:\work\l-smash"```
    -   Type ```mkdir build32-msvc && cd build32-msvc```
    -   Type ```../configure --prefix=/mingw32/local-msvc --extra-ldflags='-static'```
    -   Type ```make && make install```
    -   Close the **MINGW32** prompt

2.  Building for x64 **(Optional)**:
    -   Open **Visual Studio 2013 -> Visual Studio Tools -> VS2013 x64 Native Tools Command Prompt**
    -   Type ```C:\msys2\mingw64_shell.bat```
    -   Type ```cd "c:\work\ffmpeg"```
    -   Type ```mkdir build64-msvc && cd build64-msvc```
    -   Type ```../configure --toolchain=msvc --prefix=/mingw64/local-msvc --enable-avresample --disable-programs --disable-doc --disable-swresample --disable-encoders --disable-hwaccels --disable-filters --disable-debug```
    -   Type ```make && make install```
    -   Type ```cd "C:\work\l-smash"```
    -   Type ```mkdir build64-msvc && cd build64-msvc```
    -   Type ```../configure --prefix=/mingw64/local-msvc --extra-ldflags='-static'```
    -   Type ```make && make install```
    -   Close the **MINGW64** prompt

###Building L-SMASH Works (AviSynth plugin):

-   Go to **C:\work\L-SMASH-Works\AviSynth** and open **LSMASHSourceVCX.sln** in Visual Studio
-   Building for x86:
    -   Change the configuration from **Debug** to **Release** and **Win32**
    -   Right-click the **LSMASHSource** and go to **Properties**
    -   Go to **VC++ Directories** and add the following to:
        -   Include Directories:

            ```
C:\msys2\mingw32\local-msvc\include
C:\msys2\mingw32\include
            ```

        -   Library Directories (**4.9.1** is the GCC version, you have to check which version you have):

            ```
C:\msys2\mingw32\local-msvc\lib
C:\msys2\mingw32\i686-w64-mingw32\lib
C:\msys2\mingw32\lib
C:\msys2\mingw32\lib\gcc\i686-w64-mingw32\4.9.1
            ```

-   Building for x64 **(Optional)**:
    -   Change the configuration from **Debug** to **Release** and **x64**
    -   Right-click the **LSMASHSource** and go to **Properties**
    -   Go to **VC++ Directories** and add the following to:
        -   Include Directories:

            ```
C:\msys2\mingw64\local-msvc\include
C:\msys2\mingw64\include
            ```

        -   Library Directories (**4.9.1** is the GCC version, you have to check which version you have):

            ```
C:\msys2\mingw64\local-msvc\lib
C:\msys2\mingw64\x86_64-w64-mingw32\lib
C:\msys2\mingw64\lib
C:\msys2\mingw64\lib\gcc\x86_64-w64-mingw32\4.9.1
            ```

-   Steps for **both** x86 and x64 **Release** configurations:
    -   Right-click the **LSMASHSource** and go to **Properties**
    -   Go to **C++ -> General** and change **Debug Information Format** to **None**
    -   Go to **Linker -> Input** and add the following to to **Additional Dependencies**:

        ```
liblzma.a
libiconv.a
ws2_32.lib
        ```

    -   Go to **Linker -> Input** and add ```libcmt.lib``` to **Ignore Specific Default Libraries**
    -   Go to **Linker -> Debugging** and change **Generate Debug Info** to **No**
    -   Go to **Linker -> Optimization** and change **References** to **No (/OPT:NOREF)**

-   **Compile!**

###Creating Packages:

-   Go to **C:\msys2** and double click **msys2_shell.bat**
-   Type: ```cd "C:\work"```
-   Now download the bash script to create packages in one of two ways:
    -  Type: ```wget https://raw.githubusercontent.com/BrunoReX/build-scripts/master/L-SMASH/create_packages.sh```
    -  Or download download **create_packages.sh** manually and save it to **C:\work**
-   You may need to edit **create_packages.sh** to match your setup
-   Now type: ```./create_packages.sh``` and wait for it to finish
-   Go to **C:\work** and copy your newly created packages

###Sources:
-   [qyot27's post @ Doom9](http://forum.doom9.org/showthread.php?p=1620870#post1620870)
-   [ffmpeg documentation](https://www.ffmpeg.org/platform.html#Microsoft-Visual-C_002b_002b-or-Intel-C_002b_002b-Compiler-for-Windows)
-   [nak5124's build environment](https://github.com/nak5124/build_env)


text:
package com.hwxiasn.dubbo.facade;

public interface TestService {
	String echo(String msg);
	String time();
}


text:
module Pronto
  module LabelmanRules
    class Rule
      def initialize(patches)
        @patches = patches
      end

      def self.label(name)
        define_method('label_name') { name }
      end

      def apply
        Pronto::Label.new(label_name) if applicable?
      end

      def applicable?
        # implement me!
        false
      end
    end
  end
end


text:
package validation

import (
	"context"
	"testing"

	"go.chromium.org/luci/config/validation"

	. "github.com/smartystreets/goconvey/convey"
)

func TestValidationRules(t *testing.T) {
	t.Parallel()

	Convey("Validation Rules", t, func() {
		r := validation.NewRuleSet()
		r.Vars.Register("appid", func(context.Context) (string, error) { return "luci-change-verifier", nil })

		addRules(r)

		patterns, err := r.ConfigPatterns(context.Background())
		So(err, ShouldBeNil)
		So(len(patterns), ShouldEqual, 3)
		Convey("project-scope cq.cfg", func() {
			So(patterns[0].ConfigSet.Match("projects/xyz"), ShouldBeTrue)
			So(patterns[0].ConfigSet.Match("projects/xyz/refs/heads/master"), ShouldBeFalse)
			So(patterns[0].Path.Match("commit-queue.cfg"), ShouldBeTrue)
		})
		Convey("service-scope migration-settings.cfg", func() {
			So(patterns[1].ConfigSet.Match("services/commit-queue"), ShouldBeTrue)
			So(patterns[1].ConfigSet.Match("projects/xyz/refs/heads/master"), ShouldBeFalse)
			So(patterns[1].Path.Match("migration-settings.cfg"), ShouldBeTrue)
		})
		Convey("service-scope listener-settings.cfg", func() {
			So(patterns[2].ConfigSet.Match("services/luci-change-verifier"), ShouldBeTrue)
			So(patterns[2].ConfigSet.Match("projects/xyz/refs/heads/master"), ShouldBeFalse)
			So(patterns[2].Path.Match("listener-settings.cfg"), ShouldBeTrue)
		})
	})
}

func mustHaveOnlySeverity(err error, severity validation.Severity) error {
	So(err, ShouldNotBeNil)
	for _, e := range err.(*validation.Error).Errors {
		s, ok := validation.SeverityTag.In(e)
		So(ok, ShouldBeTrue)
		So(s, ShouldEqual, severity)
	}
	return err
}

func mustWarn(err error) error {
	return mustHaveOnlySeverity(err, validation.Warning)
}

func mustError(err error) error {
	return mustHaveOnlySeverity(err, validation.Blocking)
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--

    Copyright 2005-2015 The Kuali Foundation

    Licensed under the Educational Community License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.opensource.org/licenses/ecl2.php

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<spring:beans xmlns:spring="http://www.springframework.org/schema/beans" xmlns="http://www.kuali.org/krad/schema"
              xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.kuali.org/krad/schema http://www.kuali.org/krad/schema.xsd">
  <formView-bean entryPageId="ConfigurationTestView-ProgressiveRender-Page"
                 formClass="edu.sampleu.demo.kitchensink.UifComponentsTestForm" growlMessagingEnabled="true"
                 headertext="Configuration Test View" id="ConfigurationTestView" namespaceCode="KR-NS"
                 viewHelperServiceClass="edu.sampleu.demo.kitchensink.UIfComponentsViewHelperServiceImpl">
    <navigation>
      <spring:ref bean="ConfigurationTestView-Menu"/>
    </navigation>
    <items>
      <spring:ref bean="ConfigurationTestView-ProgressiveRender-Page"/>
      <spring:ref bean="ConfigurationTestView-Help-Page"/>
      <spring:ref bean="ConfigurationTestView-Quickfinder-Page"/>
    </items>
    <theme>
      <kradTheme-bean/>
    </theme>
    <additionalCssFiles merge="true">
      <spring:value>css/sampleapp.css</spring:value>
    </additionalCssFiles>
    <help>
      <help-bean externalHelpUrl="http://www.kuali.org" tooltipHelpContent="View help"/>
    </help>
  </formView-bean>
  <formView-bean id="ConfigurationTestView_KNS" parent="ConfigurationTestView">
    <theme>
      <classicKnsTheme-bean/>
    </theme>
  </formView-bean>
  <tabNavigationGroup-bean id="ConfigurationTestView-Menu">
    <items>
      <navigationActionLink-bean actionLabel="Page 1" navigateToPageId="ConfigurationTestView-ProgressiveRender-Page"/>
      <navigationActionLink-bean actionLabel="Help" navigateToPageId="ConfigurationTestView-Help-Page"/>
      <navigationActionLink-bean actionLabel="Lookup Widgets"
                                 navigateToPageId="ConfigurationTestView-Quickfinder-Page"/>
    </items>
  </tabNavigationGroup-bean>
</spring:beans>


text:
package com.biglakesystems.scamp.impl.eval;

import com.biglakesystems.scamp.impl.PlatformHelper;
import com.biglakesystems.scamp.spi.module.ComponentLoader;
import com.biglakesystems.scamp.spi.module.Module;
import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;

import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;

public class TestJavaServicesLoader
{
    private final PlatformHelper m_mockPlatformHelper;

    /**
     * Construct a {@link TestJavaServicesLoader} instance.
     */
    public TestJavaServicesLoader()
    {
        super();
        m_mockPlatformHelper = createMock(PlatformHelper.class);
    }

    @Before
    public void resetCommonMocks()
    {
        reset(m_mockPlatformHelper);
    }

    /**
     * Test the implementation of {@link ComponentLoader#load(Class)}.
     */
    @Test
    public void testLoad()
    {
        final ClassLoader mockLoader = createMock(ClassLoader.class);
        final Module mockModule1 = createMock(Module.class);
        final Module mockModule2 = createMock(Module.class);
        final Iterable<Module> modules = Arrays.asList(mockModule1, mockModule2);

        /* Should delegate to the platform helper. */
        expect(m_mockPlatformHelper.ServiceLoader_load(eq(Module.class), same(mockLoader))).andReturn(modules)
                .atLeastOnce();

        /* Run the test and verify expectations. */
        replayCommonMocks();
        replay(mockLoader, mockModule1, mockModule2);
        final ComponentLoader instance = new JavaServicesLoader(mockLoader, m_mockPlatformHelper);
        assertEquals(modules, instance.load(Module.class));
        verifyCommonMocks();
        verify(mockLoader, mockModule1, mockModule2);
    }

    /**
     * Test the implementation of {@link ComponentLoader#load(Class)} when no modules are registered.
     */
    @Test
    public void testLoad_noModules()
    {
        final ClassLoader mockLoader = createMock(ClassLoader.class);
        final Iterable<Module> modules = Collections.emptyList();

        /* Should delegate to the platform helper. */
        expect(m_mockPlatformHelper.ServiceLoader_load(eq(Module.class), same(mockLoader))).andReturn(modules)
                .atLeastOnce();

        /* Run the test and verify expectations. */
        replayCommonMocks();
        replay(mockLoader);
        final ComponentLoader instance = new JavaServicesLoader(mockLoader, m_mockPlatformHelper);
        assertTrue(instance.load(Module.class).isEmpty());
        verifyCommonMocks();
        verify(mockLoader);
    }

    private void replayCommonMocks()
    {
        replay(m_mockPlatformHelper);
    }

    private void verifyCommonMocks()
    {
        verify(m_mockPlatformHelper);
    }
}


text:
/// <reference no-default-lib="true"/>

interface Generator extends Iterator<any> { }

interface GeneratorFunction {
    /**
     * Creates a new Generator object.
     * @param args A list of arguments the function accepts.
     */
    new (...args: any[]): Generator;
    /**
     * Creates a new Generator object.
     * @param args A list of arguments the function accepts.
     */
    (...args: any[]): Generator;
    /**
     * The length of the arguments.
     */
    readonly length: number;
    /**
      * Returns the name of the function.
      */
    readonly name: string;
    /**
      * A reference to the prototype.
      */
    readonly prototype: Generator;
}

interface GeneratorFunctionConstructor {
    /**
      * Creates a new Generator function.
      * @param args A list of arguments the function accepts.
      */
    new (...args: string[]): GeneratorFunction;
    /**
      * Creates a new Generator function.
      * @param args A list of arguments the function accepts.
      */
    (...args: string[]): GeneratorFunction;
    /**
     * The length of the arguments.
     */
    readonly length: number;
    /**
      * Returns the name of the function.
      */
    readonly name: string;
    /**
      * A reference to the prototype.
      */
    readonly prototype: GeneratorFunction;
}
declare var GeneratorFunction: GeneratorFunctionConstructor;


text:
<?php

namespace Blogger\BlogBundle\DataFixtures\ORM;

use Blogger\BlogBundle\Entity\Category;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

class CategoryFixtures extends AbstractFixture implements OrderedFixtureInterface{

    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {

        $category1 = new Category();
        $category1->setName("Popular");
        $manager->persist($category1);

        $category2 = new Category();
        $category2->setName("Info");
        $manager->persist($category2);

        $manager->flush();

        $this->addReference('category-1', $category1);
        $this->addReference('category-2', $category2);

    }

    /**
     * Get the order of this fixture
     *
     * @return integer
     */
    public function getOrder()
    {
        return 1;
    }

}


text:
<?php
	require('helper.php'); // checks https and session status
?>

        <?php output_dependencies() ?>

Günter Hans Reporting Application

Logout?

Report Selection

Report Type:

                                        <select id="reportType" onchange="retrieveReportAndPopulateCradle()" class="selectpicker" data-width="100%">
                                            <option value="totalSales">Total Sales</option>
                                            <option value="discountsGiven">Discounts Given</option>
                                            <option value="numberOfTransactions">Transaction Count</option>
                                            <option value="salesPerTransaction">Sales Per Transaction</option>
                                            <option value="tipsPerSaleByEmployee">Tips Per Sale</option>
                                            <option value="aveTipPercentByEmployee">Average Tip Percent</option>
                                        </select>

Date Range:

                                            <input id="dateRange" type="text" class="form-control daterangepicker" value="01/01/2012 - 11/24/2015" />

Start Time:

                                            <input id="startTime" type="time" class="form-control" value="00:00">

End Time:

                                            <input id="endTime" type="time" data-placement="right" class="form-control" value="23:59">

Transaction Day:

<input type="checkbox" id="1" checked>Sun</input>

<input type="checkbox" id="2" checked>Mon</input>

<input type="checkbox" id="3" checked>Tue</input>

<input type="checkbox" id="4" checked>Wed</input>

<input type="checkbox" id="5" checked>Thu</input>

<input type="checkbox" id="6" checked>Fri</input>

<input type="checkbox" id="7" checked>Sat</input>

                                        <button id="refresh" type="button" class="button form-control btn-primary">
                                             Generate Graph
                                        </button>

Report Header

                                <canvas id="chart"></canvas>

        <?php output_plugin_activations(); ?>


text: GUI for downloading FCS files from a ReFlow server


text:
import types
import inspect
import re
import traceback

from jsonrpclib import config

iter_types = [
    types.DictType,
    types.ListType,
    types.TupleType
]

string_types = [
    types.StringType,
    types.UnicodeType
]

numeric_types = [
    types.IntType,
    types.LongType,
    types.FloatType
]

value_types = [
    types.BooleanType,
    types.NoneType
]

supported_types = iter_types+string_types+numeric_types+value_types
invalid_module_chars = r'[^a-zA-Z0-9\_\.]'

class TranslationError(Exception):
    pass

def dump(obj, serialize_method=None, ignore_attribute=None, ignore=[]):
    if not serialize_method:
        serialize_method = config.serialize_method
    if not ignore_attribute:
        ignore_attribute = config.ignore_attribute
    obj_type = type(obj)
    # Parse / return default "types"...
    if obj_type in numeric_types+string_types+value_types:
        return obj
    if obj_type in iter_types:
        if obj_type in (types.ListType, types.TupleType):
            new_obj = []
            for item in obj:
                new_obj.append(dump(item, serialize_method,
                                     ignore_attribute, ignore))
            if obj_type is types.TupleType:
                new_obj = tuple(new_obj)
            return new_obj
        # It's a dict...
        else:
            new_obj = {}
            for key, value in obj.iteritems():
                new_obj[key] = dump(value, serialize_method,
                                     ignore_attribute, ignore)
            return new_obj
    # It's not a standard type, so it needs __jsonclass__
    module_name = inspect.getmodule(obj).__name__
    class_name = obj.__class__.__name__
    json_class = class_name
    if module_name not in ['', '__main__']:
        json_class = '%s.%s' % (module_name, json_class)
    return_obj = {"__jsonclass__":[json_class,]}
    # If a serialization method is defined..
    if serialize_method in dir(obj):
        # Params can be a dict (keyword) or list (positional)
        # Attrs MUST be a dict.
        serialize = getattr(obj, serialize_method)
        params, attrs = serialize()
        return_obj['__jsonclass__'].append(params)
        return_obj.update(attrs)
        return return_obj
    # Otherwise, try to figure it out
    # Obviously, we can't assume to know anything about the
    # parameters passed to __init__
    return_obj['__jsonclass__'].append([])
    attrs = {}
    ignore_list = getattr(obj, ignore_attribute, [])+ignore
    for attr_name, attr_value in obj.__dict__.iteritems():
        if type(attr_value) in supported_types and \
                attr_name not in ignore_list and \
                attr_value not in ignore_list:
            attrs[attr_name] = dump(attr_value, serialize_method,
                                     ignore_attribute, ignore)
    return_obj.update(attrs)
    return return_obj

def load(obj):
    if type(obj) in string_types+numeric_types+value_types:
        return obj
    if type(obj) is types.ListType:
        return_list = []
        for entry in obj:
            return_list.append(load(entry))
        return return_list
    # Othewise, it's a dict type
    if '__jsonclass__' not in obj.keys():
        return_dict = {}
        for key, value in obj.iteritems():
            new_value = load(value)
            return_dict[key] = new_value
        return return_dict
    # It's a dict, and it's a __jsonclass__
    orig_module_name = obj['__jsonclass__'][0]
    params = obj['__jsonclass__'][1]
    if orig_module_name == '':
        raise TranslationError('Module name empty.')
    json_module_clean = re.sub(invalid_module_chars, '', orig_module_name)
    if json_module_clean != orig_module_name:
        raise TranslationError('Module name %s has invalid characters.' %
                               orig_module_name)
    json_module_parts = json_module_clean.split('.')
    json_class = None
    if len(json_module_parts) == 1:
        # Local class name -- probably means it won't work
        if json_module_parts[0] not in config.classes.keys():
            raise TranslationError('Unknown class or module %s.' %
                                   json_module_parts[0])
        json_class = config.classes[json_module_parts[0]]
    else:
        json_class_name = json_module_parts.pop()
        json_module_tree = '.'.join(json_module_parts)
        try:
            temp_module = __import__(json_module_tree)
        except ImportError:
            raise TranslationError('Could not import %s from module %s.' %
                                   (json_class_name, json_module_tree))
        json_class = getattr(temp_module, json_class_name)
    # Creating the object...
    new_obj = None
    if type(params) is types.ListType:
        new_obj = json_class(*params)
    elif type(params) is types.DictType:
        new_obj = json_class(**params)
    else:
        raise TranslationError('Constructor args must be a dict or list.')
    for key, value in obj.iteritems():
        if key == '__jsonclass__':
            continue
        setattr(new_obj, key, value)
    return new_obj


text:
<?xml version="1.0"?>
<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">

    <title ID="header">Paragraph</title>
    <para>
        Some text with an
        </para>
    <literallayout class="normal">Inline
line block.</literallayout>
    <para>
	More text
	</para>
    <literallayout class="normal">Another line block</literallayout>


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--L
  Copyright Oracle Inc

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details.
L-->

<cgMDR:Enumerated_Conceptual_Domain xmlns:cgMDR="http://www.cancergrid.org/schema/cgMDR" item_registration_authority_identifier="GB-CANCERGRID" data_identifier="D1E311233" version="0.1">
    <cgMDR:administered_item_administration_record>
        <cgMDR:administrative_note>Auto generated during protege import</cgMDR:administrative_note>
        <cgMDR:administrative_status>scheduledForReview</cgMDR:administrative_status>
        <cgMDR:change_description/>
        <cgMDR:creation_date>2006-08-08</cgMDR:creation_date>
        <cgMDR:effective_date>2006-08-08</cgMDR:effective_date>
        <cgMDR:explanatory_comment/>
        <cgMDR:last_change_date>2006-08-08</cgMDR:last_change_date>
        <cgMDR:origin/>
        <cgMDR:registration_status>Incomplete</cgMDR:registration_status>
        <cgMDR:unresolved_issue/>
    </cgMDR:administered_item_administration_record>
    <cgMDR:administered_by>GB-CANCERGRID-000005-1</cgMDR:administered_by>
    <cgMDR:registered_by>GB-CANCERGRID-000009-1</cgMDR:registered_by>
    <cgMDR:submitted_by>GB-CANCERGRID-000006-1</cgMDR:submitted_by>
    <cgMDR:described_by>KNCSJG1HE</cgMDR:described_by>
    <cgMDR:having>
        <cgMDR:context_identifier>GB-CANCERGRID-000001-1</cgMDR:context_identifier>
        <cgMDR:containing>
            <cgMDR:language_section_language_identifier>
                <cgMDR:country_identifier>GB</cgMDR:country_identifier>
                <cgMDR:language_identifier>eng</cgMDR:language_identifier>
            </cgMDR:language_section_language_identifier>
            <cgMDR:name>Relatedness of event to trial medication  enumerated conceptual domain</cgMDR:name>
            <cgMDR:definition_text>no definition suppied</cgMDR:definition_text>
            <cgMDR:preferred_designation>true</cgMDR:preferred_designation>
            <cgMDR:definition_source_reference/>
        </cgMDR:containing>
    </cgMDR:having>
    <cgMDR:Value_Meaning>
        <cgMDR:value_meaning_begin_date >2006-08-08</cgMDR:value_meaning_begin_date>
        <cgMDR:value_meaning_description >Unrelated</cgMDR:value_meaning_description>
        <cgMDR:value_meaning_identifier >D1E31181</cgMDR:value_meaning_identifier>
    </cgMDR:Value_Meaning>
    <cgMDR:Value_Meaning>
        <cgMDR:value_meaning_begin_date >2006-08-08</cgMDR:value_meaning_begin_date>
        <cgMDR:value_meaning_description >Unlikely</cgMDR:value_meaning_description>
        <cgMDR:value_meaning_identifier >D1E31187</cgMDR:value_meaning_identifier>
    </cgMDR:Value_Meaning>
    <cgMDR:Value_Meaning>
        <cgMDR:value_meaning_begin_date >2006-08-08</cgMDR:value_meaning_begin_date>
        <cgMDR:value_meaning_description >Probably</cgMDR:value_meaning_description>
        <cgMDR:value_meaning_identifier >D1E31193</cgMDR:value_meaning_identifier>
    </cgMDR:Value_Meaning>
    <cgMDR:Value_Meaning>
        <cgMDR:value_meaning_begin_date >2006-08-08</cgMDR:value_meaning_begin_date>
        <cgMDR:value_meaning_description >Possibly</cgMDR:value_meaning_description>
        <cgMDR:value_meaning_identifier >D1E31199</cgMDR:value_meaning_identifier>
    </cgMDR:Value_Meaning>
    <cgMDR:Value_Meaning>
        <cgMDR:value_meaning_begin_date >2006-08-08</cgMDR:value_meaning_begin_date>
        <cgMDR:value_meaning_description >Definitely</cgMDR:value_meaning_description>
        <cgMDR:value_meaning_identifier >D1E31205</cgMDR:value_meaning_identifier>
    </cgMDR:Value_Meaning>
</cgMDR:Enumerated_Conceptual_Domain>


text:
#ifndef MICROPY_INCLUDED_ESPRESSIF_COMMON_HAL_BLEIO_UUID_H
#define MICROPY_INCLUDED_ESPRESSIF_COMMON_HAL_BLEIO_UUID_H

#include "py/obj.h"

#include "host/ble_uuid.h"

typedef struct {
    mp_obj_base_t base;
    // Use the native way of storing UUID's:
    // - ble_uuid_t.uuid is a 16-bit uuid.
    // - ble_uuid_t.type is BLE_UUID_TYPE_BLE if it's a 16-bit Bluetooth SIG UUID.
    //   or is BLE_UUID_TYPE_VENDOR_BEGIN and higher, which indexes into a table of registered
    //   128-bit UUIDs.
    ble_uuid_any_t nimble_ble_uuid;
} bleio_uuid_obj_t;

void bleio_uuid_construct_from_nrf_ble_uuid(bleio_uuid_obj_t *self, ble_uuid_t *nrf_uuid);
void bleio_uuid_convert_to_nrf_ble_uuid(bleio_uuid_obj_t *self, ble_uuid_t *nrf_uuid);

#endif // MICROPY_INCLUDED_ESPRESSIF_COMMON_HAL_BLEIO_UUID_H


text:
'use strict';

/**
 * Wrapper around chrome.storage
 */
define([
	'wrappers/chrome'
], function(chrome) {

	/**
	 * Storage namespace wrapper
	 *
	 * @param name
	 * @constructor
	 */
	var Namespace = function(name) {

		this.get = function(cb) {
			chrome.storage.local.get(name, function(o) {
				if (chrome.runtime.lastError) {
					console.error('ChromeStorage.Namespace.getData : ' + chrome.runtime.lastError);
					return;
				}

				if (o && o.hasOwnProperty(name)) {
					cb(o[name]);
				} else {
					cb({});
				}
			});
		};

		this.set = function(data, cb) {
			var d = {};
			d[name] = data;

			var innerCb = function() {
				if (chrome.runtime.lastError) {
					console.error('ChromeStorage.Namespace.setData : ' + chrome.runtime.lastError);
					return;
				}

				if (typeof(cb) === 'function') {
					cb();
				}
			};

			chrome.storage.local.set(d, innerCb);
		};

	};

	/**
	 * Returns all data in the storage
	 */
	function get(cb) {
		chrome.storage.local.get(function(o) {
			if (chrome.runtime.lastError) {
				console.error('ChromeStorage.getData : ' + chrome.runtime.lastError);
				return;
			}

			cb(o);
		});
	}

	/**
	 * Sets data on global level.
	 * Be careful, this can overwrite any namespaced data
	 */
	function set(data, cb) {
		var innerCb = function() {
			if (chrome.runtime.lastError) {
				console.error('ChromeStorage.setData : ' + chrome.runtime.lastError);
				return;
			}

			if (typeof(cb) === 'function') {
				cb();
			}
		};

		chrome.storage.local.set(data, innerCb);
	}

	/**
	 * Logs all storage data to console
	 */
	function debugLog() {
		get(function(data) {
			var text = JSON.stringify(data);
			if (data !== null && Object.keys(data).length > 0 && data.LastFM) {
				if (data.LastFM.token) {
					text = text.replace(data.LastFM.token, 'xxxxx' + data.LastFM.token.substr(5));
				}
				if (data.LastFM.sessionID) {
					text = text.replace(data.LastFM.sessionID, 'xxxxx' + data.LastFM.sessionID.substr(5));
				}
			}
			console.info('chrome.storage.local = ' + text);
		});
	}

	return {
		/**
		 * Returns storage object for given namespace
		 *
		 * @return {Namespace}
		 */
		getNamespace: function(name) {
			return new Namespace(name);
		},

		debugLog: debugLog,
		get: get,
		set: set
	};

});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>lib/draft-js/moveSelectionBackward.js - itsa-react-editor</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="icon" href="../assets/favicon.ico">

            API Docs for: 0.0.1

APIs

Classes

Modules

                            <input type="search" id="api-filter" placeholder="Type to filter APIs">

Editor

component.jsx

                    Show:

                        <input type="checkbox" id="api-show-inherited" checked>
                        Inherited

                        <input type="checkbox" id="api-show-protected">
                        Protected

                        <input type="checkbox" id="api-show-private">
                        Private

                        <input type="checkbox" id="api-show-deprecated">
                        Deprecated

File: lib/draft-js/moveSelectionBackward.js

/**
 * Given a collapsed selection, move the focus `maxDistance` backward within
 * the selected block. If the selection will go beyond the start of the block,
 * move focus to the end of the previous block, but no further.
 *
 * This function is not Unicode-aware, so surrogate pairs will be treated
 * as having length 2.
 */
'use strict';

function moveSelectionBackward(editorState, maxDistance) {
  var selection = editorState.getSelection();
  var content = editorState.getCurrentContent();
  var key = selection.getStartKey();
  var offset = selection.getStartOffset();

  var focusKey = key;
  var focusOffset = 0;

  if (maxDistance > offset) {
    var keyBefore = content.getKeyBefore(key);
    if (keyBefore == null) {
      focusKey = key;
    } else {
      focusKey = keyBefore;
      var blockBefore = content.getBlockForKey(keyBefore);
      focusOffset = blockBefore.getText().length;
    }
  } else {
    focusOffset = offset - maxDistance;
  }

  return selection.merge({
    focusKey: focusKey,
    focusOffset: focusOffset,
    isBackward: true
  });
}

module.exports = moveSelectionBackward;


text:
<project name="air-imports">

  <import file="${buildsupport.dir}/import/base-imports.xml"/>

  <import file="${buildsupport.dir}/target/clean-build.xml"/>
  <import file="${buildsupport.dir}/target/clean-tests.xml"/>
  <import file="${buildsupport.dir}/target/compile-swc-air.xml"/>
  <import file="${buildsupport.dir}/target/build-air.xml"/>
  <import file="${buildsupport.dir}/target/test-air.xml"/>
  <import file="${buildsupport.dir}/target/package-air.xml"/>

</project>


text:
// Copyright (c) Lex Li. All rights reserved.
//
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace Microsoft.Web.Management.Client.Extensions
{
    public sealed class SiteUpdatedEventArgs : EventArgs
    {
        public SiteAction Action { get; }
        public string SiteName { get; }
    }
}


text:
Rails.application.routes.draw do
  devise_for :users
  resources :books

  get 'login', to: 'sessions#new', as: 'login'
  get 'logout', to: 'sessions#destroy', as: 'logout'

  resources :users
  resources :sessions

  resources :contacts

  root 'contacts#index'
end


text:
"""
test_roitimeseries
------------------

Tests for `vegindex.ndvitimeseries` module.
"""

import os

import numpy as np
from PIL import Image
from pkg_resources import Requirement
from pkg_resources import resource_filename

from vegindex import config
from vegindex import ndvitimeseries

SAMPLE_DATA_DIR = os.path.join(os.path.dirname(__file__), "sample_data")

config.archive_dir = SAMPLE_DATA_DIR

def test_reading_ndvits_file():
    """
    test reading in existing ndvits timeseries
    """

    sitename = "dukehw"
    roiname = "DB_1000"
    ndvi_file = "{}_{}_NDVI_roistats.csv".format(sitename, roiname)

    # set up path to roistats file
    ndvi_path = os.path.join(SAMPLE_DATA_DIR, sitename, "ROI", ndvi_file)

    ndvits = ndvitimeseries.NDVITimeSeries(site=sitename, ROIListID=roiname)

    ndvits.readCSV(ndvi_path)
    first_row = ndvits.rows[0]
    last_row = ndvits.rows[-1]

    np.testing.assert_equal(last_row["filename_rgb"], "dukehw_2020_07_15_215405.jpg")
    np.testing.assert_equal(last_row["filename_ir"], "dukehw_IR_2020_07_15_215405.jpg")
    np.testing.assert_equal(first_row["exposure_rgb"], 34)
    np.testing.assert_equal(first_row["exposure_ir"], 8)
    np.testing.assert_equal(len(ndvits.rows), 93946)