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="match_parent"
    android:background="@color/colorBgGary"
    android:orientation="vertical">
    <include layout="@layout/activity_base_title"/>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <ImageView
                android:id="@+id/iv_advisor_all_secret_detail_img"
                android:layout_width="match_parent"
                android:layout_height="@dimen/dm260"
                android:scaleType="fitXY"
                android:src="@drawable/advisor_detail"/>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/colorWhite"
                android:orientation="horizontal"
                android:paddingBottom="@dimen/dm024"
                android:paddingTop="@dimen/dm024">
                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/dm025"
                    android:orientation="vertical">
                    <TextView
                        android:id="@+id/tv_advisor_all_secret_detail_title"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="@dimen/dm002"
                        android:text=""
                        android:textColor="@color/titleText"
                        android:textSize="@dimen/dm028"/>
                    <TextView
                        android:id="@+id/tv_advisor_all_secret_detail_from"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="@dimen/dm010"
                        android:text="中方信富首席工作室"
                        android:textColor="@color/colorText"
                        android:textSize="@dimen/dm024"/>
                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="@dimen/dm010"
                        android:orientation="horizontal">
                        <TextView
                            android:id="@+id/tv_advisor_all_secret_detail_time"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text=""
                            android:textColor="@color/titleTextGray"
                            android:textSize="@dimen/dm024"/>
                    </LinearLayout>
                </LinearLayout>
                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="@dimen/dm020"
                    android:orientation="vertical">
                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right"
                        android:orientation="horizontal">
                        <TextView
                            android:id="@+id/tv_advisor_all_secret_detail_count"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text=""
                            android:textColor="@color/colorTitle"
                            android:textSize="@dimen/dm022"/>
                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="@dimen/dm010"
                            android:text="人参与"
                            android:textColor="@color/titleTextGray"
                            android:textSize="@dimen/dm022"/>
                    </LinearLayout>
                    <TextView
                        android:id="@+id/tv_advisor_all_secret_detail_money"
                        android:layout_width="wrap_content"
                        android:layout_gravity="right"
                        android:layout_marginTop="@dimen/dm050"
                        android:gravity="center"
                        android:layout_height="wrap_content"
                        android:text="¥0元"
                        android:textColor="@color/colorTitle"
                        android:textSize="@dimen/dm028"/>
                </LinearLayout>
            </LinearLayout>
            <View
                android:layout_width="match_parent"
                android:layout_height="@dimen/dm016"/>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/colorWhite"
                android:orientation="vertical">
                <LinearLayout android:layout_width="match_parent"
                              android:layout_height="wrap_content"
                              android:orientation="horizontal">
                    <TextView
                        android:id="@+id/tv_advisor_all_secret_detail_name"
                        android:layout_width="wrap_content"
                        android:layout_height="@dimen/dm070"
                        android:layout_marginTop="@dimen/dm002"
                        android:gravity="center"
                        android:paddingLeft="@dimen/dm020"
                        android:text="课程介绍"
                        android:textColor="@color/titleText"
                        android:textSize="@dimen/dm028"/>
                    <View
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1"/>
                    <TextView
                        android:id="@+id/tv_advisor_all_secret_detail_status"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginRight="@dimen/dm018"
                        android:textColor="@color/colorTitle"
                        android:textSize="@dimen/dm028"/>

                </LinearLayout>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@color/gray"/>
                <TextView
                    android:id="@+id/tv_advisor_all_secret_detail_detail"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="@dimen/dm020"
                    android:paddingLeft="@dimen/dm020"
                    android:text=""
                    android:textColor="@color/colorText"
                    android:textSize="@dimen/dm024"/>
            </LinearLayout>
        </LinearLayout>
        <TextView
            android:id="@+id/tv_advisor_all_secret_detail_pay"
            android:layout_width="match_parent"
            android:layout_height="@dimen/dm090"
            android:layout_alignParentBottom="true"
            android:background="@color/colorTitle"
            android:gravity="center"
            android:text="立即支付"
            android:textColor="@color/colorWhite"
            android:textSize="@dimen/dm032"/>
    </RelativeLayout>
</LinearLayout>


text:
Get Zulip notifications for your Raygun events!

1. {!create-stream.md!}

1. {!create-bot-construct-url.md!}

1. Go to your Raygun dashboard, and click on **Integrations**.
   Click on **Webhook**, and click on the **Setup** tab.

1. Set **Url** to the URL constructed above. Check the **Enabled**
   checkbox, and click **Save Changes**.

{!congrats.md!}

![](/static/images/integrations/raygun/001.png)

redpajama_set_name: RedPajamaGithub


text:
CGSize searchBarTextFieldDefaultSize = {300, 30};

@interface AGXSearchBar () <UITextFieldDelegate> {
    UIControl *_mask;
}
@end

@implementation AGXSearchBar

@dynamic maskBackgroundColor;
@dynamic searchText;

- (void)agxInitial {
    [super agxInitial];
    self.backgroundColor = UIColor.lightGrayColor;

    _searchTextField = [[UITextField alloc] initWithFrame:
                        CGRectMake(0, 0, searchBarTextFieldDefaultSize.width,
                                   searchBarTextFieldDefaultSize.height)];
    _searchTextField.font = [UIFont systemFontOfSize:searchBarTextFieldDefaultSize.height / 2];
    _searchTextField.textColor = UIColor.blackColor;
    [_searchTextField setValue:UIColor.grayColor forKeyPath:@"_placeholderLabel.textColor"];
    _searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _searchTextField.returnKeyType = UIReturnKeySearch;
    _searchTextField.delegate = self;
    [self addSubview:_searchTextField];

    _mask = [[UIControl alloc] initWithFrame:UIScreen.mainScreen.bounds];
    [_mask addTarget:self action:@selector(maskTouched:) forControlEvents:UIControlEventTouchUpInside];

    AGXAddNotificationWithObject(searchTextFieldTextDidChange:, UITextFieldTextDidChangeNotification, _searchTextField);
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _searchTextField.placeholder = AGXWidgetLocalizedStringDefault(@"AGXSearchBar.placeholder", @"Search");
    if ([self isEqual:_searchTextField.superview]) {
        _searchTextField.center = CGPointMake(self.bounds.size.width / 2,
                                              self.bounds.size.height / 2);
    }
}

- (void)dealloc {
    AGXRemoveNotificationWithObject(UITextFieldTextDidChangeNotification, _searchTextField);
    _delegate = nil;

    AGX_RELEASE(_searchTextField);
    AGX_RELEASE(_mask);
    AGX_SUPER_DEALLOC;
}

- (void)setSearchTextField:(UITextField *)searchTextField {
    if AGX_EXPECT_F([_searchTextField isEqual:searchTextField]) return;

    [_searchTextField.superview addSubview:searchTextField];
    [_searchTextField removeFromSuperview];

    AGXRemoveNotificationWithObject(UITextFieldTextDidChangeNotification, _searchTextField);
    AGX_RELEASE(_searchTextField);
    _searchTextField = AGX_RETAIN(searchTextField);
    _searchTextField.delegate = self;
    AGXAddNotificationWithObject(searchTextFieldTextDidChange:, UITextFieldTextDidChangeNotification, _searchTextField);
}

- (UIColor *)maskBackgroundColor {
    return _mask.backgroundColor;
}

- (void)setMaskBackgroundColor:(UIColor *)maskBackgroundColor {
    _mask.backgroundColor = maskBackgroundColor;
}

- (NSString *)searchText {
    return _searchTextField.text;
}

- (void)setSearchText:(NSString *)searchText {
    _searchTextField.text = searchText;
}

#pragma mark - User Event

- (void)maskTouched:(id)sender {
    if AGX_EXPECT_F(![sender isEqual:_mask]) return;

    [_searchTextField resignFirstResponder];
    [self addSubview:_searchTextField];
    _searchTextField.center = [_mask convertPoint:_searchTextField.center toView:self];
    [_mask agxAnimate:AGXAnimationMake(AGXAnimateOut|AGXAnimateFade, AGXAnimateStay, 0.1, 0)
           completion:^{ [_mask removeFromSuperview]; }];
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [UIApplication.sharedKeyWindow addSubview:_mask];
    [_mask addSubview:_searchTextField];
    _searchTextField.center = [self convertPoint:_searchTextField.center toView:_mask];

    if (![_delegate respondsToSelector:@selector(searchBarDidBeginInput:)]) return;
    [_delegate searchBarDidBeginInput:self];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (![_delegate respondsToSelector:@selector(searchBarDidEndInput:)]) return;
    [_delegate searchBarDidEndInput:self];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (![_delegate respondsToSelector:@selector(searchBar:searchWithText:editEnded:)]) return YES;

    if ([string isEqualToString:@"\n"]) {
        [_delegate searchBar:self searchWithText:_searchTextField.text editEnded:YES];
        [self maskTouched:_searchTextField.superview];
        return NO;
    }
    return YES;
}

#pragma mark - UITextFieldTextDidChangeNotification

- (void)searchTextFieldTextDidChange:(NSNotification *)notification {
    UITextField *textField = (UITextField *)notification.object;
    if (textField.markedTextRange) return;
    if (![_delegate respondsToSelector:@selector(searchBar:searchWithText:editEnded:)]) return;
    [_delegate searchBar:self searchWithText:textField.text editEnded:NO];
}

@end


text:
package com.fpt.mic.micweb.model.business;

import com.fpt.mic.micweb.model.dao.PunishmentDao;

import com.fpt.mic.micweb.model.dto.form.PunishmentDto;
import com.fpt.mic.micweb.model.entity.PunishmentEntity;
import com.fpt.mic.micweb.model.dto.form.CreatePunishmentDto;
import com.fpt.mic.micweb.model.entity.ContractEntity;
import com.fpt.mic.micweb.model.entity.helper.IncrementsEntity;
import com.fpt.mic.micweb.utils.DateUtils;
import javassist.compiler.Parser;

import java.sql.Timestamp;
import java.util.List;

/**
 * Created by PhucNguyen on 04/07/2015.
 */
public class PunishmentBusiness {
    public List<PunishmentEntity> getPunishmentByContractCode(String contractCode) {
        PunishmentDao punishmentDao = new PunishmentDao();
        return punishmentDao.getAllPunishmentByContractCode(contractCode);
    }

