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

    <string name="app_name">Yahtzee</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_board">Game Board</string>

    <!--rows-->
    <string name="ones">Ones</string>
    <string name="twos">Twos</string>
    <string name="threes">Threes</string>
    <string name="fours">Fours</string>
    <string name="fives">Fives</string>
    <string name="sixes">Sixes</string>

    <string name="max">Max</string>
    <string name="min">Min</string>

    <string name="straight">Straight</string>
    <string name="full">Full</string>
    <string name="poker">Poker</string>
    <string name="yahtzee">Yahtzee</string>
    <!--rows-END-->

    <string name="sumCategory">Sum</string>
    <string name="zeroSum">0</string>

    <!--Main-Activity-->
    <string name="play">PLAY</string>
    <string name="playerName">Player</string>
    <string name="plusSign">+</string>

    <string name="nextPlayerBtn">Next Player</string>

</resources>


text:
'use strict';

trckrApp
  .controller('FuellingCtrl', ['$scope', '$window', '$location', 'dataService', 'authService', function ($scope, $window, $location, dataService, authService) {

    // secured page, check if user is logged in
    if( !authService.logged() ) {
      $location.url('login');
      return;
    }

    // set page title
    $window.document.title = 'Fuelling | Trckr';

    // clear form's elements
    var initForm = function() {
      // init fuelling object
      $scope.fuelling = {};

      // select default country
      $scope.countries = dataService.getCountries();
      $scope.fuelling.country = $scope.countries[0];

      // select default state
      $scope.updateValues($scope.fuelling.country);

      // set default date for today
      $scope.fuelling.date = new Date();

      // load all fuellings
      $scope.fuellings = dataService.getAllFuellings();
    };

    // updates states and volume types based on country
    $scope.updateValues = function(country) {
      $scope.states = dataService.getStates(country);
      $scope.fuelling.state = $scope.states[0];

      $scope.fuelling.volumeType = dataService.getVolumeType(country);
    }

    // saves fuelling to database
    $scope.submitFuelling = function(fuelling, form) {
      if( form.$valid ) {
        // if form is valid then save to database
        dataService.addFuelling(fuelling).then(
          function(response) {
            initForm();
          });
      }
    }

    // return full state name
    $scope.fullStateName = function(state) {
      return state.abbreviation + ' - ' + state.name;
    }

    initForm();

  }]);

redpajama_set_name: RedPajamaGithub


text:
package com.github.designpattern.abstractfactory;

/**
 * Abstract Factory.
 *
 * @author Lubing Zhang
 *
 */
public class ProductA1 extends AbstractProductA {

	@Override
	public void show() {
		System.out.println("Product A1");
	}

}


text:
def measure num=1
#http://www.ruby-doc.org/core-2.1.1/Time.html for reference
#
total=0

num.times do
   start=Time.now
       yield
   ending=Time.now
   total+=ending-start
end

avg=total/num

end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace dgMicMute
{
    /// <summary>
    /// Creates a window to receive and dispatch WM_HOTKEY messages.
    /// Also now does the same for WM_DEVICECHANGE messages to detect when mics are added/removed, so it might make sense to rename the class.
    /// </summary>
    public sealed class KeyboardHook : IDisposable
    {
        // Registers a hot key with Windows.
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
        // Unregisters the hot key with Windows.
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        /// <summary>
        /// Represents the window that is used internally to get the messages.
        /// </summary>
        private class Window : NativeWindow, IDisposable
        {
            private static int WM_HOTKEY = 0x0312;
            private static int WM_DEVICECHANGE = 0x0219;

            public Window()
            {
                // create the handle for the window.
                this.CreateHandle(new CreateParams());
            }

            /// <summary>
            /// Overridden to get the notifications.
            /// </summary>
            /// <param name="m"></param>
            protected override void WndProc(ref Message m)
            {
                base.WndProc(ref m);

                // check if we got a hot key pressed.
                if (m.Msg == WM_HOTKEY)
                {
                    // get the keys.
                    Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
                    ModifierKeys modifier = (ModifierKeys)((int)m.LParam & 0xFFFF);

                    // invoke the event to notify the parent.
                    if (KeyPressed != null)
                        KeyPressed(this, new KeyPressedEventArgs(modifier, key));
                }
                else if (m.Msg == WM_DEVICECHANGE)
				{
                    if (DevicesChanged != null)
					{
                        DevicesChanged(this, null);
					}
				}
            }

            public event EventHandler<KeyPressedEventArgs> KeyPressed;
            public event EventHandler DevicesChanged;

            #region IDisposable Members

            public void Dispose()
            {
                this.DestroyHandle();
            }

            #endregion
        }

        private Window _window = new Window();
        private int _currentId;

        public KeyboardHook()
        {
            // register the event of the inner native window.
            _window.KeyPressed += delegate(object sender, KeyPressedEventArgs args)
            {
                if (KeyPressed != null)
                    KeyPressed(this, args);
            };
            _window.DevicesChanged += delegate (object sender, EventArgs args)
            {
                if (DevicesChanged != null)
                    DevicesChanged(this, args);
            };
        }

        /// <summary>
        /// Registers a hot key in the system.
        /// </summary>
        /// <param name="modifier">The modifiers that are associated with the hot key.</param>
        /// <param name="key">The key itself that is associated with the hot key.</param>
        public void RegisterHotKey(ModifierKeys modifier, Keys key)
        {
            // increment the counter.
            _currentId = _currentId + 1;

            // register the hot key.
            if (!RegisterHotKey(_window.Handle, _currentId, (uint)modifier, (uint)key))
            {
                _currentId--;
                //Settings.UsesHotkey = false; // Turn this off so we don't try to register it again until the user reconfigures the settings
                int errorCode = Marshal.GetLastWin32Error();
                //throw new InvalidOperationException($"Couldn't register the hot key.  Error code: {errorCode}", new Win32Exception(errorCode));
                throw new Win32Exception(errorCode);
            }
        }

        /// <summary>
        /// A hot key has been pressed.
        /// </summary>
        public event EventHandler<KeyPressedEventArgs> KeyPressed;
        public event EventHandler DevicesChanged;

        #region IDisposable Members

        public void Dispose()
        {
            UnregisterHotkeys();

            // dispose the inner native window.
            _window.Dispose();
        }

        public void UnregisterHotkeys()
        {
            // unregister all the registered hot keys.
            for (int i = _currentId; i > 0; i--)
            {
                UnregisterHotKey(_window.Handle, i);
            }
            _currentId = 0;
        }

        #endregion
    }

    /// <summary>
    /// Event Args for the event that is fired after the hot key has been pressed.
    /// </summary>
    public class KeyPressedEventArgs : EventArgs
    {
        private ModifierKeys _modifier;
        private Keys _key;

        internal KeyPressedEventArgs(ModifierKeys modifier, Keys key)
        {
            _modifier = modifier;
            _key = key;
        }

        public ModifierKeys Modifier
        {
            get { return _modifier; }
        }

        public Keys Key
        {
            get { return _key; }
        }
    }

    /// <summary>
    /// The enumeration of possible modifiers.
    /// </summary>
    [Flags]
    public enum ModifierKeys : uint
    {
        None = 0,
        Alt = 1,
        Control = 2,
        Shift = 4,
        Win = 8
    }
}


text:
<?php

namespace Mhor\MediaInfo\Parser;

use Mhor\MediaInfo\Builder\MediaInfoContainerBuilder;
use Mhor\MediaInfo\Container\MediaInfoContainer;
use Mhor\MediaInfo\Exception\MediainfoOutputParsingException;
use Mhor\MediaInfo\Exception\UnknownTrackTypeException;

class MediaInfoOutputParser extends AbstractXmlOutputParser
{
    /**
     * @var array
     */
    private $parsedOutput;

    /**
     * @param string $output
     */
    public function parse(string $output): void
    {
        $this->parsedOutput = $this->transformXmlToArray($output);
    }

    /**
     * @param bool $ignoreUnknownTrackTypes Optional parameter used to skip unknown track types by passing true. The
     *                                      default behavior (false) is throw an exception on unknown track types.
     *
     * @return MediaInfoContainer
     */
    public function getMediaInfoContainer(bool $ignoreUnknownTrackTypes = false): \Mhor\MediaInfo\Container\MediaInfoContainer
    {
        if ($this->parsedOutput === null) {
            throw new \Exception('You must run `parse` before running `getMediaInfoContainer`');
        }

        $mediaInfoContainerBuilder = new MediaInfoContainerBuilder();
        $mediaInfoContainerBuilder->setVersion($this->parsedOutput['@attributes']['version']);

        if (!array_key_exists('File', $this->parsedOutput)) {
            throw new MediainfoOutputParsingException(
                'XML format of mediainfo >=17.10 command has changed, check php-mediainfo documentation'
            );
        }

        foreach ($this->parsedOutput['File']['track'] as $trackType) {
            try {
                if (isset($trackType['@attributes']['type'])) {
                    $mediaInfoContainerBuilder->addTrackType($trackType['@attributes']['type'], $trackType);
                }
            } catch (UnknownTrackTypeException $ex) {
                if (!$ignoreUnknownTrackTypes) {
                    // rethrow exception
                    throw $ex;
                }
                // else ignore
            }
        }

        return $mediaInfoContainerBuilder->build();
    }
}


text:
package org.apache.http.HC4.conn;

import org.apache.http.HC4.HttpHost;

/**
 * Strategy for default port resolution for protocol schemes.
 *
 * @since 4.3
 */
public interface SchemePortResolver {

    /**
     * Returns the actual port for the host based on the protocol scheme.
     */
    int resolve(HttpHost host) throws UnsupportedSchemeException;

}


text:
Personal Website
=========================

Using Jekyll.