    public PunishmentEntity getPunishmentDetail(Integer id) {
        PunishmentDao punishmentDao = new PunishmentDao();
        return punishmentDao.read(id);
    }

    public PunishmentEntity createNewPunishment(PunishmentDto dto) {
        PunishmentEntity punishmentEntity = new PunishmentEntity();
        PunishmentDao punishmentDao = new PunishmentDao();

        punishmentEntity.setContractCode(dto.getContractCode());
        punishmentEntity.setCreatedDate(dto.getCreatedDate());
        punishmentEntity.setTitle(dto.getTitle());
        punishmentEntity.setAttachment(dto.getAttachment());
        // Set date time by default
        punishmentEntity.setLastModified(DateUtils.currentTimeWithoutNanos());
        // Create punishment
        PunishmentEntity newPunishment = punishmentDao.create(punishmentEntity);

        if (newPunishment != null) {
            return newPunishment;
        }
        return null;
    }

    public boolean editPunishment(PunishmentDto dto) {
        PunishmentDao punishmentDao = new PunishmentDao();
        PunishmentEntity punishmentEntity = punishmentDao.read(dto.getId());

        if (punishmentEntity != null) {
            punishmentEntity.setContractCode(dto.getContractCode());
            punishmentEntity.setCreatedDate(dto.getCreatedDate());
            punishmentEntity.setTitle(dto.getTitle());
            punishmentEntity.setAttachment(dto.getAttachment());
            // Concurrency set value
            punishmentEntity.setLastModified(DateUtils.currentTimeWithoutNanos());

            if (punishmentDao.update(punishmentEntity) != null) {
                return true;
            }
        }
        return false;
    }

    public Long getAllPunishmentByContractCodeCount(String code) {
        PunishmentDao punishmentDao = new PunishmentDao();
        return punishmentDao.getAllPunishmentByContractCodeCount(code);
    }

    public List getAllPunishmentByContractCode(String code, int offset, int count) {
        PunishmentDao punishmentDao = new PunishmentDao();
        return punishmentDao.getPunishmentByContractCode(code, offset, count);
    }

    public PunishmentEntity createPunishment(CreatePunishmentDto dto) {
        PunishmentDao punishmentDao = new PunishmentDao();
        PunishmentEntity punishmentEntity = new PunishmentEntity();
        punishmentEntity.setCreatedDate(dto.getCreateDate());
        punishmentEntity.setTitle(dto.getTitle());
        punishmentEntity.setAttachment(dto.getAttachment());
        punishmentEntity.setContractCode(dto.getContractCode());
        punishmentEntity.setLastModified(DateUtils.currentTimeWithoutNanos());

        PunishmentEntity newPunishmentEntity = new PunishmentEntity();
        newPunishmentEntity = punishmentDao.create(punishmentEntity);
        if (newPunishmentEntity != null) {
            return newPunishmentEntity;
        }
        return null;
    }
}


text:
package src.test.java;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GoogleSearchPageObjTest {
    WebDriver driver;

    @Before
    public void setUp() throws Exception {
        driver = new FirefoxDriver();
    }

    @Test
    public void workWithBasicAuthTest() {
        GoogleSearchPageObj google = new GoogleSearchPageObj(driver);
        google.searchFor("elemental selenium tips");
        boolean result = google.searchResultPresent("Recieve a Free, Weekly tip");
        assert (result == true);
    }

    @After
    public void tearDown() throws Exception {
        driver.quit();
    }
}


text:
layout: post
title: "Monday 06.17.19 -  CrossFit"
teaser: "A.
 B.
 C.  "
date: 2019-06-17 00:00:00
categories: wodup
tags: wods monday
header: no
---

A.

Within 9 minutes:

Back Squat
– 3 sets of 7 reps
Rest as needed

On a 3 minute timer for 9 minutesImmediately go into Part B after your last set of Back Squat….

B.

Within 14 minutes:

Shoulder Press
– 7 sets of 3 reps
Rest as needed

On a 2 minute timer for 14 minutes

C.

As Many Rounds and Reps as possible in 15 minutes:
– Run 400 meters
– 20 Pull-Ups
– 10 Burpee Box Jump-Overs 24/20 inches

View on WodUp

#### Compare to other Mondays
{: .t60 }

{% include list-posts tag='monday' entries='5' %}


text:
module ActionText
  class Attachment
    include Attachments::TrixConversion, Attachments::Minification, Attachments::Caching

    TAG_NAME = "action-text-attachment"
    SELECTOR = TAG_NAME
    ATTRIBUTES = %w( sgid content-type url href filename filesize width height previewable presentation caption )

    class << self
      def fragment_by_canonicalizing_attachments(content)
        fragment_by_minifying_attachments(fragment_by_converting_trix_attachments(content))
      end

      def from_node(node, attachable = nil)
        new(node, attachable || ActionText::Attachable.from_node(node))
      end

      def from_attachables(attachables)
        Array(attachables).map { |attachable| from_attachable(attachable) }.compact
      end

      def from_attachable(attachable, attributes = {})
        if node = node_from_attributes(attachable.to_rich_text_attributes(attributes))
          new(node, attachable)
        end
      end

      def from_attributes(attributes, attachable = nil)
        if node = node_from_attributes(attributes)
          from_node(node, attachable)
        end
      end

      private
        def node_from_attributes(attributes)
          if attributes = process_attributes(attributes).presence
            ActionText::HtmlConversion.create_element(TAG_NAME, attributes)
          end
        end

        def process_attributes(attributes)
          attributes.transform_keys { |key| key.to_s.underscore.dasherize }.slice(*ATTRIBUTES)
        end
    end

    attr_reader :node, :attachable

    delegate :to_param, to: :attachable
    delegate_missing_to :attachable

    def initialize(node, attachable)
      @node = node
      @attachable = attachable
    end

    def caption
      node_attributes["caption"].presence
    end

    def full_attributes
      node_attributes.merge(attachable_attributes).merge(sgid_attributes)
    end

    def with_full_attributes
      self.class.from_attributes(full_attributes, attachable)
    end

    def to_plain_text
      if respond_to?(:attachable_plain_text_representation)
        attachable_plain_text_representation(caption)
      else
        caption.to_s
      end
    end

    def to_html
      HtmlConversion.node_to_html(node)
    end

    def to_s
      to_html
    end

    def inspect
      "#<#{self.class.name} attachable=#{attachable.inspect}>"
    end

    private
      def node_attributes
        @node_attributes ||= ATTRIBUTES.map { |name| [ name.underscore, node[name] ] }.to_h.compact
      end

      def attachable_attributes
        @attachable_attributes ||= (attachable.try(:to_rich_text_attributes) || {}).stringify_keys
      end

      def sgid_attributes
        @sgid_attributes ||= node_attributes.slice("sgid").presence || attachable_attributes.slice("sgid")
      end
  end
end


text:
package de.hawhamburg.vs.wise15.superteam.client.api;

import de.hawhamburg.vs.wise15.superteam.client.model.Client;
import retrofit.Call;
import retrofit.http.Body;
import retrofit.http.POST;

/**
 * Created by florian on 16.11.15.
 */
public interface PlayersAPI {

    // TODO rest api?

    @POST("player")
    Call<Integer> connectPlayer(@Body Client client);

}


text:
photon.dom.subscribeToCleanup(function (node) {
    // clean disposables
    var data = photon.getData(node);
    if (data) {
        if (data.disposables) {
            for (var i = 0, n = data.disposables.length; i < n; i++) {
                data.disposables[i].dispose();
            }
        }
    }
});

photon.addDisposable = function (element, disposable) {
    var data = photon.getOrCreateData(element);
    (data.disposables = data.disposables || []).push(disposable);
};

photon.rewriteTemplate = function (template) {
    var regex = /(<[a-z]([a-z]|\d)*(\s+(?!data-context=('templateSource[^']*'|"templateSource[^']*"))[a-z0-9\-]+(=("[^"]*"|'[^']*'))?)*\s+(data-context=((["'])templateSource:([\s\S]*?))\9))/gi;

    return template.replace(regex, function () {
        var argumentsLength = arguments.length;
        var result = new photon.StringBuilder();
        var temp = arguments[0];
        result.push(temp.substring(0, temp.length - arguments[argumentsLength - 6].length));
        result.push('data-context-id=');
        var delimiter = arguments[argumentsLength - 4];
        result.push(delimiter);
        photon.rewriteScriptFragment(result, '=context.identity(' + arguments[argumentsLength - 3] + ')');
        result.push(delimiter);
        return result.get();
    });
};

photon.rewriteScriptFragment = function (builder, script) {
    builder.pushAll(['<%', script, '%>']);
};

photon.getOrCreateData = function (node) {
    return node.photonData || (node.photonData = {});
};

photon.getData = function (node) {
    return node.photonData;
};

(function () {
    function processElement(element, bindingTypes, callback) {
        for (var j = 0, nj = bindingTypes.length; j < nj; j++) {
            var bindingType = bindingTypes[j];
            var bindingValue = element.getAttribute(bindingType);
            if (bindingValue) {
                callback(element, bindingType, bindingValue);
            }
        }
    }

    // TODO: Still need to do more work to find best overall solution
    var fnDataElementSelector = document.querySelectorAll ?
        function (element, bindingTypes, callback) {
            var types = "*[" + bindingTypes.join("], *[") + "]";
            if (element.nodeType === 1) {
                processElement(element, bindingTypes, callback);
            }
            photon.array.forEach(element.querySelectorAll(types), function(childElement) {
                processElement(childElement, bindingTypes, callback);
            });
        }
        :
        function (element, bindingTypes, callback) {
            if (element.nodeType === 1) {
                processElement(element, bindingTypes, callback);
            }
            var elements = element.getElementsByTagName("*");
            for (var i = 0, ni = elements.length; i < ni; i++) {
                processElement(element, bindingTypes, callback);
            }
        };

    photon.binding.forEachBoundElement = function (element, bindingTypes, callback) {
        element = element || document;
        if (!element) {
            return;
        }
        if (photon.isString(bindingTypes)) {
            bindingTypes = [bindingTypes];
        }
        fnDataElementSelector(element, bindingTypes, callback);
    };
})();


text:
namespace ExpenseTracker.Web.Infrastructure.Mapping
{
    public interface IMapFrom<T>
        where T : class
    {
    }
}


text:
module Jobs
  class PurgeInactive < Jobs::Scheduled
    every 1.day

    def execute(args)
      User.purge_unactivated
    end
  end
end


text:
{-# LANGUAGE GeneralizedNewtypeDeriving, PatternGuards #-}
module Vimus.Macro (
  Macros
, addMacro
, removeMacro
, expandMacro
, help
, helpAll
, guessCommands
) where

import           Prelude hiding (getChar)
import           Data.List (isPrefixOf)
import           Text.Printf (printf)

import           Data.Map (Map)
import qualified Data.Map as Map

import           Data.Default

import           Vimus.Key (unExpandKeys)

import           Vimus.Input

newtype Macros = Macros (Map String String)

-- helper for `help` and `helpAll`
formatMacro :: String -> String -> String
formatMacro m c = printf "%-10s %s" (unExpandKeys m) (unExpandKeys c)

-- | Get help message for a macro.
help :: String -> Macros -> Either String String
help m (Macros ms) = maybe (noMapping m) (Right . formatMacro m) (Map.lookup m ms)

-- | Convert macros to a list of strings, suitable for help.
helpAll :: Macros -> [String]
helpAll (Macros ms) = map (uncurry formatMacro) (Map.toList ms)

noMapping :: String -> Either String a
noMapping m = Left ("no mapping for " ++ unExpandKeys m)

-- | Expand a macro.
expandMacro :: Monad m => Macros -> Char -> InputT m ()
expandMacro (Macros macroMap) = go . return
  where
    keys = Map.keys macroMap

    go input = do
      case Map.lookup input macroMap of
        Just v -> unGetString v
        Nothing ->
          if null matches
            then do
              -- input does not match any macro, so we consume exactly one
              -- character and push the rest back into the input queue
              unGetString (tail input)
            else do
              -- input is a prefix of some macro, so we read an other character
              c <- getChar
              go (input ++ [c])
      where
        matches = filter (isPrefixOf input) keys

-- | Add a macro.
addMacro :: String -> String -> Macros -> Macros
addMacro m e (Macros ms) = Macros (Map.insert m e ms)

-- | Remove a macro.
removeMacro :: String -> Macros -> Either String Macros
removeMacro m (Macros ms)
  | m `Map.member` ms  = (Right . Macros . Map.delete m) ms
  | otherwise          = noMapping m

-- | Construct a map from command to macros defined for that command.
guessCommands :: [String] -> Macros -> Map String [String]
guessCommands commands (Macros ms) = (Map.fromListWith (++) . foldr f [] . Map.toDescList) ms
  where
    f (m, e) xs
      | c `elem` commands = (c, [unExpandKeys m]) : xs
      | otherwise         = xs
      where c = strip e

    strip xs
      | ':':ys <- xs, '\n':zs <- reverse ys = reverse zs
      | otherwise = xs

-- | Default macros.
instance Default Macros where
  def = Macros Map.empty


text:
/*
 * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0
 *
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.firebasehosting.v1beta1.model;

/**
 * Model definition for ListVersionsResponse.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Firebase Hosting API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class ListVersionsResponse extends com.google.api.client.json.GenericJson {

  /**
   * The pagination token, if more results exist beyond the ones in this response. Include this
   * token in your next call to `ListVersions`. Page tokens are short-lived and should not be
   * stored.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String nextPageToken;

  /**
   * The list of versions, if any exist.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<Version> versions;

  /**
   * The pagination token, if more results exist beyond the ones in this response. Include this
   * token in your next call to `ListVersions`. Page tokens are short-lived and should not be
   * stored.
   * @return value or {@code null} for none
   */
  public java.lang.String getNextPageToken() {
    return nextPageToken;
  }

  /**
   * The pagination token, if more results exist beyond the ones in this response. Include this
   * token in your next call to `ListVersions`. Page tokens are short-lived and should not be
   * stored.
   * @param nextPageToken nextPageToken or {@code null} for none
   */
  public ListVersionsResponse setNextPageToken(java.lang.String nextPageToken) {
    this.nextPageToken = nextPageToken;
    return this;
  }

  /**
   * The list of versions, if any exist.
   * @return value or {@code null} for none
   */
  public java.util.List<Version> getVersions() {
    return versions;
  }

  /**
   * The list of versions, if any exist.
   * @param versions versions or {@code null} for none
   */
  public ListVersionsResponse setVersions(java.util.List<Version> versions) {
    this.versions = versions;
    return this;
  }

  @Override
  public ListVersionsResponse set(String fieldName, Object value) {
    return (ListVersionsResponse) super.set(fieldName, value);
  }

  @Override
  public ListVersionsResponse clone() {
    return (ListVersionsResponse) super.clone();
  }

}


text:
"""
Created on Wed Sep 18 00:06:28 2019.

@author: mtageld
"""
import os
import shutil
import sys
import tempfile

import numpy as np
import pytest
from pandas import read_csv

from histomicstk.annotations_and_masks.annotation_and_mask_utils import \
    delete_annotations_in_slide
from histomicstk.saliency.cellularity_detection_superpixels import \
    Cellularity_detector_superpixels
from histomicstk.saliency.cellularity_detection_thresholding import \
    Cellularity_detector_thresholding
from histomicstk.saliency.tissue_detection import (
    get_slide_thumbnail, get_tissue_boundary_annotation_documents,
    get_tissue_mask)

thisDir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(thisDir, '../../../tests'))
# import htk_test_utilities as utilities  # noqa
from htk_test_utilities import getTestFilePath, girderClient  # noqa

# # for protyping
# from tests.htk_test_utilities import _connect_to_existing_local_dsa
# girderClient = _connect_to_existing_local_dsa()

class Cfg:
    def __init__(self):
        self.gc = None
        self.iteminfo = None
        self.labeled = None
        self.GTcodes = None
        self.logging_savepath_cdt = tempfile.mkdtemp()
        self.logging_savepath_cds = tempfile.mkdtemp()

cfg = Cfg()

@pytest.mark.usefixtures('girderClient')  # noqa
def test_prep(girderClient):  # noqa
    cfg.gc = girderClient
    cfg.iteminfo = cfg.gc.get('/item', parameters={
        'text': "TCGA-A2-A0YE-01Z-00-DX1"})[0]
    cfg.GTcodes = read_csv(getTestFilePath('saliency_GTcodes.csv'))

class TestTissueDetection():
    """Test methods for getting ROI mask from annotations."""

    def test_get_tissue_mask(self):
        """Test get_tissue_mask()."""
        thumbnail_rgb = get_slide_thumbnail(cfg.gc, cfg.iteminfo['_id'])
        cfg.labeled, mask = get_tissue_mask(
            thumbnail_rgb, deconvolve_first=True,
            n_thresholding_steps=1, sigma=1.5, min_size=30)

        assert cfg.labeled.shape == (156, 256)
        assert len(np.unique(cfg.labeled)) == 11

    def test_get_tissue_boundary_annotation_documents(self):
        """Test get_tissue_boundary_annotation_documents()."""
        annotation_docs = get_tissue_boundary_annotation_documents(
            cfg.gc, slide_id=cfg.iteminfo['_id'], labeled=cfg.labeled)

        assert 'elements' in annotation_docs[0].keys()
        assert len(annotation_docs[0]['elements']) == 9

        # test delete existing annotations in slide
        delete_annotations_in_slide(cfg.gc, cfg.iteminfo['_id'])

        # check that it posts without issues
        resps = [
            cfg.gc.post(
                "/annotation?itemId=" + cfg.iteminfo['_id'], json=doc)
            for doc in annotation_docs
        ]
        assert all(['annotation' in resp for resp in resps])

class TestCellularityDetection:
    """Test methods for getting cellularity."""

    def test_cellularity_detection_thresholding(self):
        """Test Cellularity_detector_thresholding()."""
        # run cellularity detector
        cdt = Cellularity_detector_thresholding(
            cfg.gc, slide_id=cfg.iteminfo['_id'],
            GTcodes=cfg.GTcodes, MAG=1.0,
            verbose=1, monitorPrefix='test',
            logging_savepath=cfg.logging_savepath_cdt)
        tissue_pieces = cdt.run()

        # check
        assert len(tissue_pieces) == 3
        assert all([
            j in tissue_pieces[0].__dict__.keys() for j in
            ('labeled', 'ymin', 'xmin', 'ymax', 'xmax')
        ])

        # cleanup
        shutil.rmtree(cfg.logging_savepath_cdt)

    def test_cellularity_detection_superpixels(self):
        """Test Cellularity_detector_superpixels()."""
        # from the ROI in Amgad et al, 2019
        cnorm_main = {
            'mu': np.array([8.74108109, -0.12440419, 0.0444982]),
            'sigma': np.array([0.6135447, 0.10989545, 0.0286032]),
        }
        # run cellularity detector
        cds = Cellularity_detector_superpixels(
            cfg.gc, slide_id=cfg.iteminfo['_id'],
            MAG=1.0, compactness=0.1, spixel_size_baseMag=256 * 256,
            max_cellularity=40,
            visualize_spixels=True, visualize_contiguous=True,
            get_tissue_mask_kwargs={
                'deconvolve_first': False,
                'n_thresholding_steps': 2,
                'sigma': 1.5,
                'min_size': 500, },
            verbose=1, monitorPrefix='test',
            logging_savepath=cfg.logging_savepath_cds)
        cds.set_color_normalization_values(
            mu=cnorm_main['mu'], sigma=cnorm_main['sigma'], what='main')
        tissue_pieces = cds.run()

        # check
        assert len(tissue_pieces) == 2
        assert all([
            j in tissue_pieces[0].__dict__.keys()
            for j in ('tissue_mask', 'ymin', 'xmin', 'ymax', 'xmax',
                      'spixel_mask', 'fdata', 'cluster_props')
        ])
        assert len(tissue_pieces[0].cluster_props) == 5

        # cleanup
        shutil.rmtree(cfg.logging_savepath_cds)


text:
#ifndef UCS_ASM_X86_64_H_
#define UCS_ASM_X86_64_H_