=========
For more details, read the [documentation](http://jekyllrb.com/)


text:
#import "UIViewController.h"

#import "TKVibrationRecorderViewDelegate-Protocol.h"
#import "UIAlertViewDelegate-Protocol.h"
#import "UITextFieldDelegate-Protocol.h"

@class NSDictionary, TKVibrationRecorderView, TKVibrationRecorderViewController, TKVibratorController, TLVibrationPattern, UIAlertView, UIBarButtonItem;

@interface TKVibrationRecorderContentViewController : UIViewController <TKVibrationRecorderViewDelegate, UIAlertViewDelegate, UITextFieldDelegate>
{
    _Bool _waitingForEndOfCurrentVibrationComponent;
    int _mode;
    id <TKVibrationRecorderViewControllerDelegate> _delegate;
    TKVibrationRecorderViewController *_parentVibrationRecorderViewController;
    UIBarButtonItem *_cancelButton;
    UIBarButtonItem *_saveButton;
    UIAlertView *_vibrationNameAlertView;
    TKVibratorController *_vibratorController;
    NSDictionary *_indefiniteVibrationPattern;
    TKVibrationRecorderView *_vibrationRecorderView;
    TLVibrationPattern *_recordedVibrationPattern;
    double _currentVibrationComponentDidStartTimeStamp;
    double _currentVibrationProgressDidStartTimestamp;
}

@property(nonatomic, getter=_isWaitingForEndOfCurrentVibrationComponent, setter=_setWaitingForEndOfCurrentVibrationComponent:) _Bool _waitingForEndOfCurrentVibrationComponent; // @synthesize _waitingForEndOfCurrentVibrationComponent;
@property(nonatomic, setter=_setCurrentVibrationProgressDidStartTimestamp:) double _currentVibrationProgressDidStartTimestamp; // @synthesize _currentVibrationProgressDidStartTimestamp;
@property(nonatomic, setter=_setCurrentVibrationComponentDidStartTimeStamp:) double _currentVibrationComponentDidStartTimeStamp; // @synthesize _currentVibrationComponentDidStartTimeStamp;
@property(retain, nonatomic, setter=_setRecordedVibrationPattern:) TLVibrationPattern *_recordedVibrationPattern; // @synthesize _recordedVibrationPattern;
@property(retain, nonatomic, setter=_setVibrationRecorderView:) TKVibrationRecorderView *_vibrationRecorderView; // @synthesize _vibrationRecorderView;
@property(nonatomic, setter=_setMode:) int _mode; // @synthesize _mode;
@property(retain, nonatomic, setter=_setIndefiniteVibrationPattern:) NSDictionary *_indefiniteVibrationPattern; // @synthesize _indefiniteVibrationPattern;
@property(retain, nonatomic, setter=_setVibratorController:) TKVibratorController *_vibratorController; // @synthesize _vibratorController;
@property(retain, nonatomic, setter=_setVibrationNameAlertView:) UIAlertView *_vibrationNameAlertView; // @synthesize _vibrationNameAlertView;
@property(retain, nonatomic, setter=_setSaveButton:) UIBarButtonItem *_saveButton; // @synthesize _saveButton;
@property(retain, nonatomic, setter=_setCancelButton:) UIBarButtonItem *_cancelButton; // @synthesize _cancelButton;
@property(nonatomic) TKVibrationRecorderViewController *parentVibrationRecorderViewController; // @synthesize parentVibrationRecorderViewController=_parentVibrationRecorderViewController;
@property(nonatomic) id <TKVibrationRecorderViewControllerDelegate> delegate; // @synthesize delegate=_delegate;
- (void)_accessibilityDidExitReplayMode;
- (void)_accessibilityDidEnterReplayMode;
- (void)_accessibilityDidExitRecordingMode;
- (void)_accessibilityDidEnterRecordingMode;
- (void)_accessibilityMakeAnnouncementWithStringForLocalizationIdentifier:(id)arg1;
- (void)_finishedWithRecorder;
- (void)vibrationRecorderViewDidReachVibrationRecordingMaximumDuration:(id)arg1;
- (void)vibrationRecorderView:(id)arg1 didExitRecordingModeWithContextObject:(id)arg2;
- (_Bool)vibrationRecorderViewDidEnterRecordingMode:(id)arg1;
- (void)vibrationRecorderViewDidFinishReplayingVibration:(id)arg1;
- (void)vibrationRecorderView:(id)arg1 buttonTappedWithIdentifier:(int)arg2;
- (void)vibrationComponentDidEndForVibrationRecorderView:(id)arg1;
- (void)vibrationComponentDidStartForVibrationRecorderView:(id)arg1;
- (void)_eraseCurrentVibrationComponentDidStartTimeStamp;
- (void)_storeVibrationComponentOfTypePause:(_Bool)arg1;
- (void)_stopVibrating;
- (void)_startVibratingWithVibrationPattern:(id)arg1;
- (void)alertView:(id)arg1 clickedButtonAtIndex:(long long)arg2;
- (_Bool)textFieldShouldReturn:(id)arg1;
- (_Bool)textField:(id)arg1 shouldChangeCharactersInRange:(struct _NSRange)arg2 replacementString:(id)arg3;
- (void)_textFieldTextDidChange:(id)arg1;
- (void)_saveButtonTapped:(id)arg1;
- (void)_cancelButtonTapped:(id)arg1;
- (unsigned long long)supportedInterfaceOrientations;
- (void)willRotateToInterfaceOrientation:(long long)arg1 duration:(double)arg2;
- (void)viewDidDisappear:(_Bool)arg1;
- (void)viewWillAppear:(_Bool)arg1;
- (void)viewWillDisappear:(_Bool)arg1;
- (void)viewDidAppear:(_Bool)arg1;
- (void)loadView;
- (void)dealloc;
- (id)initWithVibratorController:(id)arg1;

@end


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- Copyright 2017-2022 Steinar Bang                                     -->
<!--                                                                      -->
<!-- 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.                                       -->

<features xmlns="http://karaf.apache.org/xmlns/features/v1.4.0" name="ukelonn.bundle.db.liquibase">
    <feature name="liquibase-core" start-level="40" version="${liquibase.version}">
        <feature>aries-proxy</feature>
        <bundle>mvn:org.apache.aries.spifly/org.apache.aries.spifly.dynamic.bundle/1.3.4</bundle>
        <bundle>mvn:org.yaml/snakeyaml/${snakeyaml.version}</bundle>
        <bundle>mvn:org.liquibase/liquibase-core/${liquibase.version}</bundle>
    </feature>
</features>


text:
package org.artifactory.ui.rest.service.utils.predefinevalues;

import org.artifactory.api.repo.RepositoryService;
import org.artifactory.descriptor.property.PredefinedValue;
import org.artifactory.descriptor.property.Property;
import org.artifactory.descriptor.property.PropertySet;
import org.artifactory.descriptor.repo.LocalRepoDescriptor;
import org.artifactory.repo.InternalRepoPathFactory;
import org.artifactory.repo.RepoPath;
import org.artifactory.rest.common.service.ArtifactoryRestRequest;
import org.artifactory.rest.common.service.RestResponse;
import org.artifactory.rest.common.service.RestService;
import org.artifactory.ui.rest.model.utils.predefinevalues.PreDefineValues;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Chen Keinan
 */
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class GetPreDefineValuesService implements RestService {

    @Autowired
    private RepositoryService repoService;

    @Override
    public void execute(ArtifactoryRestRequest request, RestResponse response) {
        String repoKey = request.getQueryParamByKey("repoKey");
        String path = request.getQueryParamByKey("path");
        String name = request.getPathParamByKey("name");
        RepoPath repoPath = InternalRepoPathFactory.create(repoKey, path);
        PreDefineValues values = new PreDefineValues();
        Map<String, Property> propertyItemMap = createPropertyItemMap(repoPath);
        if(!propertyItemMap.isEmpty()) {
            List<PredefinedValue> predefinedValues = propertyItemMap.get(name).getPredefinedValues();
            List<String> listOfPredefineValuesAsString = new ArrayList<>();
            List<String> selectedValues = new ArrayList<>();
            predefinedValues.forEach(predefinedValue -> {
                if (predefinedValue.isDefaultValue()) {
                    selectedValues.add(predefinedValue.getValue());
                } else {
                    listOfPredefineValuesAsString.add(predefinedValue.getValue());
                }
            });
            values.setSelectedValues(selectedValues);
            values.setPredefinedValues(listOfPredefineValuesAsString);
        }
        response.iModel(values);
    }

    /**
     * create property map by repo path
     * @param repoPath - repo path
     * @return map of properties
     */
    private Map<String, Property> createPropertyItemMap(RepoPath repoPath) {
        Map<String, Property> propertyItemMap = new HashMap<>();
        LocalRepoDescriptor descriptor = repoService.localOrCachedRepoDescriptorByKey(repoPath.getRepoKey());
        List<PropertySet> propertySets = new ArrayList<>(descriptor.getPropertySets());
        for (PropertySet propertySet : propertySets) {
            List<Property> propertyList = propertySet.getProperties();
            for (Property property : propertyList) {
                propertyItemMap.put(propertySet.getName()+"."+property.getName(), property);
            }
        }
        return propertyItemMap;
    }
}


text:
package com.groboot.pushapps;

public class PushAppsNotification {
	private String message;
	private String title;
	private int sound;
	private int icon;
	private boolean hasVibrate = false;
	private String link;

	public PushAppsNotification setLink(String link) {
		this.link = link;
		return this;
	}

	public String getLink() {
		return link;
	}

	public boolean isHasVibrate() {
		return hasVibrate;
	}

	public PushAppsNotification setHasVibrate(boolean hasVibrate) {
		this.hasVibrate = hasVibrate;
		return this;
	}

	public String getMessage() {
		return message;
	}

	public PushAppsNotification setMessage(String message) {
		this.message = message;
		return this;
	}

	public String getTitle() {
		return title;
	}

	public PushAppsNotification setTitle(String title) {
		this.title = title;
		return this;
	}

	public int getSound() {
		return sound;
	}

	public PushAppsNotification setSound(int sound) {
		this.sound = sound;
		return this;
	}

	public int getIcon() {
		return icon;
	}

	public PushAppsNotification setIcon(int icon) {
		this.icon = icon;
		return this;
	}

}


text:
- Decent documentation

## 0.1.0
The majority of functionality has been implemented:
- pre() and post() hooks for surrounding a function.
- removePre() and removePost() for removing existing hooks.
- Support for asynchronous functions where the callback will be called after all hooks have completed (pre and post).
- Support for complex prototypal inheritance by binding hooks to functions (within both Object or Object.prototype).
- Pass an Error to next() from within any hook to halt the hook chain.
- trigger() for manually firing a function's hooks without invoking that function directly.


text:
package org.scalajs.jsenv.phantomjs

import javax.servlet.http.HttpServletRequest

import org.eclipse.jetty.server.Server
import org.eclipse.jetty.server.nio.SelectChannelConnector
import org.eclipse.jetty.websocket.{WebSocket, WebSocketHandler}
import org.eclipse.jetty.util.component.{LifeCycle, AbstractLifeCycle}
import org.eclipse.jetty.util.log

final class JettyWebsocketManager(
    wsListener: WebsocketListener) extends WebsocketManager { thisMgr =>

  private[this] var webSocketConn: WebSocket.Connection = null
  private[this] var closed = false

  // We can just set the logger here, since we are supposed to be protected by
  // the private ClassLoader that loads us reflectively.
  log.Log.setLog(new WSLogger("root"))

  private[this] val connector = new SelectChannelConnector

  connector.setHost("localhost")
  connector.setPort(0)

  private[this] val server = new Server()

  server.addConnector(connector)
  server.setHandler(new WebSocketHandler {
    // Support Hixie 76 for Phantom.js
    getWebSocketFactory().setMinVersion(-1)

    override def doWebSocketConnect(
        request: HttpServletRequest, protocol: String): WebSocket =
      new ComWebSocketListener
  })

  server.addLifeCycleListener(new AbstractLifeCycle.AbstractLifeCycleListener {
    override def lifeCycleStarted(event: LifeCycle): Unit = {
      if (event.isRunning())
        wsListener.onRunning()
    }
  })

  private class ComWebSocketListener extends WebSocket.OnTextMessage {
    override def onOpen(connection: WebSocket.Connection): Unit = {
      thisMgr.synchronized {
        if (isConnected)
          throw new IllegalStateException("Client connected twice")
        webSocketConn = connection
      }
      wsListener.onOpen()
    }

    override def onClose(statusCode: Int, reason: String): Unit = {
      thisMgr.synchronized {
        webSocketConn = null
        closed = true
      }
      wsListener.onClose()
      server.stop()

      if (statusCode != 1000) {
        throw new Exception("Abnormal closing of connection. " +
            s"Code: $statusCode, Reason: $reason")
      }
    }

    override def onMessage(message: String): Unit =
      wsListener.onMessage(message)
  }

  private class WSLogger(fullName: String) extends log.AbstractLogger {
    private[this] var debugEnabled = false

    def debug(msg: String, args: Object*): Unit =
      if (debugEnabled) log("DEBUG", msg, args)

    def debug(msg: String, thrown: Throwable): Unit =
      if (debugEnabled) log("DEBUG", msg, thrown)

    def debug(thrown: Throwable): Unit =
      if (debugEnabled) log("DEBUG", thrown)

    def getName(): String = fullName

    def ignore(ignored: Throwable): Unit = ()

    def info(msg: String, args: Object*): Unit = log("INFO", msg, args)
    def info(msg: String, thrown: Throwable): Unit = log("INFO", msg, thrown)
    def info(thrown: Throwable): Unit = log("INFO", thrown)

    def warn(msg: String, args: Object*): Unit = log("WARN", msg, args)
    def warn(msg: String, thrown: Throwable): Unit = log("WARN", msg, thrown)
    def warn(thrown: Throwable): Unit = log("WARN", thrown)

    def isDebugEnabled(): Boolean = debugEnabled
    def setDebugEnabled(enabled: Boolean): Unit = debugEnabled = enabled

    private def log(lvl: String, msg: String, args: Object*): Unit =
      wsListener.log(s"$lvl: $msg " + args.mkString(", "))

    private def log(lvl: String, msg: String, thrown: Throwable): Unit =
      wsListener.log(s"$lvl: $msg $thrown\n{$thrown.getStackStrace}")

    private def log(lvl: String, thrown: Throwable): Unit =
      wsListener.log(s"$lvl: $thrown\n{$thrown.getStackStrace}")

    protected def newLogger(fullName: String) = new WSLogger(fullName)
  }

  def start(): Unit = server.start()

  def stop(): Unit = server.stop()

  def isConnected: Boolean = webSocketConn != null && !closed
  def isClosed: Boolean = closed

  def localPort: Int = connector.getLocalPort()

  def sendMessage(msg: String) = synchronized {
    if (webSocketConn != null)
      webSocketConn.sendMessage(msg)
  }

}


text:
namespace mtg {

void addTargetPlayer(StackObject & so, Player & player)
{
    so.targets.emplace(TargetType::player,std::unique_ptr<Target>(new TargetPlayer(&player)));
}

void addTargetLibrary(StackObject & so, Player & owner)
{
    so.targets.emplace(TargetType::library,std::unique_ptr<Target>(new TargetLibrary(&owner)));
}

void addTargetPermanent(StackObject & so, PermanentIt permIt)
{
    so.targets.emplace(TargetType::permanent,std::unique_ptr<Target>(new TargetPermanent(permIt)));
}

void addTargetCard(StackObject & so, CardRef card)
{
    so.targets.emplace(TargetType::card,std::unique_ptr<Target>(new TargetCard(card)));
}

void addTargetStackObject(StackObject & so, Stack::iterator obj)
{
    so.targets.emplace(TargetType::stack,std::unique_ptr<Target>(new TargetStackObject(obj)));
}

}


text:
package eu.chargetime.ocpp.model.test;

import eu.chargetime.ocpp.model.core.HeartbeatConfirmation;
import org.junit.Before;
import org.junit.Test;

import java.util.Calendar;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class HeartbeatConfirmationTest {
    HeartbeatConfirmation confirmation;

    @Before
    public void setUp() throws Exception {
        confirmation = new HeartbeatConfirmation();
    }

    @Test
    public void setCurrentTime_now_currentTimeIsSet() {
        // Given
        Calendar now = Calendar.getInstance();

        // When
        confirmation.setCurrentTime(now);

        // Then
        assertThat(confirmation.objCurrentTime(), equalTo(now));
    }

    @Test
    public void validate_currentTimeIsSet_returnsTrue() {
        // Given
        confirmation.setCurrentTime(Calendar.getInstance());

        // When
        boolean isValid = confirmation.validate();

        // Then
        assertThat(isValid, is(true));
    }

    @Test
    public void validate_returnFalse() {
        // When
        boolean isValid = confirmation.validate();

        // Then
        assertThat(isValid, is(false));
    }
}


text:
package dagger.internal.codegen.bindinggraphvalidation;

import static dagger.spi.model.BindingKind.DELEGATE;
import static dagger.spi.model.BindingKind.MULTIBOUND_SET;
import static javax.tools.Diagnostic.Kind.ERROR;

import com.google.common.base.Joiner;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import dagger.spi.model.Binding;
import dagger.spi.model.BindingGraph;
import dagger.spi.model.BindingGraphPlugin;
import dagger.spi.model.DiagnosticReporter;
import dagger.spi.model.Key;
import javax.inject.Inject;

/** Validates that there are not multiple set binding contributions to the same binding. */
final class SetMultibindingValidator implements BindingGraphPlugin {

  @Inject
  SetMultibindingValidator() {
  }

  @Override
  public String pluginName() {
    return "Dagger/SetMultibinding";
  }

  @Override
  public void visitGraph(BindingGraph bindingGraph, DiagnosticReporter diagnosticReporter) {
    bindingGraph.bindings().stream()
        .filter(binding -> binding.kind().equals(MULTIBOUND_SET))
        .forEach(
            binding ->
                checkForDuplicateSetContributions(binding, bindingGraph, diagnosticReporter));
  }

  private void checkForDuplicateSetContributions(
      Binding binding, BindingGraph bindingGraph, DiagnosticReporter diagnosticReporter) {
    // Map of delegate target key to the original contribution binding
    Multimap<Key, Binding> dereferencedBindsTargets = HashMultimap.create();
    for (Binding dep : bindingGraph.requestedBindings(binding)) {
      if (dep.kind().equals(DELEGATE)) {
        dereferencedBindsTargets.put(dereferenceDelegateBinding(dep, bindingGraph), dep);
      }
    }

    dereferencedBindsTargets
        .asMap()
        .forEach(
            (targetKey, contributions) -> {
              if (contributions.size() > 1) {
                diagnosticReporter.reportComponent(
                    ERROR,
                    bindingGraph.componentNode(binding.componentPath()).get(),
                    "Multiple set contributions into %s for the same contribution key: %s.\n\n"
                        + "    %s\n",
                    binding.key(),
                    targetKey,
                    Joiner.on("\n    ").join(contributions));
              }
            });
  }

  /** Returns the delegate target of a delegate binding (going through other delegates as well). */
  private Key dereferenceDelegateBinding(Binding binding, BindingGraph bindingGraph) {
    ImmutableSet<Binding> delegateSet = bindingGraph.requestedBindings(binding);
    if (delegateSet.isEmpty()) {
      // There may not be a delegate if the delegate is missing. In this case, we just take the
      // requested key and return that.
      return Iterables.getOnlyElement(binding.dependencies()).key();
    }
    // If there is a binding, first we check if that is a delegate binding so we can dereference
    // that binding if needed.
    Binding delegate = Iterables.getOnlyElement(delegateSet);
    if (delegate.kind().equals(DELEGATE)) {
      return dereferenceDelegateBinding(delegate, bindingGraph);
    }
    return delegate.key();
  }
}


text:
package org.nd4j.parameterserver.distributed.messages.requests;

import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.nd4j.parameterserver.distributed.messages.BaseVoidMessage;
import org.nd4j.parameterserver.distributed.messages.RequestMessage;
import org.nd4j.parameterserver.distributed.messages.aggregations.InitializationAggregation;
import org.nd4j.parameterserver.distributed.messages.intercom.DistributedInitializationMessage;

/**
 * This method propagates storage/weights initialization over distributed Shards
 *
 * @author raver119@gmail.com
 */
@Slf4j
@Builder
@Deprecated
public class InitializationRequestMessage extends BaseVoidMessage implements RequestMessage {
    protected int vectorLength;
    protected int numWords;
    protected long seed;
    protected boolean useHs;
    protected boolean useNeg;
    protected int columnsPerShard;

    protected InitializationRequestMessage() {
        super(4);
        taskId = -119L;
    }

    public InitializationRequestMessage(int vectorLength, int numWords, long seed, boolean useHs, boolean useNeg,
                    int columnsPerShard) {
        this();
        this.vectorLength = vectorLength;
        this.numWords = numWords;
        this.seed = seed;
        this.useHs = useHs;
        this.useNeg = useNeg;
        this.columnsPerShard = columnsPerShard;
    }

    @Override
    public void processMessage() {
        DistributedInitializationMessage dim = new DistributedInitializationMessage(vectorLength, numWords, seed, useHs,
                        useNeg, columnsPerShard);

        InitializationAggregation aggregation = new InitializationAggregation(
                        (short) voidConfiguration.getNumberOfShards(), transport.getShardIndex());
        aggregation.setOriginatorId(this.originatorId);

        clipboard.pin(aggregation);

        dim.setOriginatorId(this.originatorId);
        dim.extractContext(this);
        dim.processMessage();

        if (voidConfiguration.getNumberOfShards() > 1)
            transport.sendMessageToAllShards(dim);
    }

    @Override
    public boolean isBlockingMessage() {
        return true;
    }
}


text: AI sea bot cpp realization


text:
require File.join(File.dirname(__FILE__), '..', 'lib', 'logbot')

DataMapper.setup(:default, "sqlite3:///")


text:
package at.int32.sweaty.ui.controls;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Composite;

import at.int32.sweaty.ui.Control;

public class Link extends Widget<org.eclipse.swt.widgets.Link> {

	private String link, text;

	public Link(Control parent) {
		super(parent);
	}

	public String text() {
		return this.text;
	}

	public String link() {
		return this.link;
	}

	public Link link(String text, String link) {
		this.text = text;
		this.link = link;

		String full = "" + text + "";

		this.ctrl.setText(full);

		return this;
	}

	@Override
	public org.eclipse.swt.widgets.Link getBaseControl(Composite parent,
			int style) {
		org.eclipse.swt.widgets.Link link = new org.eclipse.swt.widgets.Link(
				parent, SWT.NONE);

		link.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Program.launch(Link.this.link);
			}

		});
		return link;
	}
}