#include <ucs/sys/compiler.h>
#include <stdint.h>

#ifdef __SSE4_1__
#  include <smmintrin.h>
#endif
#ifdef __AVX__
#  include <immintrin.h>
#endif

#define UCS_SYS_CACHE_LINE_SIZE    64

/**
 * In x86_64, there is strong ordering of each processor with respect to another
 * processor, but weak ordering with respect to the bus.
 */
#define ucs_memory_bus_fence()        asm volatile ("mfence"::: "memory")
#define ucs_memory_bus_store_fence()  asm volatile ("sfence" ::: "memory")
#define ucs_memory_bus_load_fence()   asm volatile ("lfence" ::: "memory")
#define ucs_memory_cpu_fence()        ucs_compiler_fence()
#define ucs_memory_cpu_store_fence()  ucs_compiler_fence()
#define ucs_memory_cpu_load_fence()   ucs_compiler_fence()

static inline uint64_t ucs_arch_read_hres_clock()
{
    uint32_t low, high;
    asm volatile ("rdtsc" : "=a" (low), "=d" (high));
    return ((uint64_t)high << 32) | (uint64_t)low;
}

double ucs_arch_get_clocks_per_sec();

ucs_cpu_model_t ucs_arch_get_cpu_model();

#endif


text:
""" This module handles everything related to log parsing """
import re       # For parsing the log file (regular expressions)
import os       # For working with files on the operating system
import logging  # For logging
from game_objects.item  import Item
from game_objects.floor import Floor, Curse
from game_objects.state  import TrackerState
from options import Options

class LogParser(object):
    """
    This class load Isaac's log file, and incrementally modify a state representing this log
    """
    def __init__(self, prefix, tracker_version, log_finder):
        self.state = TrackerState("", tracker_version, Options().game_version)
        self.log = logging.getLogger("tracker")
        self.wdir_prefix = prefix
        self.log_finder = log_finder

        self.reset()

    def reset(self):
        """Reset variable specific to the log file/run"""
        # Variables describing the parser state
        self.getting_start_items = False
        self.current_room = ""
        self.current_seed = ""
        # Cached contents of log
        self.content = ""
        # Log split into lines
        self.splitfile = []
        self.run_start_line = 0
        self.seek = 0
        self.spawned_coop_baby = 0
        self.log_file_handle = None
        # if they switched between rebirth and afterbirth, the log file we use could change
        self.log_file_path = self.log_finder.find_log_file(self.wdir_prefix)
        self.state.reset(self.current_seed, Options().game_version)

    def parse(self):
        """
        Parse the log file and return a TrackerState object,
        or None if the log file couldn't be found
        """

        self.opt = Options()
        # Attempt to load log_file
        if not self.__load_log_file():
            return None
        self.splitfile = self.content.splitlines()

        # This will become true if we are getting starting items
        self.getting_start_items = False

        # Process log's new output
        for current_line_number, line in enumerate(self.splitfile[self.seek:]):
            self.__parse_line(current_line_number, line)

        self.seek = len(self.splitfile)
        return self.state

    def __parse_line(self, line_number, line):
        """
        Parse a line using the (line_number, line) tuple
        """
        # In Afterbirth+, nearly all lines start with this.
        # We want to slice it off.
        info_prefix = '[INFO] - '
        if line.startswith(info_prefix):
            line = line[len(info_prefix):]

        # Messages printed by mods have this prefix.
        # strip it, so mods can spoof actual game log messages to us if they want to
        luadebug_prefix ='Lua Debug: '
        if line.startswith(luadebug_prefix):
            line = line[len(luadebug_prefix):]

        # AB and AB+ version messages both start with this text (AB+ has a + at the end)
        if line.startswith('Binding of Isaac: Afterbirth'):
            self.__parse_version_number(line)
        if line.startswith('Binding of Isaac: Rebirth'):
            self.__parse_version_number(line)
        if line.startswith('RNG Start Seed:'):
            self.__parse_seed(line, line_number)
        if line.startswith('Room'):
            self.__parse_room(line)
        if line.startswith('Level::Init'):
            self.__parse_floor(line, line_number)
        if line.startswith("Curse"):
            self.__parse_curse(line)
        if line.startswith("Spawn co-player!"):
            self.spawned_coop_baby = line_number + self.seek
        if re.search(r"Added \d+ Collectibles", line):
            self.log.debug("Reroll detected!")
            self.state.reroll()
        if line.startswith('Adding collectible '):
            self.__parse_item_add(line_number, line)
        if line.startswith('Gulping trinket '):
            self.__parse_trinket_gulp(line)
        if line.startswith('Removing collectible '):
            self.__parse_item_remove(line)

    def __trigger_new_run(self, line_number):
        self.log.debug("Starting new run, seed: %s", self.current_seed)
        self.run_start_line = line_number + self.seek
        self.state.reset(self.current_seed, Options().game_version)

    def __parse_version_number(self, line):
        words = line.split()
        self.state.version_number = words[-1]

    def __parse_seed(self, line, line_number):
        """ Parse a seed line """
        # This assumes a fixed width, but from what I see it seems safe
        self.current_seed = line[16:25]

        # Antibirth doesn't have a proper way to detect run resets
        # it will wipe the tracker when doing a "continue"
        if self.opt.game_version == "Antibirth":
            self.__trigger_new_run(line_number)

    def __parse_room(self, line):
        """ Parse a room line """
        if 'Start Room' not in line:
            self.getting_start_items = False

        match = re.search(r"Room (.+?)\(", line)
        if match:
            room_id = match.group(1)
            self.state.change_room(room_id)

    def __parse_floor(self, line, line_number):
        """ Parse the floor in line and push it to the state """
        # Create a floor tuple with the floor id and the alternate id
        if self.opt.game_version == "Afterbirth" or self.opt.game_version == "Afterbirth+":
            regexp_str = r"Level::Init m_Stage (\d+), m_StageType (\d+)"
        elif self.opt.game_version == "Rebirth" or self.opt.game_version == "Antibirth":
            regexp_str = r"Level::Init m_Stage (\d+), m_AltStage (\d+)"
        else:
            return
        search_result = re.search(regexp_str, line)
        if search_result is None:
            self.log.debug("log.txt line doesn't match expected regex\nline: \"" + line+ "\"\nregex:\"" + regexp_str + "\"")
            return

        floor = int(search_result.group(1))
        alt = search_result.group(2)
        self.getting_start_items = True

        # we use generation of the first floor as our trigger that a new run started.
        # in antibirth, this doesn't work; instead we have to use the seed being printed as our trigger
        # that means if you s+q in antibirth, it resets the tracker.
        if floor == 1 and self.opt.game_version != "Antibirth":
            self.__trigger_new_run(line_number)

        # Special handling for the Cathedral and The Chest and Afterbirth
        if self.opt.game_version == "Afterbirth" or self.opt.game_version == "Afterbirth+":
            # In Afterbirth, Cath is an alternate of Sheol (which is 10)
            # and Chest is an alternate of Dark Room (which is 11)
            if floor == 10 and alt == '0':
                floor -= 1
            elif floor == 11 and alt == '1':
                floor += 1
        else:
            # In Rebirth, floors have different numbers
            if alt == '1' and (floor == 9 or floor == 11):
                floor += 1
        floor_id = 'f' + str(floor)

        # Greed mode
        if alt == '3':
            floor_id += 'g'

        self.state.add_floor(Floor(floor_id))
        return True

    def __parse_curse(self, line):
        """ Parse the curse and add it to the last floor """
        if line.startswith("Curse of the Labyrinth!"):
            self.state.add_curse(Curse.Labyrinth)
        if line.startswith("Curse of Blind"):
            self.state.add_curse(Curse.Blind)
        if line.startswith("Curse of the Lost!"):
            self.state.add_curse(Curse.Lost)

    def __parse_item_add(self, line_number, line):
        """ Parse an item and push it to the state """
        if len(self.splitfile) > 1 and self.splitfile[line_number + self.seek - 1] == line:
            self.log.debug("Skipped duplicate item line from baby presence")
            return False
        space_split = line.split(" ")
        numeric_id = space_split[2] # When you pick up an item, this has the form: "Adding collectible 105 (The D6)"
        item_name = " ".join(space_split[3:])[1:-1]
        item_id = ""

        # Check if we recognize the numeric id
        if Item.contains_info(numeric_id):
            item_id = numeric_id
        else:
            # it might be a modded custom item. let's see if we recognize the name
            item_id = Item.modded_item_id_prefix + item_name
            if not Item.contains_info(item_id):
                item_id = "NEW"

        self.log.debug("Picked up item. id: %s, name: %s", item_id, item_name)
        if ((line_number + self.seek) - self.spawned_coop_baby) < (len(self.state.item_list) + 10) \
                and self.state.contains_item(item_id):
            self.log.debug("Skipped duplicate item line from baby entry")
            return False

        # It's a blind pickup if we're on a blind floor and we don't have the Black Candle
        blind_pickup = self.state.last_floor.floor_has_curse(Curse.Blind) and not self.state.contains_item('260')
        added = self.state.add_item(Item(item_id, self.state.last_floor, self.getting_start_items, blind=blind_pickup))
        if not added:
            self.log.debug("Skipped adding item %s to avoid space-bar duplicate", item_id)
        return True

    def __parse_trinket_gulp(self, line):
        """ Parse a (modded) trinket gulp and push it to the state """
        space_split = line.split(" ")
        # When using a mod like racing+, a trinket gulp has the form: "Gulping trinket 10"
        numeric_id = str(int(space_split[2]) + 2000) # the tracker hackily maps trinkets to items 2000 and up.

        # Check if we recognize the numeric id
        if Item.contains_info(numeric_id):
            item_id = numeric_id
        else:
            item_id = "NEW"

        self.log.debug("Gulped trinket: %s", item_id)

        added = self.state.add_item(Item(item_id, self.state.last_floor, self.getting_start_items))
        if not added:
            self.log.debug("Skipped adding item %s to avoid space-bar duplicate", item_id)
        return True

    def __parse_item_remove(self, line):
        """ Parse an item and remove it from the state """
        space_split = line.split(" ") # Hacky string manipulation
        item_id = space_split[2] # When you lose an item, this has the form: "Removing collectible 105 (The D6)"
        item_name = " ".join(space_split[3:])[1:-1]

        # Check if the item ID exists
        if Item.contains_info(item_id):
            removal_id = item_id
        else:
            # that means it's probably a custom item
            removal_id = Item.modded_item_id_prefix + item_name

        self.log.debug("Removed item. id: %s", removal_id)

        # A check will be made inside the remove_item function
        # to see if this item is actually in our inventory or not.
        return self.state.remove_item(removal_id)

    def __load_log_file(self):
        if self.log_file_path is None:
            return False

        if self.log_file_handle is None:
            self.log_file_handle = open(self.log_file_path, 'rb')

        cached_length = len(self.content)
        file_size = os.path.getsize(self.log_file_path)

        if cached_length > file_size or cached_length == 0: # New log file or first time loading the log
            self.reset()
            self.content = open(self.log_file_path, 'rb').read()
        elif cached_length < file_size:  # Append existing content
            self.log_file_handle.seek(cached_length + 1)
            self.content += self.log_file_handle.read()
        return True


text:
<!DOCTYPE html>

		<meta charset="UTF-8">
		<title>Gaia-Web</title>

		<link rel="stylesheet" href="/gaia.css" type="text/css" media="all"/>

		{{navigation}}

<input id="div-id-command-line-classic-input-text" class="command_line_input_text" style="width:100%;" type="text" value="" />


text:
package com.nvapp.video.webrtc;

import com.nvapp.comic.R;
import com.nvapp.video.webrtc.support.RingAlarm;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageButton;
import android.widget.TextView;
import de.greenrobot.event.EventBus;

public class SendCallActivity extends Activity implements OnClickListener {
    private static final int CONNECTION_REQUEST = 1;
    /* 是否是发起者 */
    private boolean initiator;
    /* 声音报警 */
    private RingAlarm alarm;

    @SuppressLint("InlinedApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN
                             | LayoutParams.FLAG_KEEP_SCREEN_ON
                             | LayoutParams.FLAG_DISMISS_KEYGUARD
                             | LayoutParams.FLAG_SHOW_WHEN_LOCKED
                             | LayoutParams.FLAG_TURN_SCREEN_ON);

        setContentView(R.layout.activity_sendcall);

        ImageButton btnHangUp = (ImageButton) this.findViewById(R.id.btnHangUp);
        btnHangUp.setOnClickListener(this);

        Intent intent = this.getIntent();
        initiator = intent.getBooleanExtra(RTCClient.EXTRA_INITIATOR, true);

        if (initiator) {
            String toUser = intent.getStringExtra(RTCClient.EXTRA_TO_USER);
            this.setTips(String.format("请求%s视频中...", toUser));
        } else {
            String fromUser = intent.getStringExtra(RTCClient.EXTRA_FROM_USER);
            this.setTips(String.format("%s 视频请求中...", fromUser));
        }

        alarm = new RingAlarm();
        alarm.ring(this);

        EventBus.getDefault().register(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CONNECTION_REQUEST) {
            setResult(resultCode);
            finish();
        }
    }

    /* 接收EventBus消息 */
    public void onEventMainThread(RTCEvent event) {
        if (RTCClient.CMD_REPLY_CALL.equals(event.getName())) {
            Intent intent = new Intent(this, VideoActivity.class);
            intent.putExtra(RTCClient.EXTRA_INITIATOR, this.initiator);

            startActivityForResult(intent, CONNECTION_REQUEST);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btnHangUp) {
            this.finish();
        }
    }

    @Override
    public void onStop() {
        if (this.alarm != null) {
            alarm.stop();
        }

        super.onStop();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);

        super.onDestroy();
    }

    private void setTips(final String tips) {

        this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                TextView tv = (TextView) findViewById(R.id.video_request_tips);
                tv.setText(tips);
            }
        });
    }
}


text:
from FbBase import FbBase
from FbExporter import FbExporter, FbLikedUrlExporter


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;

using Internal.TypeSystem;
using ILCompiler.DependencyAnalysis;

using Debug = System.Diagnostics.Debug;

namespace ILCompiler
{
    public class EmptyMetadataManager : MetadataManager
    {
        public override bool SupportsReflection => false;

        public EmptyMetadataManager(CompilerTypeSystemContext typeSystemContext)
            : base(typeSystemContext, new FullyBlockedMetadataPolicy(), new FullyBlockedManifestResourcePolicy(), new NoDynamicInvokeThunkGenerationPolicy())
        {
        }

        public override void AddToReadyToRunHeader(ReadyToRunHeaderNode header, NodeFactory nodeFactory, ExternalReferencesTableNode commonFixupsTableNode)
        {
            // We don't attach any metadata blobs.
        }

        public override IEnumerable<ModuleDesc> GetCompilationModulesWithMetadata()
        {
            return Array.Empty<ModuleDesc>();
        }

        protected override MetadataCategory GetMetadataCategory(FieldDesc field)
        {
            return MetadataCategory.None;
        }

        protected override MetadataCategory GetMetadataCategory(MethodDesc method)
        {
            return MetadataCategory.None;
        }

        protected override MetadataCategory GetMetadataCategory(TypeDesc type)
        {
            return MetadataCategory.None;
        }

        protected override void ComputeMetadata(NodeFactory factory,
                                                out byte[] metadataBlob,
                                                out List<MetadataMapping<MetadataType>> typeMappings,
                                                out List<MetadataMapping<MethodDesc>> methodMappings,
                                                out List<MetadataMapping<FieldDesc>> fieldMappings,
                                                out List<MetadataMapping<MethodDesc>> stackTraceMapping)
        {
            metadataBlob = Array.Empty<byte>();

            typeMappings = new List<MetadataMapping<MetadataType>>();
            methodMappings = new List<MetadataMapping<MethodDesc>>();
            fieldMappings = new List<MetadataMapping<FieldDesc>>();
            stackTraceMapping = new List<MetadataMapping<MethodDesc>>();
        }

        /// <summary>
        /// Gets a stub that can be used to reflection-invoke a method with a given signature.
        /// </summary>
        public override MethodDesc GetCanonicalReflectionInvokeStub(MethodDesc method)
        {
            return null;
        }

        public override bool WillUseMetadataTokenToReferenceMethod(MethodDesc method)
        {
            return false;
        }

        public override bool WillUseMetadataTokenToReferenceField(FieldDesc field)
        {
            return false;
        }

        private sealed class FullyBlockedMetadataPolicy : MetadataBlockingPolicy
        {
            public override bool IsBlocked(MetadataType type)
            {
                Debug.Assert(type.IsTypeDefinition);
                return true;
            }

            public override bool IsBlocked(MethodDesc method)
            {
                Debug.Assert(method.IsTypicalMethodDefinition);
                return true;
            }

            public override bool IsBlocked(FieldDesc field)
            {
                Debug.Assert(field.IsTypicalFieldDefinition);
                return true;
            }
        }

        private sealed class FullyBlockedManifestResourcePolicy : ManifestResourceBlockingPolicy
        {
            public override bool IsManifestResourceBlocked(ModuleDesc module, string resourceName)
            {
                return true;
            }
        }
    }
}


text:
""" This code is used to read the log file into the memory  and convert into the data frame
    Once the log file is loaded ,every item in the IPQuery file checked if exist and result is print onto the console"""

#importing  python modules required for this script to perform operations

import time
import sys

start = time.time()#capturing time instance

class IpQuery:
    """Below methods contain the functionality to read file paths ,import log and query data
       and provide the result to the console """
    def __init__(self):
        self.log_file_name= ""
        self.query_file_name = ""
        self.logset = {}
        self.IPlist= []

    def Inputfiles(self):
        """code to check the arguments passed  and throw an error  """
        if len(sys.argv)!= 3:
            raise  ValueError(""" PLEASE PASS THE BOTH LOG FILE AND IPQUERY FILE AS INPUT TO SCRIPT
                              ex: python program.py log_file query_file """)
       # extracting file names from command line
        self.log_file_name=sys.argv[1]
        self.query_file_name = sys.argv[2]

    def read_logfile(self):
        #Reading the log data
        with open(self.log_file_name,'r') as f:
            self.logset = {line.split(' ')[2] for line in f}

    def read_Queryfile(self):
        #Reading the query file into the  dataframe"""
        with open(self.query_file_name,'r') as f:
            self.IPlist = [line.rstrip('\n') for line in f]

    def CheckIpAdress(self):
        #Ip address from query file ae checked against the log file """
        dummy= self.logset.intersection(set(self.IPlist))

        for element in self.IPlist:
            if element in dummy:
                print "1"
            else :
                print "0"

#Create an instance of the IpQuery file
msd=IpQuery()
#Extacting the input file information
msd.Inputfiles()
#Importing the Ip informatin from the log files
msd.read_logfile()
#Importing the Ipquery information from the quer file
msd.read_Queryfile()
#Serching for the Ip in log file
msd.CheckIpAdress()

print "Execution Time of this script is  %f" %(time.time() - start)


text:
// Highlight function
jQuery.fn.extend({
  highlight: function(search, insensitive, hls_class){
    //var regex = new RegExp("(<[^>]*>)|("+ search.replace(/([-.*+?^${}()|[\]\/\\])/i,"\\$1") +")", insensitive ? "i" : "g");
    //Removed (<[^>]*>)| from above regexp to fix the problem of tags in search text
    var regex = new RegExp("("+ search.replace(/([-.*+?^${}()|[\]\/\\])/i,"\\$1") +")", insensitive ? "i" : "g");
    return this.html(this.html().replace(regex, function(a, b, c){
      //return (a.charAt(0) == "<") ? a : "" + c + "";
      return "" + b + "";
    }));
  }
});

// Unwrap function

jQuery.fn.extend({
  unwrap: function(){
    return this.each(function(){
      jQuery(this.childNodes).insertBefore(this);
    }).remove();
  }
});

// jFilter function