text:
module Tools

  class JsonGenerator

    def self.generate_from_permits
      file_path = "public/permits.json"
      data = Permit.select(Permit.json_fields)
      pre_json = data.collect(&:ready_json)
      File.write(file_path, pre_json.to_json)
    end

    def self.generate_from_temporary_signs
      file_path = "public/temporary_signs.json"
      data = TemporarySign.select(TemporarySign.json_fields)
      pre_json = data.collect(&:ready_json)
      File.write(file_path, pre_json.to_json)
    end

  end
end


text:
from ryu.services.protocols.bgp.base import Activity
from ryu.lib import hub
from ryu.lib.packet import bmp
from ryu.lib.packet import bgp
from ryu.services.protocols.bgp import constants as const
import socket
import logging
from calendar import timegm
from ryu.services.protocols.bgp.signals.emit import BgpSignalBus

LOG = logging.getLogger('bgpspeaker.bmp')

class BMPClient(Activity):
    """A BMP client.

    Try to establish BMP session between a configured BMP server.
    If BMP session is established, transfer information about peers
    (e.g. received and sent open msgs, contents of adj-rib-in, other stats)

    """

    def __init__(self, core_service, host, port):
        super(BMPClient, self).__init__(name='BMPClient(%s:%s)' % (host, port))
        self._core_service = core_service
        self._core_service.signal_bus.register_listener(
            BgpSignalBus.BGP_ADJ_RIB_IN_CHANGED,
            lambda _, data: self.on_adj_rib_in_changed(data)
        )
        self._core_service.signal_bus.register_listener(
            BgpSignalBus.BGP_ADJ_UP,
            lambda _, data: self.on_adj_up(data)
        )
        self._core_service.signal_bus.register_listener(
            BgpSignalBus.BGP_ADJ_DOWN,
            lambda _, data: self.on_adj_down(data)
        )
        self._socket = None
        self.server_address = (host, port)
        self._connect_retry_event = hub.Event()
        self._connect_retry_time = 5

    def _run(self):
        self._connect_retry_event.set()

        while True:
            self._connect_retry_event.wait()

            try:
                self._connect_retry_event.clear()
                self._connect_tcp(self.server_address,
                                  self._handle_bmp_session)
            except socket.error:
                    self._connect_retry_event.set()
                    LOG.info('Will try to reconnect to %s after %s secs: %s' %
                             (self.server_address, self._connect_retry_time,
                              self._connect_retry_event.is_set()))

            self.pause(self._connect_retry_time)

    def _send(self, msg):
        if not self._socket:
            return
        assert isinstance(msg, bmp.BMPMessage)
        serialized_msg = msg.serialize()

        ret = self._socket.send(msg.serialize())

    def on_adj_rib_in_changed(self, data):
        peer = data['peer']
        path = data['received_route']
        update_msg = peer._construct_update(path)
        msg = self._construct_route_monitoring(peer, path)
        self._send(msg)

    def on_adj_up(self, data):
        peer = data['peer']
        msg = self._construct_peer_up_notification(peer)
        self._send(msg)

        for path in peer._adj_rib_in.itervalues():
            update_msg = peer._construct_update(path)
            msg = self._construct_route_monitoring(peer, path)
            self._send(msg)

    def on_adj_down(self, data):
        peer = data['peer']
        msg = self._construct_peer_down_notification(peer)
        self._send(msg)

    def _construct_peer_up_notification(self, peer):
        if peer.is_mpbgp_cap_valid(bgp.RF_IPv4_VPN) or \
                peer.is_mpbgp_cap_valid(bgp.RF_IPv6_VPN):
            peer_type = bmp.BMP_PEER_TYPE_L3VPN
        else:
            peer_type = bmp.BMP_PEER_TYPE_GLOBAL

        peer_distinguisher = 0
        peer_as = peer._neigh_conf.remote_as
        peer_bgp_id = peer.protocol.recv_open_msg.bgp_identifier
        timestamp = peer.state._established_time

        local_address = peer.host_bind_ip
        local_port = int(peer.host_bind_port)
        peer_address, remote_port = peer.protocol._remotename
        remote_port = int(remote_port)

        sent_open_msg = peer.protocol.sent_open_msg
        recv_open_msg = peer.protocol.recv_open_msg

        msg = bmp.BMPPeerUpNotification(local_address=local_address,
                                        local_port=local_port,
                                        remote_port=remote_port,
                                        sent_open_message=sent_open_msg,
                                        received_open_message=recv_open_msg,
                                        peer_type=peer_type,
                                        is_post_policy=False,
                                        peer_distinguisher=peer_distinguisher,
                                        peer_address=peer_address,
                                        peer_as=peer_as,
                                        peer_bgp_id=peer_bgp_id,
                                        timestamp=timestamp)

        return msg

    def _construct_peer_down_notification(self, peer):
        if peer.is_mpbgp_cap_valid(bgp.RF_IPv4_VPN) or \
                peer.is_mpbgp_cap_valid(bgp.RF_IPv6_VPN):
            peer_type = bmp.BMP_PEER_TYPE_L3VPN
        else:
            peer_type = bmp.BMP_PEER_TYPE_GLOBAL

        peer_as = peer._neigh_conf.remote_as
        peer_bgp_id = peer.protocol.recv_open_msg.bgp_identifier
        peer_address, _ = peer.protocol._remotename

        return bmp.BMPPeerDownNotification(bmp.BMP_PEER_DOWN_REASON_UNKNOWN,
                                           data=None,
                                           peer_type=peer_type,
                                           is_post_policy=False,
                                           peer_distinguisher=0,
                                           peer_address=peer_address,
                                           peer_as=peer_as,
                                           peer_bgp_id=peer_bgp_id,
                                           timestamp=0)

    def _construct_route_monitoring(self, peer, path):
        if peer.is_mpbgp_cap_valid(bgp.RF_IPv4_VPN) or \
                peer.is_mpbgp_cap_valid(bgp.RF_IPv6_VPN):
            peer_type = bmp.BMP_PEER_TYPE_L3VPN
        else:
            peer_type = bmp.BMP_PEER_TYPE_GLOBAL

        peer_distinguisher = 0
        peer_as = peer._neigh_conf.remote_as
        peer_bgp_id = peer.protocol.recv_open_msg.bgp_identifier
        peer_address, _ = peer.protocol._remotename

        bgp_update = peer._construct_update(path)
        is_post_policy = not path.filtered
        timestamp = timegm(path.timestamp)

        msg = bmp.BMPRouteMonitoring(bgp_update=bgp_update,
                                     peer_type=peer_type,
                                     is_post_policy=is_post_policy,
                                     peer_distinguisher=peer_distinguisher,
                                     peer_address=peer_address,
                                     peer_as=peer_as, peer_bgp_id=peer_bgp_id,
                                     timestamp=timestamp)

        return msg

    def _handle_bmp_session(self, socket):

        self._socket = socket
        # send init message
        init_info = {'type': bmp.BMP_INIT_TYPE_STRING,
                     'value': u'This is Ryu BGP BMP message'}
        init_msg = bmp.BMPInitiation([init_info])
        self._send(init_msg)

        # send peer-up message for each peers
        peer_manager = self._core_service.peer_manager

        for peer in (p for p in peer_manager.iterpeers if p.in_established()):
            msg = self._construct_peer_up_notification(peer)
            self._send(msg)

            for path in peer._adj_rib_in.itervalues():
                update_msg = peer._construct_update(path)
                msg = self._construct_route_monitoring(peer, path)
                self._send(msg)

        # TODO periodically send stats to bmpstation

        while True:
            # bmpstation shouldn't send any packet to bmpclient.
            # this recv() is only meant to detect socket closed
            ret = self._socket.recv(1)
            if len(ret) == 0:
                LOG.debug('BMP socket is closed. retry connecting..')
                self._socket = None
                self._connect_retry_event.set()
                break

            # silently ignore packets from the bmpstation