jQuery.fn.jfilter = function(o) {

  // Defaults
  /*var o = jQuery.extend({
  list: '#filterable',
	speed: '100',
	highlight: 'highlight'
  },o);*/

  return this.each(function(){
    jQuery(this).keyup(function(){
      var li = jQuery(o.list).hasClass('as_selected_elements_list')? 'li.as_selected' : 'li'
      var str = jQuery(this).val().replace( /<|>/, "" );
      jQuery(this).val(str);
      (str != '') ? jQuery(o.clear_btn).show() : jQuery(o.clear_btn).hide();
      jQuery('.'+o.highlight).unwrap();
      var filter = jQuery(this).val();
      jQuery(o.list + ' ' + li +' p').each(function () {
        if (jQuery(this).text().search(new RegExp(filter, "i")) < 0) {
          jQuery(this.parentNode).fadeOut(o.speed);
        }
        else {
          jQuery(this.parentNode).show();
          jQuery(this).highlight(filter, 1, o.highlight);
        }
      });
    });
  });
};


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RaiseFault async="false" continueOnError="false" enabled="true" name="HPX_RaiseFault_Generic">
    <DisplayName>HPX_RaiseFault_Generic</DisplayName>
    <Description>This policy is used to throw a custom generic error encountered during execution. Specific handling and response payload is set in the fault handlers appropriately.</Description>
    <Properties/>
    <FaultResponse>
        <Set/>
    </FaultResponse>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</RaiseFault>


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

<title>V-Index</title>
<meta name="date" content="2015-06-04">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D E F G I L M O P R S T U V W

V

VNDir - Class in main

VNDir class will ensure that a book and a config file both exist.

VNDir() - Constructor for class main.VNDir

Constructor, will instantiate with config and book file.

VNEnd - Class in main

State of the end

VNEnd(int) - Constructor for class main.VNEnd

Just a state to define this state based game

VNMenu - Class in main

Menu screen

VNMenu(int, VNDir) - Constructor for class main.VNMenu

Constructor.

VNReader - Class in main

Main reader for the VN.

VNReader(int, VNDir) - Constructor for class main.VNReader

Starts off VNReader with path name information with VNDir and its state

VNSound - Class in main

Play sounds with this VNSound tool.

VNSound(File) - Constructor for class main.VNSound

Constructor that starts off the VNSound tool with a sound.

VNSound(File, float) - Constructor for class main.VNSound

Constructor that starts off the VNSound tool with a sound at a certain volume.

VNSound() - Constructor for class main.VNSound

A constructor for those who dont want open any sound and just have a VNSound tool nearby to use.

VNTool - Class in main

Tool to display VN type things onto the screen

VNTool(GameContainer, StateBasedGame, VNSound, VNSound) - Constructor for class main.VNTool

Constructor for VNTool.

A C D E F G I L M O P R S T U V W

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<?php

namespace Vegas\Forms;

use Phalcon\DI;
use Vegas\DI\InjectionAwareTrait;
use Vegas\Forms\Element\AssetsInjectableInterface;
use Vegas\Validation\Validator\PresenceOf;

/**
 * Class BuilderAbstract
 * @package Vegas\Forms
 */
abstract class BuilderAbstract implements BuilderInterface
{
    /**
     * Separator for default name element
     */
    const NAME_SEPARATOR = '-';

    /**
     * Currently built element
     * @var mixed
     */
    protected $element;

    /**
     * Stores fields of record retrieved from database
     * @var InputSettings
     */
    protected $settings;

    /**
     * Stores additional fields
     */
    protected $additionalOptions;

    /**
     * Method for building form element
     * @param InputSettings $settings
     * @return mixed
     */
    public function build(InputSettings $settings)
    {
        $this->settings = $settings;

        $this->setElement();
        $this->setValidator();
        $this->setLabel();
        $this->setDefault();
        $this->setAttributes();
        $this->setData();
        $this->setAdditionalOptions();

        return $this->getElement();
    }

    /**
     * Method sets element and return object instance. Only for form builder purpose.
     * @return mixed
     */
    public function initElement()
    {
        if(is_null($this->settings)) {
            $this->settings = new InputSettings();
        }

        return $this->build($this->settings);
    }

    /**
     * Default setter for dataProvider field
     */
    public function setData() {

    }

    /**
     * Default setter for element validator
     */
    public function setValidator()
    {
        if($this->settings->getValue(InputSettings::REQUIRED_PARAM)) {
            $this->element->addValidator(new PresenceOf());
        }
    }

    /**
     * Default setter for element label
     */
    public function setLabel()
    {
        if($this->settings->getValue(InputSettings::LABEL_PARAM)) {
            $this->element->setLabel($this->settings->getValue(InputSettings::LABEL_PARAM));
        } else {
            $this->element->setLabel(preg_replace('/.*\\\/', '', get_class($this)));
        }
    }

    /**
     * Default setter for element default value
     */
    public function setDefault()
    {
        if($this->settings->getValue(InputSettings::DEFAULTS_PARAM)) {
            $this->element->setDefault($this->settings->getValue(InputSettings::DEFAULTS_PARAM));
        }
    }

    /**
     * Default setter for placeholder attribute
     */
    public function setAttributes()
    {
        if($this->settings->getValue(InputSettings::PLACEHOLDER_PARAM)) {
            $this->element->setAttribute('placeholder',  $this->settings->getValue(InputSettings::PLACEHOLDER_PARAM));
        }
    }

    /**
     * Default setter for extra options
     */
    public function setAdditionalOptions(){ }

    public function getAdditionalOptions()
    {
        return $this->additionalOptions;
    }

    /**
     * Getter for element field
     * @return mixed
     */
    public function getElement()
    {
        return $this->element;
    }

}


text:
package org.elasticsearch.common.unit;

import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.xcontent.XContent;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESTestCase;

import java.io.IOException;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.number.IsCloseTo.closeTo;

public class FuzzinessTests extends ESTestCase {
    public void testNumerics() {
        String[] options = new String[]{"1.0", "1", "1.000000"};
        assertThat(Fuzziness.build(randomFrom(options)).asByte(), equalTo((byte) 1));
        assertThat(Fuzziness.build(randomFrom(options)).asInt(), equalTo(1));
        assertThat(Fuzziness.build(randomFrom(options)).asFloat(), equalTo(1f));
        assertThat(Fuzziness.build(randomFrom(options)).asDouble(), equalTo(1d));
        assertThat(Fuzziness.build(randomFrom(options)).asLong(), equalTo(1l));
        assertThat(Fuzziness.build(randomFrom(options)).asShort(), equalTo((short) 1));
    }

    public void testParseFromXContent() throws IOException {
        final int iters = randomIntBetween(10, 50);
        for (int i = 0; i < iters; i++) {
            {
                XContent xcontent = XContentType.JSON.xContent();
                float floatValue = randomFloat();
                String json = jsonBuilder().startObject()
                        .field(Fuzziness.X_FIELD_NAME, floatValue)
                        .endObject().string();
                XContentParser parser = xcontent.createParser(json);
                assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
                assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
                assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_NUMBER));
                Fuzziness parse = Fuzziness.parse(parser);
                assertThat(parse.asFloat(), equalTo(floatValue));
                assertThat(parse.asDouble(), closeTo(floatValue, 0.000001));
                assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT));
            }
            {
                XContent xcontent = XContentType.JSON.xContent();
                Integer intValue = frequently() ? randomIntBetween(0, 2) : randomIntBetween(0, 100);
                Float floatRep = randomFloat();
                Number value = intValue;
                if (randomBoolean()) {
                    value = new Float(floatRep += intValue);
                }
                String json = jsonBuilder().startObject()
                        .field(Fuzziness.X_FIELD_NAME, randomBoolean() ? value.toString() : value)
                        .endObject().string();
                XContentParser parser = xcontent.createParser(json);
                assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
                assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
                assertThat(parser.nextToken(), anyOf(equalTo(XContentParser.Token.VALUE_NUMBER), equalTo(XContentParser.Token.VALUE_STRING)));
                Fuzziness parse = Fuzziness.parse(parser);
                assertThat(parse.asInt(), equalTo(value.intValue()));
                assertThat((int) parse.asShort(), equalTo(value.intValue()));
                assertThat((int) parse.asByte(), equalTo(value.intValue()));
                assertThat(parse.asLong(), equalTo(value.longValue()));
                if (value.intValue() >= 1) {
                    assertThat(parse.asDistance(), equalTo(Math.min(2, value.intValue())));
                }
                assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT));
                if (intValue.equals(value)) {
                    switch (intValue) {
                        case 1:
                            assertThat(parse, sameInstance(Fuzziness.ONE));
                            break;
                        case 2:
                            assertThat(parse, sameInstance(Fuzziness.TWO));
                            break;
                        case 0:
                            assertThat(parse, sameInstance(Fuzziness.ZERO));
                            break;
                        default:
                            break;
                    }
                }
            }
            {
                XContent xcontent = XContentType.JSON.xContent();
                String json = jsonBuilder().startObject()
                        .field(Fuzziness.X_FIELD_NAME, randomBoolean() ? "AUTO" : "auto")
                        .endObject().string();
                if (randomBoolean()) {
                    json = Fuzziness.AUTO.toXContent(jsonBuilder().startObject(), null).endObject().string();
                }
                XContentParser parser = xcontent.createParser(json);
                assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
                assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
                assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_STRING));
                Fuzziness parse = Fuzziness.parse(parser);
                assertThat(parse, sameInstance(Fuzziness.AUTO));
                assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT));
            }

            {
                String[] values = new String[]{"d", "H", "ms", "s", "S", "w"};
                String actual = randomIntBetween(1, 3) + randomFrom(values);
                XContent xcontent = XContentType.JSON.xContent();
                String json = jsonBuilder().startObject()
                        .field(Fuzziness.X_FIELD_NAME, actual)
                        .endObject().string();
                XContentParser parser = xcontent.createParser(json);
                assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
                assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
                assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_STRING));
                Fuzziness parse = Fuzziness.parse(parser);
                assertThat(parse.asTimeValue(), equalTo(TimeValue.parseTimeValue(actual, null, "fuzziness")));
                assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT));
            }
        }

    }

    public void testAuto() {
        assertThat(Fuzziness.AUTO.asByte(), equalTo((byte) 1));
        assertThat(Fuzziness.AUTO.asInt(), equalTo(1));
        assertThat(Fuzziness.AUTO.asFloat(), equalTo(1f));
        assertThat(Fuzziness.AUTO.asDouble(), equalTo(1d));
        assertThat(Fuzziness.AUTO.asLong(), equalTo(1l));
        assertThat(Fuzziness.AUTO.asShort(), equalTo((short) 1));
        assertThat(Fuzziness.AUTO.asTimeValue(), equalTo(TimeValue.parseTimeValue("1ms", TimeValue.timeValueMillis(1), "fuzziness")));

    }

    public void testAsDistance() {
        final int iters = randomIntBetween(10, 50);
        for (int i = 0; i < iters; i++) {
            Integer integer = Integer.valueOf(randomIntBetween(0, 10));
            String value = "" + (randomBoolean() ? integer.intValue() : integer.floatValue());
            assertThat(Fuzziness.build(value).asDistance(), equalTo(Math.min(2, integer.intValue())));
        }
    }

    public void testSerialization() throws IOException {
        Fuzziness fuzziness = Fuzziness.AUTO;
        Fuzziness deserializedFuzziness = doSerializeRoundtrip(fuzziness);
        assertEquals(fuzziness, deserializedFuzziness);

        fuzziness = Fuzziness.fromEdits(randomIntBetween(0, 2));
        deserializedFuzziness = doSerializeRoundtrip(fuzziness);
        assertEquals(fuzziness, deserializedFuzziness);
    }

    public void testSerializationAuto() throws IOException {
        Fuzziness fuzziness = Fuzziness.AUTO;
        Fuzziness deserializedFuzziness = doSerializeRoundtrip(fuzziness);
        assertEquals(fuzziness, deserializedFuzziness);
        assertEquals(fuzziness.asInt(), deserializedFuzziness.asInt());
    }

    private static Fuzziness doSerializeRoundtrip(Fuzziness in) throws IOException {
        BytesStreamOutput output = new BytesStreamOutput();
        in.writeTo(output);
        StreamInput streamInput = StreamInput.wrap(output.bytes());
        return Fuzziness.readFuzzinessFrom(streamInput);
    }
}


text:
const assert = require('assert')
const request = require('supertest')
const jsonServer = require('../../src/server')

describe('Fake server', () => {
  let server
  let router
  let db

  beforeEach(() => {
    db = {}

    db.user = {
      name: 'foo',
      email: 'foo@example.com',
    }

    server = jsonServer.create()
    router = jsonServer.router(db, { _isFake: true })
    server.use(jsonServer.defaults())
    server.use(router)
  })

  describe('POST /:resource', () => {
    test('should not create resource', async () => {
      const user = { name: 'bar' }
      await request(server).post('/user').send(user).expect(201, user)
      assert.notDeepStrictEqual(db.user, user)
    })
  })

  describe('PUT /:resource', () => {
    test('should not update resource', async () => {
      const user = { name: 'bar' }
      await request(server).put('/user').send(user).expect(200, user)
      assert.notDeepStrictEqual(db.user, user)
    })
  })

  describe('PATCH /:resource', () => {
    test('should not update resource', async () => {
      const user = { name: 'bar' }
      await request(server)
        .patch('/user')
        .send(user)
        .expect(200, { name: 'bar', email: 'foo@example.com' })
      assert.notDeepStrictEqual(db.user, user)
    })
  })
})


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__short_fscanf_add_84.h
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-84.tmpl.h
*/
/*
 * @description
 * CWE: 190 Integer Overflow
 * BadSource: fscanf Read data from the console using fscanf()
 * GoodSource: Set data to a small, non-zero number (two)
 * Sinks: add
 *    GoodSink: Ensure there will not be an overflow before adding 1 to data
 *    BadSink : Add 1 to data, which can cause an overflow
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */

#include "std_testcase.h"

namespace CWE190_Integer_Overflow__short_fscanf_add_84
{

#ifndef OMITBAD

class CWE190_Integer_Overflow__short_fscanf_add_84_bad
{
public:
    CWE190_Integer_Overflow__short_fscanf_add_84_bad(short dataCopy);
    ~CWE190_Integer_Overflow__short_fscanf_add_84_bad();

private:
    short data;
};

#endif /* OMITBAD */

#ifndef OMITGOOD

class CWE190_Integer_Overflow__short_fscanf_add_84_goodG2B
{
public:
    CWE190_Integer_Overflow__short_fscanf_add_84_goodG2B(short dataCopy);
    ~CWE190_Integer_Overflow__short_fscanf_add_84_goodG2B();

private:
    short data;
};

class CWE190_Integer_Overflow__short_fscanf_add_84_goodB2G
{
public:
    CWE190_Integer_Overflow__short_fscanf_add_84_goodB2G(short dataCopy);
    ~CWE190_Integer_Overflow__short_fscanf_add_84_goodB2G();

private:
    short data;
};

#endif /* OMITGOOD */

}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http.Headers;
using System.Windows.Forms;
using UML=TSF.UmlToolingFramework.UML;
using TSF_EA=TSF.UmlToolingFramework.Wrappers.EA;
using EAAddinFramework;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using System.Linq;
using Newtonsoft.Json.Linq;
using WT=WorkTrackingFramework;
using TFS=EAAddinFramework.WorkTracking.TFS;
using EA_WT=EAAddinFramework.WorkTracking;
using EAAddinFramework.Utilities;

namespace EATFSConnector
{
	/// <summary>
	/// Description of MyClass.
	/// </summary>
	public class EATFSConnectorAddin:EAAddinBase
	{
		// define menu constants
        const string menuName = "-&TFS Connector";
        const string menuSynchTFStoEA = "&TFS => EA";
        const string menuSynchEAtoTFS = "&EA => TFS";
        const string menuSettings = "&Settings";
        const string menuSetProject = "Set &Project";
        const string menuGoToTFSWeb = "&Open TFS website";
        const string menuAbout = "&About";

        //private attributes
        private EATFSConnectorSettings settings = new EATFSConnectorSettings();

        /// <summary>
        /// constructor, set menu names
        /// </summary>
        public EATFSConnectorAddin():base()
        {
        	this.menuHeader = menuName;
			this.menuOptions = new string[]{menuSynchTFStoEA,menuSynchEAtoTFS,menuSetProject,menuGoToTFSWeb, menuSettings, menuAbout};
        }
       	/// <summary>
        /// The EA_GetMenuState event enables the Add-In to set a particular menu option to either enabled or disabled. This is useful when dealing with locked packages and other situations where it is convenient to show a menu option, but not enable it for use.
        /// This event is raised just before Enterprise Architect has to show particular menu options to the user. Its use is described in the Define Menu Items topic.
        /// Also look at EA_GetMenuItems.
        /// </summary>
        /// <param name="Repository">An EA.Repository object representing the currently open Enterprise Architect model.
        /// Poll its members to retrieve model data and user interface status information.</param>
        /// <param name="MenuLocation">String representing the part of the user interface that brought up the menu.
        /// Can be TreeView, MainMenu or Diagram.</param>
        /// <param name="MenuName">The name of the parent menu for which sub-items must be defined. In the case of the top-level menu it is an empty string.</param>
        /// <param name="ItemName">The name of the option actually clicked, for example, Create a New Invoice.</param>
        /// <param name="IsEnabled">Boolean. Set to False to disable this particular menu option.</param>
        /// <param name="IsChecked">Boolean. Set to True to check this particular menu option.</param>
		public override void EA_GetMenuState(EA.Repository Repository, string MenuLocation, string MenuName, string ItemName, ref bool IsEnabled, ref bool IsChecked)
		{
			switch (ItemName)
            {
				case menuSetProject:
					IsEnabled = (MenuLocation == "TreeView" && this.model.selectedElement is TSF_EA.Package);
					break;
				case menuSynchTFStoEA:
					IsEnabled = (this.model.selectedElement is TSF_EA.Package
					             && ! (this.model.selectedElement is TSF_EA.RootPackage)
					             || (this.getCurrentWorkitem() != null && this.getCurrentWorkitem().ID.Length > 0));
					break;
				case menuSynchEAtoTFS:
					IsEnabled = (this.model.selectedElement is TSF_EA.Package
					            || this.model.selectedElement is TSF_EA.ElementWrapper);
					break;
				case menuGoToTFSWeb:
					IsEnabled = ( this.getCurrentProject() != null);
					break;
				default:
					base.EA_GetMenuState(Repository, MenuLocation, MenuName, ItemName, ref IsEnabled, ref IsChecked);
					break;
			}
		}
       	/// <summary>
        /// Called when user makes a selection in the menu.
        /// This is your main exit point to the rest of your Add-in
        /// </summary>
        /// <param name="Repository">the repository</param>
        /// <param name="Location">the location of the menu</param>
        /// <param name="MenuName">the name of the menu</param>
        /// <param name="ItemName">the name of the selected menu item</param>
        public override void EA_MenuClick(EA.Repository Repository, string Location, string MenuName, string ItemName)
        {
            switch (ItemName)
            {
            	case menuSynchTFStoEA:
            		synchTFSToEA();
            		break;
                case menuSynchEAtoTFS:
            		sychEAToTFS();
                    break;
                case menuSetProject:
            		setProject();
            		break;
            	case menuGoToTFSWeb:
            		goToTFSWeb();
            		break;
		        case menuAbout :
            		new AboutWindow().ShowDialog(model.mainEAWindow);
		            break;
	            case menuSettings:
		            new TFSConnectorSettingsForm(this.settings,model).ShowDialog(model.mainEAWindow);
	                break;
            }
        }