text:
title: Solving Absolute Value Equations
localeTitle: Resolvendo Equações de Valor Absoluto
---
## Resolvendo Equações de Valor Absoluto

Este é um esboço. [Ajude nossa comunidade a expandi-lo](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/solving-absolute-value-equations/index.md) .

[Este guia de estilo rápido ajudará a garantir que sua solicitação de recebimento seja aceita](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Mais Informações:


text:
#include "gpurule.h"

#ifdef HAVE_OPENCL

namespace petabricks
{

void
GpuRule::generateTrampCodeSimple(Transform& trans, CodeGenerator& o)
{
  if( !_rule->isOpenClRule() )
    return;

  CLCodeGenerator clcodegen(o.cgPtr());
  IterationDefinition iterdef(*_rule, _rule->getSelfDependency(), _rule->isSingleCall());
  std::vector<std::string> packedargs = iterdef.packedargs();
  std::vector<std::string> packedargnames = iterdef.packedargnames();

  o.os() << "// GPURULE TRAMPOLINE CODE\n";

  // Create variables to hold handles to program, kernel
  o.hos() << "static cl_program clprog_" << _rule->id() << ";\n";
  o.hos() << "static cl_kernel clkern_" << _rule->id() << ";\n\n";
  o.os( ) << "cl_program " << trans.name() << "_instance::clprog_" << _rule->id()
	  << " = 0;\n";
  o.os( ) << "cl_kernel " << trans.name() << "_instance::clkern_" << _rule->id()
	  << " = 0;\n";

  // Create init function call
  o.beginFunc("int", codename()+"_init", std::vector<std::string>(),true);

  _rule->generateOpenCLKernel( trans, clcodegen, iterdef );

  o.os( ) << "cl_int err;";

  //o.os( ) << "/* -- Testing purposes only, to make this easy to read --\n\n";
  //clcodegen.outputStringTo( o.os( ) );
  //o.os( ) << "\n*/\n";

  o.os( ) << "const char* clsrc = ";
  clcodegen.outputEscapedStringTo( o.os( ) );
  o.os( ) << ";\n";

  o.comment( "Source for kernel." );
  o.os( ) << "cl_context ctx = OpenCLUtil::getContext( );\n\n";

  o.comment( "Build program." );
  o.os( ) << "size_t programlength = strlen( clsrc );\n";
  //TODO: fail to create program
  o.os( ) << "clprog_" << _rule->id() << " = clCreateProgramWithSource( ctx, 1, (const char **)&clsrc, NULL, &err );\n";
  o.os( ) << "JASSERT( CL_SUCCESS == err ).Text( \"Failed to create program.\" );\n\n";
  //o.os( ) << "err = OpenCLUtil::buildProgram( clprog_" << _rule->id() << " );\n";
  //ciErrNum = clBuildProgram(cpProgram, 0, NULL, "-cl-fast-relaxed-math", NULL, NULL);
  o.os( ) << "err = clBuildProgram( clprog_" << _rule->id() << ", 0, NULL, NULL, NULL, NULL);\n";
  o.os( ) << "std::cout << \"clBuildProgram err #\" << err << \": \" << OpenCLUtil::errorString( err ) << std::endl;\n";
  o.os( ) << "JASSERT( CL_SUCCESS == err ).Text( \"Failed to build program.\" );\n\n";

  o.comment( "Create kernel." );
  o.os( ) << "clkern_" << _rule->id() << "= clCreateKernel( clprog_" << _rule->id() << ", \"kernel_main\", &err );\n";
  o.os( ) << "#if OPENCL_TRACE\nstd::cout << \"clCreateKernel err #\" << err << \": \" << OpenCLUtil::errorString( err ) << std::endl;\n#endif\n";
  o.os( ) << "JASSERT( CL_SUCCESS == err ).Text( \"Failed to create kernel.\" );\n\n";

  o.os( ) << "return 0;";
  o.endFunc();

  // Create actual function call
  o.beginFunc("petabricks::DynamicTaskPtr", codename(), packedargs);
  o.write("return ");
  o.call(_rule->trampcodename(trans)+TX_OPENCL_POSTFIX, packedargnames);
  o.endFunc();

  // Invoke init once before main.
  o.os() << "static int ignored_"
         << trans.name()
         << '_'
         << codename()
         << " = "
         << trans.name()
         << "_instance::"
         << codename()
         << "_init();\n\n";
}

void
GpuRule::generateCallCodeSimple(Transform& /*trans*/, CodeGenerator& o, const SimpleRegionPtr& region)
{
  o.comment( "GENERATECALLCODESIMPLE" );
  o.callSpatial(codename(), region);
}

void
GpuRule::generateCallTaskCode(const std::string& name, Transform& trans, CodeGenerator& o, const SimpleRegionPtr& region)
{
  o.comment( "GENERATECALLTASKCODE" );
  o.mkSpatialTask(name, trans.instClassName(), codename(), region);
}

  /*
void petabricks::UserRule::generateCallCodeSimple(Transform& trans, CodeGenerator& o, const SimpleRegionPtr& region){
  o.callSpatial(trampcodename(trans)+TX_STATIC_POSTFIX, region);
}

void petabricks::UserRule::generateCallTaskCode(const std::string& name, Transform& trans, CodeGenerator& o, const SimpleRegionPtr& region){
  o.mkSpatialTask(name, trans.instClassName(), trampcodename(trans)+TX_DYNAMIC_POSTFIX, region);
}
  */

bool
GpuRule::canProvide(const MatrixDefPtr& m) const
{
  return _rule->canProvide(m);
}

void
GpuRule::getApplicableRegionDescriptors(RuleDescriptorList& rdl, const MatrixDefPtr& md, int i, const RulePtr& rule)
{
  _rule->getApplicableRegionDescriptors(rdl, md, i, rule);
}

bool
GpuRule::isSingleElement() const
{
  return _rule->isSingleElement();
}

int
GpuRule::dimensions() const
{
  return _rule->dimensions();
}

FormulaPtr
GpuRule::getSizeOfRuleIn(int d)
{
  return _rule->getSizeOfRuleIn(d);
}

std::string
GpuRule::codename() const
{
  return "gpuRule"+jalib::XToString(_id);
}

void
GpuRule::collectDependencies(StaticScheduler& scheduler)
{
  return _rule->collectDependencies(scheduler);
}

  /*
void
GpuRule::genWhereSwitch(Transform& trans, CodeGenerator& o)
{
  return _rule->genWhereSwitch(trans,o);
}
  */

DependencyDirection
GpuRule::getSelfDependency() const
{
  return _rule->getSelfDependency();
}

petabricks::RuleFlags::PriorityT petabricks::GpuRule::priority() const {
  return _rule->priority();
}
bool petabricks::GpuRule::isRecursive() const {
  return _rule->isRecursive();
}
bool petabricks::GpuRule::hasWhereClause() const {
  return _rule->hasWhereClause();
}
petabricks::FormulaPtr petabricks::GpuRule::getWhereClause() const {
  return _rule->getWhereClause();
}

}//namespace

#endif


text:
#ifndef BOOST_SPIRIT_INCLUDE_CLASSIC_DEBUG_NODE
#define BOOST_SPIRIT_INCLUDE_CLASSIC_DEBUG_NODE
#include <boost/spirit/home/classic/debug/debug_node.hpp>
#endif


text:
package org.apache.geronimo.timer;

import org.apache.geronimo.transaction.context.TransactionContextManager;
import org.apache.geronimo.transaction.manager.TransactionManagerImpl;
import org.apache.geronimo.transaction.manager.XidFactoryImpl;

/**
 *
 *
 * @version $Rev$ $Date$
 *
 * */
public class TransactionalThreadPooledTimerTest extends AbstractThreadPooledTimerTest {

    protected void setUp() throws Exception {
        TransactionManagerImpl transactionManager = new TransactionManagerImpl(10 * 1000,
                new XidFactoryImpl("WHAT DO WE CALL IT?".getBytes()), null, null);
        transactionContextManager = new TransactionContextManager(transactionManager, transactionManager);
        executableWorkFactory = new TransactionalExecutorTaskFactory(transactionContextManager, 1);
        super.setUp();
    }
}


text:
#include "CSaveView.h"

#include "VisualizationBase/src/ViewItemManager.h"

using namespace Visualization;

namespace Interaction {

CSaveView::CSaveView() : Command{"saveView"}{}

bool CSaveView::canInterpret(Item*, Item*, const QStringList& commandTokens,
		const std::unique_ptr<Visualization::Cursor>&)
{
	return (commandTokens.size() <= 2) && QString("saveView").startsWith(commandTokens.first());
}

CommandResult* CSaveView::execute(Item* source, Item*, const QStringList&,
		const std::unique_ptr<Visualization::Cursor>&)
{
	//Try to use an existing manager if possible
	if (source->findAncestorWithNode() && source->findAncestorWithNode()->node()->manager())
	{
		source->scene()->viewItems()->saveView(source->scene()->currentViewItem(),
					source->findAncestorWithNode()->node()->manager());
		return new CommandResult();
	}
	else return new CommandResult(new CommandError("Could not save view"));
}

QList<CommandSuggestion*> CSaveView::suggest(Item*, Item*, const QString& textSoFar,
		const std::unique_ptr<Visualization::Cursor>&)
{
	if (textSoFar.startsWith(name()) || name().startsWith(textSoFar))
		return {new CommandSuggestion(name(), "Save the current view")};
	else return {};
}

}


text: <?php get_template_part('templates/content', 'practicearea'); ?>


text:
module DSLMacros
  module InstanceMethods
    def capture_stdout
      @@original_stdout = STDOUT
      $stdout = StringIO.new
    end

    def restore_stdout
      $stdout = @@original_stdout
    end
  end
  module ClassMethods

    def it_should_return_true(msg, &block)
      it "returns true #{msg}" do
        capture_stdout
        begin
          FailFast(SIMPLE_FILE_PATH).check.but_fail_later do
            raise "BUG : @@errorz should be empty \n#{errors.inspect}"  unless errors.empty?
            result = self.instance_eval(&block)
            #TODO : BETTER ERROR REPORTING
            result.should == true
          end
        rescue => e
          raise e
        end
        restore_stdout
      end
    end

    def it_should_return_false(msg, &block)
      it "returns false #{msg}" do
        capture_stdout
        begin
          FailFast(SIMPLE_FILE_PATH).check.but_fail_later do
            raise "BUG : @@errorz should be empty \n#{errors.inspect}"  unless errors.empty?
            result = self.instance_eval(&block)
            #TODO : BETTER ERROR REPORTING
            result.should == false
          end
        rescue => e
          raise e
        end
        restore_stdout
      end
    end

    def it_should_not_raise_an_error(msg, &block)
      it "does not raise an error #{msg}" do
        capture_stdout
        begin
          FailFast(SIMPLE_FILE_PATH).check do
            raise "BUG : @@errorz should be empty \n#{errors.inspect}"  unless errors.empty?
            self.instance_eval(&block)
          end
        rescue => e
          raise e
        ensure
          if FailFast.failed?
            fail "ZZshould not have raised an error, but it raised\n#{FailFast.global_errors.join("\n")}"
          end
        end
        restore_stdout
      end
    end

    def it_should_raise_an_error(key, kind, msg, &block)
      it "raises an error #{kind}-#{key}-#{msg}" do
        capture_stdout
        begin
          FailFast(SIMPLE_FILE_PATH).check do
            raise "BUG : @@errorz should be empty \n#{errors.inspect}"  unless errors.empty?
            self.instance_eval(&block)
          end
        rescue => e
          # uncomment the next line after the refactoring/once error are no longer raise
          #  raise e
        ensure
          if !FailFast.failed?
            fail "\ne2d\nshould have raised a #{kind} error for #{key} \n==#{e}"
          elsif FailFast.global_errors.length == 1 && !FailFast.global_errors.first.has_key_and_kind?(key, kind)
            fail "\ne2e\nshould have raised a #{kind.inspect} error for #{key.inspect}, but raised instead #{FailFast.global_errors.inspect}"
          elsif 2 <= FailFast.global_errors.length
            fail "\ne2f\nshould have raised only a #{kind} error for #{key}\n#{FailFast.global_errors.join("\n")}"
          end
        end
        restore_stdout
      end
    end
    def it_should_raise_a_direct_error(value, kind, msg, &block)
      it "raises an error #{kind}-#{value}-#{msg}" do
        capture_stdout
        begin
          FailFast(SIMPLE_FILE_PATH).check do
            raise "BUG : @@errorz should be empty \n#{errors.inspect}"  unless errors.empty?
            self.instance_eval(&block)
          end
        rescue => e
          # uncomment the next line after the refactoring/once error are no longer raise
          #  raise e
        ensure
          if !FailFast.failed?
            fail "\ne2d\nshould have raised a #{kind} error for #{value} \n==#{e}"
          elsif FailFast.global_errors.length == 1 && !FailFast.global_errors.first.has_value_and_kind?(value, kind)
            fail "\ne2e\nshould have raised a #{kind.inspect} error for #{value.inspect}\n, but raised instead\n#{FailFast.global_errors.inspect}"
          elsif 2 <= FailFast.global_errors.length
            fail "\ne2f\nshould have raised only 1 #{kind} error for #{value}\nbut raised instead\n#{FailFast.global_errors.join("\n")}"
          end
        end
        restore_stdout
      end
    end

  end

  def self.included(receiver)
    receiver.extend(ClassMethods)
    receiver.send :include, InstanceMethods
  end
end

Spec::Runner.configure do |config|
  config.include(DSLMacros)
end


text:
package org.apache.hadoop.hbase.codec.prefixtree.row.data;

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

import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.codec.prefixtree.PrefixTreeTestConstants;
import org.apache.hadoop.hbase.codec.prefixtree.row.BaseTestRowData;
import org.apache.hadoop.hbase.util.ByteRange;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.SimpleByteRange;
import org.apache.hadoop.hbase.util.byterange.impl.ByteRangeTreeSet;

import com.google.common.collect.Lists;

/*
 * test different timestamps
 *
 * http://pastebin.com/7ks8kzJ2
 * http://pastebin.com/MPn03nsK
 */
public class TestRowDataUrls extends BaseTestRowData{

  static List<ByteRange> rows;
	static{
    List<String> rowStrings = new ArrayList<String>();
    rowStrings.add("com.edsBlog/directoryAa/pageAaa");
    rowStrings.add("com.edsBlog/directoryAa/pageBbb");
    rowStrings.add("com.edsBlog/directoryAa/pageCcc");
    rowStrings.add("com.edsBlog/directoryAa/pageDdd");
    rowStrings.add("com.edsBlog/directoryBb/pageEee");
    rowStrings.add("com.edsBlog/directoryBb/pageFff");
    rowStrings.add("com.edsBlog/directoryBb/pageGgg");
    rowStrings.add("com.edsBlog/directoryBb/pageHhh");
    rowStrings.add("com.isabellasBlog/directoryAa/pageAaa");
    rowStrings.add("com.isabellasBlog/directoryAa/pageBbb");
    rowStrings.add("com.isabellasBlog/directoryAa/pageCcc");
    rowStrings.add("com.isabellasBlog/directoryAa/pageDdd");
    rowStrings.add("com.isabellasBlog/directoryBb/pageEee");
    rowStrings.add("com.isabellasBlog/directoryBb/pageFff");
    rowStrings.add("com.isabellasBlog/directoryBb/pageGgg");
    rowStrings.add("com.isabellasBlog/directoryBb/pageHhh");
    ByteRangeTreeSet ba = new ByteRangeTreeSet();
    for (String row : rowStrings) {
      ba.add(new SimpleByteRange(Bytes.toBytes(row)));
    }
    rows = ba.compile().getSortedRanges();
  }

  static List<String> cols = Lists.newArrayList();
  static {
    cols.add("Chrome");
    cols.add("Chromeb");
    cols.add("Firefox");
    cols.add("InternetExplorer");
    cols.add("Opera");
    cols.add("Safari");
  }

  static long ts = 1234567890;

  static int MAX_VALUE = 50;

  static List<KeyValue> kvs = Lists.newArrayList();
  static {
    for (ByteRange row : rows) {
      for (String col : cols) {
        KeyValue kv = new KeyValue(row.deepCopyToNewArray(), PrefixTreeTestConstants.TEST_CF,
            Bytes.toBytes(col), ts, KeyValue.Type.Put, Bytes.toBytes("VALUE"));
        kvs.add(kv);
        // System.out.println("TestRows5:"+kv);
      }
    }
  }

  @Override
  public List<KeyValue> getInputs() {
    return kvs;
  }

}


text:
<?php
$con = file_get_contents("https://www.google.com/images/srpr/logo4w.png");
$en = base64_encode($con);
include("lib/nusoap.php");
$wsdl = "http://localhost/service/server.php?wsdl";
$client = new nusoap_client($wsdl, 'wsdl');

$authenticate = array(
    'username' => 'rokon',
    'password' => 'rokon'
);
$result = $client->call('authenticate', $authenticate);
$token = end(explode('-', $result));

$pressStart = array(
    'token' => $token,
    'project_id' => 3,
    'memo' => "New Memo",
);
$result = $client->call('pressStart', $pressStart);
$saveTimeSlot = array(
    'token' => $token,
    'image' => $en,
);
$result = $client->call('saveTimeSlot', $saveTimeSlot);
print_r($result);

function data_uri($base64encoded, $mime)
{
    return ('data:' . $mime . ';base64,' . $base64encoded);
}
?>
<!--<img src="<?php //echo data_uri($result, 'image/png');                  ?>" alt="An elephant" />-->


text:
[![Zorium](./icons/zorium_logo.png)](https://zorium.zolmeister.com/)

## [Zorium](https://zorium.zolmeister.com/) - The CoffeeScript Web Framework

#### [zorium.zolmeister.com](https://zorium.zolmeister.com/)

(╯°□°)╯︵ ┻━┻
v2.0.0

### Features

  - First Class [RxJS Observables](https://github.com/Reactive-Extensions/RxJS)
  - Built for Isomorphism (server-side rendering)
  - Standardized [Best Practices](https://zorium.zolmeister.com/best-practices)
  - [Material Design Components](https://zorium.zolmeister.com/paper)
  - Production-ready [Seed Project](https://github.com/Zorium/zorium-seed)
  - It's just CoffeeScript, no magic

### Example

```coffee
z = require 'zorium'

class Icon
  render: ({children}) ->
    z '.icon', children

class AppComponent
  constructor: ->
    @state = z.state
      name: 'Zorium'

  render: =>
    {name} = @state.getValue()

    z '.zorium',
      z 'p.text',
        z Icon, 'fireworks'
        "The Future -#{name}"

z.render new AppComponent(), document.body
```

### Documentation

[zorium.zolmeister.com](https://zorium.zolmeister.com/)

### Installation

```bash
yarn add zorium
```

### Contribute

```bash
yarn install
yarn test
```

### Changelog
  - 1.x -> 2
    - [breaking] deprecate `z.ev()`
    - [breaking] deprecate `attributes` property for manually specifying attributes
    - [breaking] deprecate `z.router`
    - [breaking] upgrade to RxJS v5
    - [breaking] remove requestAnimationFrame and Promise polyfill
    - add support for rendering static classes as components
    - migrate backend from [virtual-dom](https://github.com/Matt-Esch/virtual-dom) to [dio.js](https://github.com/thysultan/dio.js)


text:
package apincer.android.uamp.ui;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.transition.Slide;

import com.jaeger.library.StatusBarUtil;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItem;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems;

import java.util.List;

import apincer.android.uamp.FileManagerService;
import apincer.android.uamp.MusicService;
import apincer.android.uamp.R;
import apincer.android.uamp.model.MediaItem;

/**
 * A full screen editor that shows the current  music with a background image
 * depicting the album art. The activity also has controls to seek/pause/play the audio.
 */
public class MetadataActivity extends AppCompatActivity {
    private ViewPager viewPager;

    public static boolean startActivity(AppCompatActivity  context, List<MediaItem> mediaItems) {
        if(mediaItems==null || mediaItems.isEmpty()) {
            return false;
        }
        FileManagerService.addToEdit(mediaItems);
        Intent intent = new Intent(context, MetadataActivity.class);
        ActivityCompat.startActivityForResult(context, intent, MusicService.REQUEST_CODE_EDIT_MEDIA_TAG, null);
        return true;
    }

    @Override
    public void onBackPressed() {
        int currentFragment = viewPager.getCurrentItem();

        if(currentFragment==0) {
            super.onBackPressed();
        }else {
            viewPager.setCurrentItem(currentFragment-1);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initActivityTransitions();
        // requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_metadata);
        StatusBarUtil.setColor(this, getColor(R.color.colorPrimaryDark_light));
        setTitle("");

        viewPager = findViewById(R.id.viewpager);
        SmartTabLayout viewPagerTab = findViewById(R.id.viewpagertab);

        FragmentPagerItems pages = new FragmentPagerItems(this);
        pages.add(FragmentPagerItem.of("Edit Metadata", MetadataEditorFragment.class));
        if(FileManagerService.getEditItems().size()>1) {
            pages.add(FragmentPagerItem.of("Selected Songs", MetadataDetailsFragment.class));
        }
        pages.add(FragmentPagerItem.of("Search", MetadataSearchFragment.class));

        FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(
                getSupportFragmentManager(), pages);

        viewPager.setAdapter(adapter);
        viewPagerTab.setViewPager(viewPager);
    }

    private void initActivityTransitions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Slide transition = new Slide();
            transition.excludeTarget(android.R.id.statusBarBackground, true);
            getWindow().setEnterTransition(transition);
            getWindow().setReturnTransition(transition);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}


text:
'use strict';

/**
 * Running the indexing procedure in the catalog mode.
 */

function parseReference(reference) {
  var result = [];
  reference = reference.split(',');
  // In the catalog mode, each catalog is a combination of a catalog alias
  // and an optional page offset in the catalog traversing.
  for (var r in reference) {
    reference[r] = reference[r].split('+');
    if (reference[r].length === 1) {
      reference[r][1] = 0;
    } else if (reference[r].length === 2) {
      // Let's make this nummeric.
      reference[r][1] = parseInt(reference[r][1], 10);
    } else {
      throw new Error('Every reference in the catalog mode must ' +
          'contain a catalog alias optionally seperated by a plus (+), ' +
          'ex: ES+10, for the tenth page offset of the ES catalog.');
    }
    result.push({
      catalogAlias: reference[r][0],
      offset: reference[r][1]
    });
  }
  return result;
}

module.exports.generateQueries = function(state) {
  var relevantCatalogs = parseReference(state.reference);
  return relevantCatalogs.map(function(catalogReference) {
    return {
      catalogAlias: catalogReference.catalogAlias,
      query: 'ID *',
      offset: catalogReference.offset || 0
    };
  });
};


text:
Here you may get thousands pre-made source code samples for simple implementation in your own programming C# projects. ByteScout Data Extraction Suite was made to help with PDF A compatibility test with PDF extractor SDK in C#. ByteScout Data Extraction Suite is the set that includes 3 SDK products for data extraction from PDF, scans, images and from spreadsheets: PDF Extractor SDK, Data Extraction SDK, Barcode Reader SDK.

This rich and prolific sample source code in C# for ByteScout Data Extraction Suite contains various functions and options you should do calling the API to implement PDF A compatibility test with PDF extractor SDK. To use PDF A compatibility test with PDF extractor SDK in your C# project or application just copy & paste the code and then run your app! C# application implementation mostly involves various stages of the software development so even if the functionality works please check it with your data and the production environment.

Our website gives free trial version of ByteScout Data Extraction Suite. It includes all these source code samples with the purpose to assist you with your C# application implementation.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Data%20Extraction%20Suite%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Data%20Extraction%20Suite%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### ****PDFATest.NETCore.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
    <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
    <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
    <GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
    <GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>
    <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
    <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
    <GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
    <GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
    <GenerateAssemblyTrademarkAttribute>false</GenerateAssemblyTrademarkAttribute>
    <GenerateAssemblyCultureAttribute>false</GenerateAssemblyCultureAttribute>
    <GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute>
  </PropertyGroup>
  <ItemGroup>
    <None Include="..\..\sample1.pdf" Link="sample1.pdf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Windows.Compatibility" Version="2.0.0" />
  </ItemGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDFExtractor">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>c:\Program Files\Bytescout PDF Extractor SDK\netcoreapp2.0\Bytescout.PDFExtractor.dll</HintPath>
    </Reference>
    <Reference Include="Bytescout.PDFExtractor.OCRExtension">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>c:\Program Files\Bytescout PDF Extractor SDK\netcoreapp2.0\Bytescout.PDFExtractor.OCRExtension.dll</HintPath>
    </Reference>
  </ItemGroup>
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****PDFATest.VS2005.csproj:**

```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>8.0.50727</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{25E68A98-BA0D-428D-99F4-0ED8C42DD41C}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>PDFATest</RootNamespace>
    <AssemblyName>PDFATest</AssemblyName>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDFExtractor, Version=1.0.0.12, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="..\..\sample1.pdf">
      <Link>sample1.pdf</Link>
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****PDFATest.VS2008.csproj:**

```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>9.0.21022</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{25E68A98-BA0D-428D-99F4-0ED8C42DD41C}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>PDFATest</RootNamespace>
    <AssemblyName>PDFATest</AssemblyName>
    <OldToolsVersion>2.0</OldToolsVersion>
    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDFExtractor, Version=1.0.0.12, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="..\..\sample1.pdf">
      <Link>sample1.pdf</Link>
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****PDFATest.VS2010.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{25E68A98-BA0D-428D-99F4-0ED8C42DD41C}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>PDFATest</RootNamespace>
    <AssemblyName>PDFATest</AssemblyName>
    <OldToolsVersion>3.5</OldToolsVersion>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDFExtractor, Version=1.0.0.12, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="..\..\sample1.pdf">
      <Link>sample1.pdf</Link>
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****Program.cs:**

```
using System;
using Bytescout.PDFExtractor;

namespace PDFATest
{
	class Program
	{
		static void Main(string[] args)
		{
			// Create Bytescout.PDFExtractor.PDFAValidator instance
			PDFAValidator validator = new PDFAValidator();
			validator.RegistrationName ="demo";
			validator.RegistrationKey = "demo";

			// Load sample PDF document
            validator.LoadDocumentFromFile("sample1.pdf");

		    if (validator.IsPDFA)
		        Console.WriteLine("This file conforms to the PDF/A standard");
		    else
		    {
		        Console.WriteLine("This file doesn't conform to the PDF/A standard.");
		        Console.WriteLine("Issues:");

		        foreach (string validationError in validator.ValidationErrors)
		            Console.WriteLine(validationError);
		    }

			// Cleanup
			validator.Dispose();

			Console.WriteLine();
			Console.WriteLine("Press any key to continue...");
			Console.ReadLine();
		}
	}
}

```

<!-- code block end -->


text:
/* httpd that log requests in JSON format */
package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
)

// For Content-Length, calculated on init
var imageLen string

func init() {
	/* image is generated from image.go, see Makefile */
	imageLen = fmt.Sprintf("%d", len(image))
}

// homeHandler serves the image
func homeHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "image/png")
	w.Header().Set("Content-Length", imageLen)
	w.Write(image)
}

func main() {
	port := 8080
	flag.IntVar(&port, "port", port, "port to listen on")
	flag.Parse()

	http.HandleFunc("/", homeHandler)
	addr := fmt.Sprintf(":%d", port)
	log.Fatal(http.ListenAndServe(addr, nil))
}


text:
class AddDealIdToComments < ActiveRecord::Migration
  def change
    add_reference :comments, :deal, index: true
  end
end


text:
from setuptools import setup, find_packages

readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')

requirements = [
    'configobj',
    'six',
    'validator',
    'argparse'
]

test_requirements = [
    # TODO: put package test requirements here
]

setup(
    name='masterha_toolkit',
    version='0.2.0',
    description='Tools for MySQL MasterHA failover and monitoring',
    long_description=readme + '\n\n' + history,
    author='Tyler Mitchell',
    author_email='zastari@gmail.com',
    url='https://github.com/zastari/masterha_toolkit',
    packages=find_packages(exclude=["build", "dist", "docs", "tests"]),
    package_dir={'masterha_toolkit':
                 'masterha_toolkit'},
    include_package_data=True,
    install_requires=requirements,
    license="BSD",
    zip_safe=False,
    keywords='masterha_toolkit',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.7',
    ],
    test_suite='tests',
    tests_require=test_requirements,
    entry_points = {
        'console_scripts': ['masterha_dispatch=masterha_toolkit.dispatch:main']
    }
)


text:
===============================
django SHOP - Variable Products
===============================

This app's purpose is to provide two product mixin classes together with two
corresponding view mixin classes. They offers two simple product variations
variants. They can be used as a stand-alone app or as a starting point how
to add a self contained variation to a product.

Currently two variation variants are implemented

Option groups
=============
One or more groups of options may be assigned to a product. Such a group can be
something like color, wrapping paper, etc. Each of these groups can have two or
more options, say for group color: red, pink, yellow, magenta.

The shop owner may specify for each product, which option groups shall belong to
it. To each option, an additional price can be added.

While filling the shopping cart, the customer then may chose one of these
options using a select box.

Text options
============
One or more text options may be assigned to a product. Such an option can be
something such as an individual engraving or a congratulation message. An
additional price may be added per character.

While filling the shopping cart, the customer then may add an individual text
message to the product he intends to buy.

Installation
------------
This requires a patched version of django SHOP (https://github.com/jrief/django-shop/tree/variations)
which offers a simpler interface to products variations.

* Add ``shop_optiongroups`` and/or to ``shop_textoptions`` your INSTALLED_APPS
  of your settings.py.
* Add ``shop_optiongroups.cart_modifier.OptionGroupsCartModifier``
  and/or ``shop_textoptions.cart_modifier.TextOptionsOptionsCartModifier``
  to your SHOP_CART_MODIFIERS of your settings.py.

Alternative models
------------------
You can easily override the current models with a customized options class
derived from the abstract base classes ``shop_optiongroups.models.bases.OptionGroupBase``,
``shop_optiongroups.models.bases.OptionBase`` and
``shop_textoptions.models.bases.TextOptionBase``. This gives you the possibility
to add additional fields to your customized option model class.

To enable this overriding, in ``settings.py`` point ``SHOP_OPTIONGROUP_MODEL``
and/or ``SHOP_OPTION_MODEL`` and/or  ``SHOP_TEXTOPTION_MODEL`` to your class
model.

Usage
-----
Run schemamigration for ``shop_optiongroups`` and ``shop_textoptions`` and
migrate those schemas.

Change your code
================
Add to your product model one or both of these mixin classes::

   from shop.models.productmodel import Product
   from shop_optiongroups.models import ProductOptionGroupsMixin
   from shop_textoptions.models import ProductTextOptionsMixin

   class MyProduct(Product, ProductOptionGroupsMixin, ProductTextOptionsMixin):
       ...

Add to your product's detail view one or both of these mixin classes::

   from shop.views.product import ProductDetailView
   from shop_optiongroups.views import ProductOptionGroupsViewMixin
   from shop_textoptions.views import ProductTextOptionsViewMixin

   class MyProductDetailView(ProductOptionGroupsViewMixin, \
      ProductTextOptionsViewMixin, ProductDetailView):

Override django-shop's `product_detail.html` template and add selection elements
so that your users can select these variations. Use the prepared template tags
for this purpose::

   {% load product_optiongroups product_textoptions %}
   ...
   {% with option_groups=object|get_option_groups %}
   {% if option_groups %}

Variations:

     {% for option_group in option_groups %}
     {{ option_group.name }}:
     {% with option_group|get_options as options %}
     <select name="add_item_option_group_{{ option_group.id }}">
       {% for option in options %}
       <option value="{{ option.id }}">{{ option.name }}</option>
       {% endfor %}
     </select>
     {% endwith %}
     {% endfor %}

   {% endif %}
   {% endwith %}
   ...
   {% with text_options=object.text_options.all %}
   {% if text_options %}

Text options:

     {% for text_option in text_options %}
     {{ text_option.name }}:
     <input type="text" name="add_item_text_option_{{ text_option.id }}" value="" />
     {% endfor %}

   {% endif %}
   {% endwith %}

Fill your database
==================

* Log into the admin interface.
* Go to Shop_Optiongroups.
* Add an Option Group and add Options to this group.
* Go to Shop_Textoptions.
* Add a Text Option.

Contributing
============

Feel free to fork this project on github, send pull requests...
development discussion happends on the django SHOP mailing list
https://groups.google.com/forum/#!forum/django-shop


text:
from enum import IntEnum
from collections import namedtuple

from clips._clips import lib, ffi

class CLIPSError(RuntimeError):
    """An error occurred within the CLIPS Environment."""

    def __init__(self, env: ffi.CData, message: str = None, code: int = None):
        if message is None:
            routers = environment_data(env, 'routers')
            message = routers['python-error-router'].last_message
            message = message.lstrip('\n').rstrip('\n').replace('\n', ' ')

        super(CLIPSError, self).__init__(message)

        self.code = code

class CLIPSType(IntEnum):
    FLOAT = 0
    INTEGER = 1
    SYMBOL = 2
    STRING = 3
    MULTIFIELD = 4
    EXTERNAL_ADDRESS = 5
    FACT_ADDRESS = 6
    INSTANCE_ADDRESS = 7
    INSTANCE_NAME = 8
    VOID = 9

class SaveMode(IntEnum):
    LOCAL_SAVE = lib.LOCAL_SAVE
    VISIBLE_SAVE = lib.VISIBLE_SAVE

class ClassDefaultMode(IntEnum):
    CONVENIENCE_MODE = 0
    CONSERVATION_MODE = 1

class Strategy(IntEnum):
    DEPTH = 0
    BREADTH = 1
    LEX = 2
    MEA = 3
    COMPLEXITY = 4
    SIMPLICITY = 5
    RANDOM = 6

class SalienceEvaluation(IntEnum):
    WHEN_DEFINED = lib.WHEN_DEFINED
    WHEN_ACTIVATED = lib.WHEN_ACTIVATED
    EVERY_CYCLE = lib.EVERY_CYCLE

class Verbosity(IntEnum):
    VERBOSE = 0
    SUCCINT = 1
    TERSE = 2

class TemplateSlotDefaultType(IntEnum):
    NO_DEFAULT = lib.NO_DEFAULT
    STATIC_DEFAULT = lib.STATIC_DEFAULT
    DYNAMIC_DEFAULT = lib.DYNAMIC_DEFAULT

class PutSlotError(IntEnum):
    PSE_NO_ERROR = lib.PSE_NO_ERROR
    PSE_NULL_POINTER_ERROR = lib.PSE_NULL_POINTER_ERROR
    PSE_INVALID_TARGET_ERROR = lib.PSE_INVALID_TARGET_ERROR
    PSE_SLOT_NOT_FOUND_ERROR = lib.PSE_SLOT_NOT_FOUND_ERROR
    PSE_TYPE_ERROR = lib.PSE_TYPE_ERROR
    PSE_RANGE_ERROR = lib.PSE_RANGE_ERROR
    PSE_ALLOWED_VALUES_ERROR = lib.PSE_ALLOWED_VALUES_ERROR
    PSE_CARDINALITY_ERROR = lib.PSE_CARDINALITY_ERROR
    PSE_ALLOWED_CLASSES_ERROR = lib.PSE_ALLOWED_CLASSES_ERROR

PUT_SLOT_ERROR = {PutSlotError.PSE_NULL_POINTER_ERROR:
                  lambda s: RuntimeError("Internal error '%s'" % s),
                  PutSlotError.PSE_INVALID_TARGET_ERROR:
                  lambda s: ValueError("invalid target for slot '%s'" % s),
                  PutSlotError.PSE_SLOT_NOT_FOUND_ERROR:
                  lambda s: KeyError("slot '%s' does not exist" % s),
                  PutSlotError.PSE_TYPE_ERROR:
                  lambda s: TypeError("invalid type for slot '%s'" % s),
                  PutSlotError.PSE_RANGE_ERROR:
                  lambda s: ValueError("invalid range for slot '%s'" % s),
                  PutSlotError.PSE_ALLOWED_VALUES_ERROR:
                  lambda s: ValueError("value not allowed for slot '%s'" % s),
                  PutSlotError.PSE_CARDINALITY_ERROR:
                  lambda s: IndexError("invalid cardinality for slot '%s'" % s),
                  PutSlotError.PSE_ALLOWED_CLASSES_ERROR:
                  lambda s: ValueError("class not allowed for slot '%s'" % s)}

def initialize_environment_data(env: ffi.CData) -> 'EnvData':
    fact = lib.CreateFactBuilder(env, ffi.NULL)
    if fact is ffi.NULL:
        raise CLIPSError(env, code=lib.FBError(env))
    instance = lib.CreateInstanceBuilder(env, ffi.NULL)
    if fact is ffi.NULL:
        raise CLIPSError(env, code=lib.FBError(env))
    function = lib.CreateFunctionCallBuilder(env, 0)
    if fact is ffi.NULL:
        raise CLIPSError(env, code=lib.FBError(env))
    multifield = lib.CreateMultifieldBuilder(env, 0)
    if multifield is ffi.NULL:
        raise CLIPSError(env)
    string = lib.CreateStringBuilder(env, 0)
    if string is ffi.NULL:
        raise CLIPSError(env)
    builders = EnvBuilders(fact, instance, function, string, multifield)

    fact = lib.CreateFactModifier(env, ffi.NULL)
    if fact is ffi.NULL:
        raise CLIPSError(env, code=lib.FMError(env))
    instance = lib.CreateInstanceModifier(env, ffi.NULL)
    if instance is ffi.NULL:
        raise CLIPSError(env, code=lib.FMError(env))
    modifiers = EnvModifiers(fact, instance)

    functions = UserFunctions({}, {})

    ENVIRONMENT_DATA[env] = EnvData(builders, modifiers, {}, functions)

    lib.DefinePythonFunction(env)

    return ENVIRONMENT_DATA[env]

def delete_environment_data(env: ffi.CData):
    data = ENVIRONMENT_DATA.pop(env, None)

    if data is not None:
        fact, instance, function, string, multifield = data.builders

        lib.FBDispose(fact)
        lib.IBDispose(instance)
        lib.FCBDispose(function)
        lib.SBDispose(string)
        lib.MBDispose(multifield)

        fact, instance = data.modifiers
        lib.FMDispose(fact)
        lib.IMDispose(instance)

def environment_data(env: ffi.CData, name: str) -> type:
    """Retrieve Environment specific data."""
    return getattr(ENVIRONMENT_DATA[env], name)

def environment_builder(env: ffi.CData, name: str) -> ffi.CData:
    """Retrieve Environment specific builder."""
    return getattr(ENVIRONMENT_DATA[env].builders, name)

def environment_modifier(env: ffi.CData, name: str) -> ffi.CData:
    """Retrieve Environment specific modifier."""
    return getattr(ENVIRONMENT_DATA[env].modifiers, name)

ENVIRONMENT_DATA = {}
EnvData = namedtuple('EnvData', ('builders',
                                 'modifiers',
                                 'routers',
                                 'user_functions'))
EnvBuilders = namedtuple('EnvBuilders', ('fact',
                                         'instance',
                                         'function',
                                         'string',
                                         'multifield'))
EnvModifiers = namedtuple('EnvModifiers', ('fact',
                                           'instance'))
UserFunctions = namedtuple('UserFunctions', ('functions',
                                             'external_addresses'))


text:
<html>
    <head>
        <meta charset="utf-8" />
        <title> sounci </title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
        <link rel="stylesheet" href="public/css/global.css" />
        <link rel="stylesheet" href="public/css/button.css" />
        <link rel="stylesheet" href="public/css/info.css" />
        <link rel="stylesheet" href="public/css/custom_smalltalk.css" />
        <link href='https://fonts.googleapis.com/css?family=Exo+2:500' rel='stylesheet' type='text/css'>

    </head>
    <body>
        <div id="content"> </div>

        <script src="public/js/bundle.js"></script>
        <script src="public/js/button.js"></script>
    </body>
</html>