		void goToTFSWeb()
		{
			try
			{
				string TFSUrl;
				var currentProject = this.getCurrentProject();
				if (currentProject != null)
				{
					var selectedWorkitem = this.getCurrentWorkitem();
					if (selectedWorkitem != null)
					{
						TFSUrl = selectedWorkitem.url;
					}
					else
					{
						TFSUrl = currentProject.url;
					}
					//open url
					Process.Start(TFSUrl);
				}
				else
				{
					MessageBox.Show("No TFS project found","No TFS Project",MessageBoxButtons.OK,MessageBoxIcon.Error);
				}
			}
			catch(Exception e)
        	{
        		Logger.logError("Error Message: " + e.Message + Environment.NewLine + "Stacktrace: " + e.StackTrace);
        		MessageBox.Show("An error occured: " + e.Message + Environment.NewLine +
        		                "Please check the logfile at: " + Logger.logFileName,"TFS Connector Error"
        		                ,MessageBoxButtons.OK,MessageBoxIcon.Error);
        	}

		}
		private TFS.TFSWorkItem getCurrentWorkitem()
		{
			var currentProject = this.getCurrentProject();
			if (currentProject != null)
			{
				 var selectedItem = this.model.selectedElement as TSF_EA.ElementWrapper;
				//check if the type or the stereotype corresponds to one of the mapped elementtypes or stereotypes
				if (selectedItem != null &&
				    ( this.settings.mappedElementTypes.Contains(selectedItem.EAElementType)
				     || this.settings.mappedStereotypes.Any(selectedItem.stereotypeNames.Contains)
				    ))
				{
					return new TFS.TFSWorkItem(currentProject,selectedItem);
				}
			}
			//no project or no appropriate selected element
			return null;
		}

		void sychEAToTFS()
		{
			try
			{
				var results = new Dictionary<WT.Workitem, bool>();
				//if a package is selected then synchronize all owned workitems
				var selectedPackage = this.model.selectedItem as UML.Classes.Kernel.Package;
				if (selectedPackage != null)
				{
					var currentProject = this.getCurrentProject();
					if (currentProject != null)
					{
						foreach (TFS.TFSWorkItem ownedWorkItem in currentProject.getOwnedWorkitems(selectedPackage, true))
						{
							results.Add(ownedWorkItem, ownedWorkItem.synchronizeToTFS());
						}
					}
				}
				//if a workitem was selected then synchronize this single workitem
				var currentWorkitem = getCurrentWorkitem();
				if (currentWorkitem != null)
				{
					results.Add(currentWorkitem,currentWorkitem.synchronizeToTFS());
				}
				//tell the user what happened
				MessageBox.Show(string.Format("{0} workitems were succesfully synchronized\n{1} workitems could not be synchronized"
				                              , results.Count(x => x.Value), results.Count(x => !x.Value)),"Synchronize to EA => TFS result",MessageBoxButtons.OK,MessageBoxIcon.Information);
			}
			catch(Exception e)
        	{
				if (!(e is OperationCanceledException))
				{
	        		Logger.logError("Error Message: " + e.Message + Environment.NewLine + "Stacktrace: " + e.StackTrace);
	        		MessageBox.Show("An error occured: " + e.Message + Environment.NewLine +
	        		                "Please check the logfile at: " + Logger.logFileName,"TFS Connector Error"
	        		                ,MessageBoxButtons.OK,MessageBoxIcon.Error);
				}
        	}
		}

        private void synchTFSToEA()
        {
        	try
	        {
	        	var results = new Dictionary<WT.Workitem, bool>();
	    		//get a list of all workitems of a certain type
	    		var currentProject = getCurrentProject();
	    		//get the workitems is project was found
	    		if (currentProject != null)
	    		{
	    			//get the selected package
	    			var selectedPackage = this.model.selectedItem as TSF_EA.Package;
	    			if (selectedPackage != null)
	    			{
	        			var selectImportTypes = new SelectImportTypesForm(this.settings);
	        			if (selectImportTypes.ShowDialog(this.model.mainEAWindow) == DialogResult.OK)
	        			{
	        				if (selectImportTypes.allTypes)
	        				{
	        					//import all types
	        					foreach (EA_WT.WorkItem workitem in currentProject.workitems)
	        					{
	        						if (settings.workitemMappings.Any(x => x.Value.Equals(workitem.type, StringComparison.InvariantCultureIgnoreCase)))
	        						{
		        						var mapping = settings.workitemMappings.First(x => x.Value.Equals(workitem.type, StringComparison.InvariantCultureIgnoreCase));
		        						results.Add(workitem, workitem.synchronizeToEA(selectedPackage,mapping.Key));
	        						}
	        					}
	        				}
	        				else
	        				{
	        					//import only the selected type
			        			foreach (EA_WT.WorkItem workitem in currentProject.workitems
			        			         .Where(x => x.type.Equals(selectImportTypes.TFSWorkitemType,StringComparison.InvariantCultureIgnoreCase)))
			        			{
		        					results.Add(workitem, workitem.synchronizeToEA(selectedPackage,selectImportTypes.SparxType));
			        			}
	        				}
	        			}
	    			}
	    			else
	    			{
	    				var currentWorkitem = this.getCurrentWorkitem();
	    				if (currentWorkitem.ID.Length > 0)
	    				{
	    					results.Add(currentWorkitem,currentWorkitem.synchronizeToEA());
	    				}
	    			}
	    		}
	    		//tell the user what happened
				MessageBox.Show(string.Format("{0} workitems were succesfully synchronized \n{1} workitems could not be synchronized"
			                              , results.Count(x => x.Value), results.Count(x => !x.Value)),"Synchronize TFS => EA result",MessageBoxButtons.OK,MessageBoxIcon.Information);
        	}
        	catch(Exception e)
        	{
        		if (!(e is OperationCanceledException))
				{
	        		Logger.logError("Error Message: " + e.Message + Environment.NewLine + "Stacktrace: " + e.StackTrace);
	        		MessageBox.Show("An error occured: " + e.Message + Environment.NewLine +
	        		                "Please check the logfile at: " + Logger.logFileName,"TFS Connector Error"
	        		                ,MessageBoxButtons.OK,MessageBoxIcon.Error);
        		}
        	}
        }

		void setProject()
		{

			var currentProject = getCurrentProject();
			var projectForm = new SetProjectForm();
			if (currentProject != null) projectForm.projectName = currentProject.name;

			//set on root node
			var selectedRoot = this.model.selectedItem as TSF_EA.RootPackage;
			if (selectedRoot != null)
			{
				if (projectForm.ShowDialog(model.mainEAWindow) == DialogResult.OK
				   && projectForm.projectName.Length > 0)
				{
					selectedRoot.notes = "project=" + projectForm.projectName;
					selectedRoot.save();
				}
			}
			else
			{
				//set on package
				var selectedPackage = this.model.selectedItem as TSF_EA.Package;
				if (selectedPackage != null)
				{
					if (projectForm.ShowDialog(model.mainEAWindow) == DialogResult.OK
					   && projectForm.projectName.Length > 0)
					{
						selectedPackage.addTaggedValue("project",projectForm.projectName);
					}
				}
			}
		}
		/// <summary>
		/// returns the project based on the currently selected element.
		/// </summary>
		/// <returns>the TFSProject based on the currently selected item</returns>
        private TFS.TFSProject getCurrentProject()
        {
			var currentProject = TFS.TFSProject.getCurrentProject(this.model.selectedElement as TSF_EA.Element,this.settings.getTFSUrl(this.model),this.settings);
			if (currentProject == null)
			{
        		//if not found return default project
        		currentProject = new TFS.TFSProject(settings.defaultProject,this.settings.getTFSUrl(this.model),this.settings);
			}
			return currentProject;
        }

	}

}


text:
package org.hightides.annotations.processor;

import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.hightides.annotations.util.NamingUtil;
import org.opentides.util.FileUtil;

/**
 * This class is responsible in updating the message property file.
 * @author allantan
 *
 */
public class MessagePropertyProcessor implements Processor {

	private static Logger _log = Logger.getLogger(MessagePropertyProcessor.class);
	private static final String messageFilename = "src/resources/languages/messages.properties";

	/* (non-Javadoc)
	 * @see org.hightides.annotations.processor.Processor#execute(java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	public void execute(Map<String, Object> params) {

		// process only when @Page annotation
		if (!"org.hightides.annotations.Page".equals(params.get("annotation"))) {
			return;
		}
		// read the property files
		Properties origProps = FileUtil.readProperty(messageFilename);

		// add model name label
		Properties newProps = new Properties();
		String prefix = "label."+NamingUtil.toElementName((String)params.get("modelName"))+".";
		String key = prefix.substring(0, prefix.length()-1); // remove the dot
		String label  = (String)params.get("label");
		if (label == null)
			label = (String) params.get("className");
		if (!origProps.containsKey(key) || !label.equals(origProps.get(prefix))) {
			newProps.put(key, label);
		}

		// retrieve the message keys and values
		List<Map<String,Object>> fieldParams = (List<Map<String,Object>>) params.get("fields");
		for (Map<String,Object> props:fieldParams) {
			key   = prefix+props.get("fieldName");
			label = (String) props.get("label");
			if (label == null)
				label = NamingUtil.toLabel((String)props.get("fieldName"));
			// update only when changes exist
			if (!origProps.containsKey(key) || !label.equals(origProps.get(key))) {
				newProps.put(key, label);
			}
			// add model name with field name when field is numeric or a date field
			if ((Boolean)props.get("isNumeric") != null || (Boolean)props.get("isDate") != null) {
				key = NamingUtil.toElementName((String)params.get("modelName"))+"."+props.get("fieldName");
				// update only when changes exist
				if (!origProps.containsKey(key) || !label.equals(origProps.get(key)))
					newProps.put(key, label);
			}
		}
		if (newProps.size()==0) {
			// no update needed
			_log.info("No update on message property necessary.");
			return;
		}
		// add to property file
		origProps.putAll(newProps);
		// backup property file
		FileUtil.backupFile(messageFilename);
		// save property file
		FileUtil.saveProperty(messageFilename, origProps, "Saved by Hightides for message generation.");
		_log.info("Updated message property file with "+newProps.size()+ " key/value pairs.");
	}
}


text:
FROM appcelerator/grafana:grafana-5.0.4
ENV FORCE_HOSTNAME	auto
ENV GRAFANA_PLUGIN_LIST  "grafana-piechart-panel"
ENV ENABLE_AUTH_ANONYMOUS "true"

COPY config /etc/extra-config/grafana


text:
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/classes'

describe "StringIO#close" do
  before(:each) do
    @io = StringIOSpecs.build
  end

  it "returns nil" do
    @io.close.should be_nil
  end

  it "prevents further reading and/or writing" do
    @io.close
    lambda { @io.read(1) }.should raise_error(IOError)
    lambda { @io.write('x') }.should raise_error(IOError)
  end

  it "raises an IOError when self was already closed" do
    @io.close
    lambda { @io.close }.should raise_error(IOError)
  end
end