text:
package org.eclipse.bpel.model.messageproperties.impl;

import java.util.Collection;

import javax.xml.namespace.QName;

//Bugzilla 340654 - renamed to avoid confusion with WSDL's ExtensibilityElement
import org.eclipse.bpel.model.impl.BPELExtensibilityElementImpl;
import org.eclipse.bpel.model.messageproperties.MessagepropertiesPackage;
import org.eclipse.bpel.model.messageproperties.Property;
import org.eclipse.bpel.model.messageproperties.util.MessagepropertiesConstants;
import org.eclipse.bpel.model.util.BPELServicesUtility;

import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;

import org.eclipse.wst.wsdl.internal.impl.ExtensibilityElementImpl;
import org.eclipse.wst.wsdl.Definition;
import org.eclipse.wst.wsdl.internal.impl.DefinitionImpl;
import org.eclipse.xsd.XSDElementDeclaration;
import org.eclipse.xsd.XSDTypeDefinition;

import org.w3c.dom.Element;

/**
 *
 * An implementation of the model object 'Property'.
 *
 *

 * The following features are implemented:
 *

 *
{@link org.eclipse.bpel.model.messageproperties.impl.PropertyImpl#getQName QName}

 *
{@link org.eclipse.bpel.model.messageproperties.impl.PropertyImpl#getName Name}

 *
{@link org.eclipse.bpel.model.messageproperties.impl.PropertyImpl#getType Type}

 *
{@link org.eclipse.bpel.model.messageproperties.impl.PropertyImpl#getID ID}

 *

 *

 *
 * @generated
 */
public class PropertyImpl extends ExtensibilityElementImpl implements Property {
	/**
	 * The default value of the '{@link #getQName() QName}' attribute.
	 *
	 *
	 * @see #getQName()
	 * @generated
	 * @ordered
	 */
	protected static final QName QNAME_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getQName() QName}' attribute.
	 *
	 *
	 * @see #getQName()
	 * @generated
	 * @ordered
	 */
	protected QName qName = QNAME_EDEFAULT;

	/**
	 * The default value of the '{@link #getName() Name}' attribute.
	 *
	 *
	 * @see #getName()
	 * @generated
	 * @ordered
	 */
	protected static final String NAME_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getName() Name}' attribute.
	 *
	 *
	 * @see #getName()
	 * @generated
	 * @ordered
	 */
	protected String name = NAME_EDEFAULT;

	/**
	 * The default value of the '{@link #getType() Type}' attribute.
	 *
	 *
	 * @see #getType()
	 * @generated
	 * @ordered
	 */
	protected static final Object TYPE_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getType() Type}' attribute.
	 *
	 *
	 * @see #getType()
	 * @generated
	 * @ordered
	 */
	protected Object type = TYPE_EDEFAULT;

	/**
	 * The default value of the '{@link #getID() ID}' attribute.
	 *
	 *
	 * @see #getID()
	 * @generated
	 * @ordered
	 */
	protected static final String ID_EDEFAULT = null;

	/**
	 *
	 *
	 * @generated
	 */
	protected PropertyImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */

	protected EClass eStaticClass() {
		return MessagepropertiesPackage.Literals.PROPERTY;
	}

	/**
	 *
	 *
	 * @generated NOT
	 */
	public QName getQName() {
		return new QName(getEnclosingDefinition().getTargetNamespace(), name);
	}

	/**
	 *
	 *
	 * @generated NOT
	 */
	public void setQName(QName newQName) {
		// Do nothing.
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getName() {
		return name;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setName(String newName) {
		String oldName = name;
		name = newName;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET,
					MessagepropertiesPackage.PROPERTY__NAME, oldName, name));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public Object getType() {
		return type;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setType(Object newType) {
		Object oldType = type;
		type = newType;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET,
					MessagepropertiesPackage.PROPERTY__TYPE, oldType, type));
	}

	/**
	 *
	 *
	 * @generated NOT
	 */
	public String getID() {
		// TODO: NEW_WSDL review this
		String namespace = getEnclosingDefinition() != null ? getEnclosingDefinition()
				.getTargetNamespace() : "";
		String id = BPELServicesUtility.getId(new QName(namespace, getName()),
				this);
		return id;
	}

	/**
	 *
	 *
	 * @generated
	 */

	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
		case MessagepropertiesPackage.PROPERTY__QNAME:
			return getQName();
		case MessagepropertiesPackage.PROPERTY__NAME:
			return getName();
		case MessagepropertiesPackage.PROPERTY__TYPE:
			return getType();
		case MessagepropertiesPackage.PROPERTY__ID:
			return getID();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */

	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
		case MessagepropertiesPackage.PROPERTY__QNAME:
			setQName((QName) newValue);
			return;
		case MessagepropertiesPackage.PROPERTY__NAME:
			setName((String) newValue);
			return;
		case MessagepropertiesPackage.PROPERTY__TYPE:
			setType(newValue);
			return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */

	public void eUnset(int featureID) {
		switch (featureID) {
		case MessagepropertiesPackage.PROPERTY__QNAME:
			setQName(QNAME_EDEFAULT);
			return;
		case MessagepropertiesPackage.PROPERTY__NAME:
			setName(NAME_EDEFAULT);
			return;
		case MessagepropertiesPackage.PROPERTY__TYPE:
			setType(TYPE_EDEFAULT);
			return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */

	public boolean eIsSet(int featureID) {
		switch (featureID) {
		case MessagepropertiesPackage.PROPERTY__QNAME:
			return QNAME_EDEFAULT == null ? qName != null : !QNAME_EDEFAULT
					.equals(qName);
		case MessagepropertiesPackage.PROPERTY__NAME:
			return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT
					.equals(name);
		case MessagepropertiesPackage.PROPERTY__TYPE:
			return TYPE_EDEFAULT == null ? type != null : !TYPE_EDEFAULT
					.equals(type);
		case MessagepropertiesPackage.PROPERTY__ID:
			return ID_EDEFAULT == null ? getID() != null : !ID_EDEFAULT
					.equals(getID());
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */

	public String toString() {
		if (eIsProxy())
			return super.toString();

		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (qName: "); //$NON-NLS-1$
		result.append(qName);
		result.append(", name: "); //$NON-NLS-1$
		result.append(name);
		result.append(", type: "); //$NON-NLS-1$
		result.append(type);
		result.append(')');
		return result.toString();
	}

	/**
	 * Override the XML element token.
	 */

	public QName getElementType() {
		if (elementType == null)
			elementType = new QName(MessagepropertiesConstants.NAMESPACE,
					MessagepropertiesConstants.PROPERTY_ELEMENT_TAG);
		return elementType;
	}

	//
	// Reconcile methods: DOM -> Model
	//

	public void reconcileAttributes(Element changedElement) {
		super.reconcileAttributes(changedElement);

		setName(MessagepropertiesConstants.getAttribute(changedElement,
				MessagepropertiesConstants.PROPERTY_NAME_ATTRIBUTE));

		reconcileReferences(false);
	}

	public void reconcileReferences(boolean deep) {
		Definition definition = getEnclosingDefinition();
		Element element = getElement();
		if (element != null
				&& element
						.hasAttribute(MessagepropertiesConstants.PROPERTY_TYPE_ATTRIBUTE)) {
			QName qname = createQName(
					definition,
					element.getAttribute(MessagepropertiesConstants.PROPERTY_TYPE_ATTRIBUTE));
			if (qname != null) {
				XSDTypeDefinition xsdType = ((DefinitionImpl) definition)
						.resolveTypeDefinition(qname.getNamespaceURI(),
								qname.getLocalPart());
				if (xsdType != null && getType() != xsdType) {
					setType(xsdType);
				}
			}
		}
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=330813
		// https://jira.jboss.org/browse/JBIDE-7107
		// added element handling
		if (element != null
				&& element
						.hasAttribute(MessagepropertiesConstants.PROPERTY_XSD_ELEMENT_ATTRIBUTE)) {
			QName qname = createQName(
					definition,
					element.getAttribute(MessagepropertiesConstants.PROPERTY_XSD_ELEMENT_ATTRIBUTE));
			if (qname != null) {
				XSDElementDeclaration xsdElement = ((DefinitionImpl) definition)
						.resolveElementDeclaration(qname.getNamespaceURI(),
								qname.getLocalPart());
				if (xsdElement != null && getType() != xsdElement) {
					setType(xsdElement);
				}
			}
		}
		super.reconcileReferences(deep);
	}

	public void handleUnreconciledElement(Element child,
			Collection remainingModelObjects) {
	}

	//
	// For reconciliation: Model -> DOM
	//

	protected void changeAttribute(EAttribute eAttribute) {
		if (isReconciling)
			return;

		super.changeAttribute(eAttribute);
		Element theElement = getElement();
		if (theElement != null) {
			if (eAttribute == null
					|| eAttribute == MessagepropertiesPackage.eINSTANCE
							.getProperty_Name()) {
				niceSetAttribute(theElement,
						MessagepropertiesConstants.PROPERTY_NAME_ATTRIBUTE,
						getName());
			}

			if (eAttribute == null
					|| eAttribute == MessagepropertiesPackage.eINSTANCE
							.getProperty_Type()) {
				// https://bugs.eclipse.org/bugs/show_bug.cgi?id=330813
				// https://jira.jboss.org/browse/JBIDE-7107
				// this is unfortunate, but the Property model object only has a "type" which serves both
				// for "type" and "element" addressing - we just have to figure out which is which from the
				// stored object type before serializing to WSDL.
				Object type = getType();
				if (type instanceof XSDTypeDefinition) {
					XSDTypeDefinition xsdType = (XSDTypeDefinition) type;
					String uri = xsdType.getURI();
					niceSetAttributeURIValue(
							theElement,
							MessagepropertiesConstants.PROPERTY_XSD_ELEMENT_ATTRIBUTE,
							null);
					niceSetAttributeURIValue(theElement,
							MessagepropertiesConstants.PROPERTY_TYPE_ATTRIBUTE,
							uri);
				} else if (type instanceof XSDElementDeclaration) {
					XSDElementDeclaration xsdElement = (XSDElementDeclaration) type;
					String uri = xsdElement.getURI();
					niceSetAttributeURIValue(
							theElement,
							MessagepropertiesConstants.PROPERTY_XSD_ELEMENT_ATTRIBUTE,
							uri);
					niceSetAttributeURIValue(theElement,
							MessagepropertiesConstants.PROPERTY_TYPE_ATTRIBUTE,
							null);
				}
			}
		}
	}

	public Element createElement() {
		// Register a prefix for the namespace.
		// If we don't do this, the WSDL model will deserialize our elements as UnknownExtensibilityElements.
		//if (getEnclosingDefinition().getPrefix(MessagepropertiesConstants.NAMESPACE) == null) {
		//	getEnclosingDefinition().addNamespace(MessagepropertiesPackage.eNS_PREFIX, MessagepropertiesConstants.NAMESPACE);
		// }

		Element newElement = super.createElement();

		return newElement;
	}

} //PropertyImpl


text:
yum -y install python-pip
### 清理cache
yum clean all

### 升级pip
pip install --upgrade pip

### 安装virtualenv
pip install virtualenv
### 创建虚拟环境
virtualenv venv
### 激活虚拟环境
source bin/activate
### 离开
(env) [root@iZ25zrelpocZ virtualenv]# deactivate

### pip安装requirements.txt依赖
pip install -r requirements.txt
### 查看当前已安装包是否可升级
pip list --outdated
### 升级pip已安装所有包
pip list --outdated | grep '^[a-z]* (' | cut -d " " -f 1 | xargs pip install -U
### pip生成requirements.txt文件
pip freeze > requirements.txt

redpajama_set_name: RedPajamaGithub


text:
namespace views {
class Window;
}

class TestViewsDelegate : public views::ViewsDelegate {
 public:
  TestViewsDelegate();
  virtual ~TestViewsDelegate();

  // Overridden from views::ViewsDelegate:
  virtual ui::Clipboard* GetClipboard() const;
  virtual void SaveWindowPlacement(views::Window* window,
                                   const std::wstring& window_name,
                                   const gfx::Rect& bounds,
                                   bool maximized) OVERRIDE { }
  virtual bool GetSavedWindowBounds(views::Window* window,
                                    const std::wstring& window_name,
                                    gfx::Rect* bounds) const;

  virtual bool GetSavedMaximizedState(views::Window* window,
                                      const std::wstring& window_name,
                                      bool* maximized) const;

  virtual void NotifyAccessibilityEvent(
      views::View* view, ui::AccessibilityTypes::Event event_type) OVERRIDE {}

  virtual void NotifyMenuItemFocused(
      const std::wstring& menu_name,
      const std::wstring& menu_item_name,
      int item_index,
      int item_count,
      bool has_submenu) {}
#if defined(OS_WIN)
  virtual HICON GetDefaultWindowIcon() const OVERRIDE {
    return NULL;
  }
#endif

  virtual void AddRef() OVERRIDE {}
  virtual void ReleaseRef() OVERRIDE {}

 private:
  mutable scoped_ptr<ui::Clipboard> clipboard_;

  DISALLOW_COPY_AND_ASSIGN(TestViewsDelegate);
};

#endif  // VIEWS_TEST_TEST_VIEWS_DELEGATE_H_


text:
# Cecil

The code in this section is based on the Cecil project.


text:
@interface NSString (HashColor)

- (UIColor *)hashColor;

@end


text:
module.exports = function(app) {
  app.factory('calcService', function() {

    // sanitize input to only recognize numbers
    var sanitize = function(inputString) {
      if (!inputString) return null; // early return to prevent console errors
      var strArray = inputString.match(/-?\.?[0-9]+\.?[0-9]*/g);
      if (!strArray) return null; // same, prevent console errors
      var numArray = strArray.map(parseFloat);
      return numArray;
    };

    // convert array to comma-separated string
    var stringify = function(someArray) {
      if (!someArray) return null;
      return someArray.join(', ');
    };

    // sort array ascending
    var sortify = function(someArray) {
      if (!someArray) return null;
      return someArray.sort(function (a, b) { return a - b; });
    };

    // calc object passed to controller
    var calc = {
      displaySorted: function(inputString) {
        if (!inputString || !sanitize(inputString)) return null;
        return stringify(sortify(sanitize(inputString)));
      },

      calcMean: function(inputString) {
        var numArray = sanitize(inputString);
        if (!numArray) return null;
        if (numArray.length < 2) return numArray[0];
        sum = numArray.reduce(function (a, b) {
          return +a + +b;
        });
        mean = sum / numArray.length;
        return mean;
      },

      calcMedian: function(inputString) {
        var numArray = sanitize(inputString);
        if (!numArray) return null;
        var sorted = sortify(numArray);

        // if array length is odd
        if (sorted.length % 2) {
          return sorted[Math.floor(sorted.length / 2)];
        }
        // if array length is even
        else {
          var el1 = sorted[Math.floor(sorted.length / 2)];
          var el2 = sorted[Math.floor(sorted.length / 2 - 1)];
          return (el1 + el2) / 2;
        };
      },

      calcMode: function(inputString) {
        var numArray = sanitize(inputString);
        if (!numArray) return null;
        // Assumes multiple modes possible.
        // If all inputs unique, all are modes.
        var modeMap = {},
            maxCount = 0,
            modes = [numArray[0]];

        for(var i = 0; i < numArray.length; i++) {
          var el = numArray[i];

          if (modeMap[el] == null) { modeMap[el] = 1; }
          else { modeMap[el]++; }

          if (modeMap[el] > maxCount) {
            modes = [el];
            maxCount = modeMap[el];
          } else if (modeMap[el] == maxCount) {
            modes.push(el);
            maxCount = modeMap[el];
          }
        }
        return stringify(sortify(modes));
      }
    };
    return calc;
  });
};


text:
using AutoMapper;
using Euricom.IoT.Api.Dtos;
using Euricom.IoT.Api.Managers;
using Euricom.IoT.Api.Managers.Interfaces;
using Euricom.IoT.Api.Utilities;
using Restup.Webserver.Attributes;
using Restup.Webserver.Models.Contracts;
using Restup.Webserver.Models.Schemas;
using Restup.WebServer.Attributes;
using System;

namespace Euricom.IoT.Api.Controllers
{
    [Authorize]
    [RestController(InstanceCreationType.Singleton)]
    public class LogController
    {
        private readonly ILogManager _logManager;

        public LogController()
        {
            _logManager = new LogManager();
        }

        [UriFormat("/logs")]
        public IGetResponse QueryLogFiles()
        {
            try
            {
                var logFiles = _logManager.QueryLogFiles();
                return ResponseUtilities.GetResponseOk(logFiles);
            }
            catch (Exception ex)
            {
                Logging.Logger.Instance.LogErrorWithContext(this.GetType(), ex);
                throw new Exception($"Could not get log: exception: {ex.Message}");
            }
        }

        [UriFormat("/logs_openzwave")]
        public IGetResponse GetOpenZWaveLog()
        {
            try
            {
                var logFiles = _logManager.GetOpenZWaveLog();
                return ResponseUtilities.GetResponseOk(logFiles);
            }
            catch (Exception ex)
            {
                Logging.Logger.Instance.LogErrorWithContext(this.GetType(), ex);
                throw new Exception($"Could not get log: exception: {ex.Message}");
            }
        }

        [UriFormat("/logs/{day}")]
        public IGetResponse GetAll(string day)
        {
            try
            {
                var log = _logManager.GetLog(day);
                var logDto = Mapper.Map<LogDto>(log);
                return ResponseUtilities.GetResponseOk(logDto);
            }
            catch (Exception ex)
            {
                Logging.Logger.Instance.LogErrorWithContext(this.GetType(), ex);
                throw new Exception($"Could not get log: exception: {ex.Message}");
            }
        }
    }
}


text:
<?php
  session_start();
  if (!isset($_SESSION["uid"])) {
    header("Location: Login/index.html");
  }
  if($_SESSION["code"] != "1"){
    echo "";
  }
?>

          DAVID

          內湖思恩堂

            Toggle navigation

                  4

You have 4 messages

                            Support Team
                             5 mins

Why not buy a new awesome theme?

See All Messages

                  10

You have 10 notifications

                           5 new members joined today

View all

                  9

You have 9 tasks

                            Design some buttons
                            20%

                              20% Complete

                    View all tasks

                  <?php echo $_SESSION["name"]; ?>

                      <?php echo $_SESSION["name"]; ?>
                      <?php echo $_SESSION["group_name"]; ?>

                      個人資料

                      登出

<?php echo $_SESSION["name"]; ?>

HEADER

 公告事項

               詩歌管理

詩歌查詢

詩歌新增

詩歌清單

 小組回報單

 敬拜表單

 Another Link

               系統管理

公告管理


text:
package dfa.analyses;

import dfa.framework.DFADirection;
import dfa.framework.DFAFactory;
import dfa.framework.DataFlowAnalysis;
import dfa.framework.SimpleBlockGraph;

/**
 * A {@code ReachingDefinitionsFactory} creates {@code ReachingDefinitionsAnalysis}-Instances from a
 * {@code SimpleBlockGraph}.
 *
 * @author Nils Jessen
 */
public class ReachingDefinitionsFactory extends DFAFactory<ReachingDefinitionsElement> {

    @Override
    public String getName() {
        return "Reaching-Definitions";
    }

    @Override
    public DFADirection getDirection() {
        return DFADirection.FORWARD;
    }

    @Override
    public DataFlowAnalysis<ReachingDefinitionsElement> getAnalysis(SimpleBlockGraph blockGraph) {
        return new ReachingDefinitionsAnalysis(blockGraph);
    }

}


text:
sudo apt-get install --only-upgrade fontconfig=2.11.0-0ubuntu4.2 -y
sudo apt-get install --only-upgrade libfontconfig1=2.11.0-0ubuntu4.2 -y


text:
const path = require('path');
const webpack = require('webpack');

module.exports = {
    entry: './src/dexie.mongoify.js',
    output: {
        path: './dist',
        filename: 'dexie.mongoify.min.js',
        libraryTarget: 'umd'
    },
    externals: {
        'dexie': 'Dexie'
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            minimize: true,
            output: {
                comments: false
            }
        })
    ]
};


text:
if [ -f elasticsearch-1.1.0.deb ]
then
    echo "elasticsearch is already here! Stop downloading!"
else
    wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.1.0.deb
fi
echo "Install Elasticsearch"
echo "WARNING: if Elasticsearch is already installed the next command will"
echo "force to install 1.1.0"
echo "using sudo dpkg -i --force-confnew elasticsearch-1.1.0.deb"
echo "Please press cntrl+C to abort"
sudo dpkg -i --force-confnew elasticsearch-1.1.0.deb
echo "Start Elasticsearch"
sudo service elasticsearch start


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/theme_item"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/text_field_without_top_border"
        android:paddingBottom="@dimen/content_padding"
        android:paddingLeft="@dimen/content_padding"
        android:paddingRight="@dimen/content_padding"
        android:paddingTop="10.0dip"
        android:text="我要要么上山打老虎我要要么上山打老虎我要要么上山打老虎我要要么上山打老虎我要要么上山打老虎"
        android:textColor="#ff555555"
        android:textSize="15.0sp" />

</LinearLayout>


text:
//  xibLocalizationPostprocessor.m
//
//  Created by William Shipley on 4/14/08.
//  Copyright © 2005-2009 Golden % Braeburn, LLC.

#import <Cocoa/Cocoa.h>

NSDictionary *load_kv_pairs(NSString *input);

int main(int argc, const char *argv[])
{
    NSAutoreleasePool *autoreleasePool = [[NSAutoreleasePool alloc] init]; {
        if (argc != 3 && argc != 4) {
            fprintf(stderr, "Usage: xibLocalizationPostprocessor inputfile outputfile (Replace IB keys with their English string value)\n");
			fprintf(stderr, "       xibLocalizationPostprocessor transfile inputfile outputfile (Reverse mode: Change English keys back to IB keys in translation)\n");
            exit (-1);
        }

		NSUInteger inputFileIndex = 1;
		NSDictionary *translatedStrings = nil;
		if(argc == 4) {
			NSError *error = nil;
			NSStringEncoding usedEncoding;
			NSString *translatedFile = [NSString stringWithContentsOfFile:[NSString stringWithUTF8String:argv[1]] usedEncoding:&usedEncoding error:&error];
			if (error) {
				fprintf(stderr, "Error reading transfile %s: %s\n", argv[1], error.localizedDescription.UTF8String);
				exit (-1);
			}
			translatedStrings = load_kv_pairs(translatedFile);

			inputFileIndex++;
		}

        NSError *error = nil;
        NSStringEncoding usedEncoding;
        NSString *rawXIBStrings = [NSString stringWithContentsOfFile:[NSString stringWithUTF8String:argv[inputFileIndex]] usedEncoding:&usedEncoding error:&error];
        if (error) {
            fprintf(stderr, "Error reading inputfile %s: %s\n", argv[inputFileIndex], error.localizedDescription.UTF8String);
            exit (-1);
        }

        NSMutableString *outputStrings = [NSMutableString string];
        NSUInteger lineCount = 0;
        NSString *lastComment = nil;
        for (NSString *line in [rawXIBStrings componentsSeparatedByString:@"\n"]) {
            lineCount++;

            if ([line hasPrefix:@"/*"]) { // eg: /* Class = "NSMenuItem"; title = "Quit Library"; ObjectID = "136"; */
                lastComment = line;
                continue;

            } else if (line.length == 0) {
                lastComment = nil;
                continue;

            } else if ([line hasPrefix:@"\""] && [line hasSuffix:@"\";"]) { // eg: "136.title" = "Quit Library";

                NSRange quoteEqualsQuoteRange = [line rangeOfString:@"\" = \""];
                if (quoteEqualsQuoteRange.length && NSMaxRange(quoteEqualsQuoteRange) < line.length - 1) {
                    if (lastComment) {
                        [outputStrings appendString:lastComment];
                        [outputStrings appendString:@"\n"];
                    }
					NSString *stringNeedingLocalization = [line substringFromIndex:NSMaxRange(quoteEqualsQuoteRange)]; // chop off leading: "blah" = "
                    stringNeedingLocalization = [stringNeedingLocalization substringToIndex:stringNeedingLocalization.length - 2]; // chop off trailing: ";
					if(translatedStrings) {
						NSString *translation = [translatedStrings objectForKey:stringNeedingLocalization];
						if(!translation) {
							fprintf(stderr, "Warning: key \"%s\" not found in transfile.\n",[stringNeedingLocalization UTF8String]);
							translation = stringNeedingLocalization; //fallback to untranslated
						}
						[outputStrings appendFormat:@"%@\" = \"%@\";\n\n", [line substringToIndex:quoteEqualsQuoteRange.location], translation];
					}
					else {
						[outputStrings appendFormat:@"\"%@\" = \"%@\";\n\n", stringNeedingLocalization, stringNeedingLocalization];
					}

                    continue;
                }
            }

            NSLog(@"Warning: skipped garbage input line %lu, contents: \"%@\"", (unsigned long)lineCount, line);
        }

        if (outputStrings.length && ![outputStrings writeToFile:[NSString stringWithUTF8String:argv[inputFileIndex+1]] atomically:NO encoding:usedEncoding error:&error]) {
            fprintf(stderr, "Error writing %s: %s\n", argv[inputFileIndex+1], error.localizedDescription.UTF8String);
            exit (-1);
        }
    } [autoreleasePool release];
}

NSDictionary *load_kv_pairs(NSString *input)
{
	NSDictionary *result = [NSMutableDictionary dictionary];

	NSUInteger lineCount = 0;
	//don't try [NSString enumerateLines...] here. It supports some obscure Unicode line breaks!
	for (NSString *line in [input componentsSeparatedByString:@"\n"]) {
		lineCount++;

		if (line.length == 0 || [line hasPrefix:@"/*"]) {
			continue;
		}

		if ([line hasPrefix:@"\""] && [line hasSuffix:@"\";"]) { // eg: "136.title" = "Quit Library";

			NSRange quoteEqualsQuoteRange = [line rangeOfString:@"\" = \""];
			if (quoteEqualsQuoteRange.location != NSNotFound && quoteEqualsQuoteRange.length && NSMaxRange(quoteEqualsQuoteRange) < line.length - 1) {
				NSRange keyRange = NSMakeRange(1,quoteEqualsQuoteRange.location - 1); //the first " is always at pos. 0 (we checked that above)
				NSString *key = [line substringWithRange:keyRange];
				NSString *value = [line substringFromIndex:NSMaxRange(quoteEqualsQuoteRange)]; // chop off leading: "blah" = "
				value = [value substringToIndex:[value length] - 2]; // chop off trailing: ";
				[result setValue:value forKey:key];
				continue;
			}
		}

		NSLog(@"Warning: skipped garbage trans line %lu, contents: \"%@\"", (unsigned long)lineCount, line);
	}

	return result;
}


text:
import Kefir from 'kefir';

// lodash functions
import isBoolean from 'lodash/isBoolean';
import isNull from 'lodash/isNull';
import isString from 'lodash/isString';

// libs
import arrayFlatMap from './lib/arrayFlatMap';
import event$ from './lib/event$';

// actors
import dom from './actors/dom';
import firebase from './actors/firebase';
import storage from './actors/storage';
import url from './actors/url';

// The App Conductor. Responsible for mapping events to state changes.
export default data => {
	// create a logging function
	const observer = (name, color) => data.env === 'development' ? {
		value: v => console.log(`%c${name}: ${JSON.stringify(v)}`,`background:${color}`),
		error: console.error
	} : {};

	// create the input/output pools
	const events = Kefir.pool();
	const changes = Kefir.pool();

	// a shared change pool was a bad idea.
	const firebaseChanges = Kefir.pool();

	// activate (and log) the pools
	events.observe(observer('e','#fef'));
	changes.observe(observer('c','#eff'));
	firebaseChanges.observe(observer('f','#cff'));

	// confirm my changes to topic happen before reading new value
	const pending$ = Kefir.merge([
		event$(events, 'set:topic').filter(isString).map(() => 1),
		event$(events, 'report:topic').filter(isString).map(() => -1)
	]);
	const nonePending$ = pending$.scan((a,b) => Math.max(a + b, 0), 0).map(pending => pending === 0);
	const negPending$ = pending$.scan((a,b) => a + b, 0).map(pending => pending < 0);
	changes.plug(event$(events, 'change:topic').filterBy(nonePending$).map(topic => ({topic})));
	changes.plug(event$(events, 'report:topic').filterBy(negPending$).map(topic => ({topic})));

	// simple change event to state change passthrough
	changes.plug(arrayFlatMap(
		['name', 'show_votes', 'users', 'vote'],
		key => event$(events, `change:${key}`).map(val => ({[key]:val}))
	));
	firebaseChanges.plug(event$(events, 'change:name').map(name => ({name})));

	// simple set event to state change passthrough
	firebaseChanges.plug(arrayFlatMap(
		['name', 'topic', 'vote'],
		key => event$(events, `set:${key}`).map(val => ({[key]:val}))
	));
	changes.plug(event$(events, 'set:name').map(name => ({name})));

	// is_voter change event if the value is a boolean
	const isVoter$ = event$(events, 'change:is_voter').filter(isBoolean).map(is_voter => ({is_voter}));
	changes.plug(isVoter$);
	firebaseChanges.plug(isVoter$);

	// is_editor change event if the value is a boolean
	const isEditor$ = event$(events, 'change:is_editor').filter(isBoolean).map(is_editor => ({is_editor}));
	changes.plug(isEditor$);
	firebaseChanges.plug(isEditor$);

	// set room on submit
	changes.plug(event$(events, 'submit:room').skipDuplicates().map(room => ({room})));
	firebaseChanges.plug(event$(events, 'submit:room').skipDuplicates().map(room => ({room})));

	// set deck
	changes.plug(event$(events, 'change:votes').filter().map(votes => ({votes})));
	firebaseChanges.plug(event$(events, 'change:votes').filter(isNull).map(() => ({votes: data.defaultVotes})));

	// reset action
	firebaseChanges.plug(Kefir.constant({
		show_votes: false,
		topic: '',
		clear_votes: true
	}).sampledBy(event$(events, 'click:reset')));

	// reveal action
	firebaseChanges.plug(Kefir.constant({
		show_votes: true
	}).sampledBy(event$(events, 'click:reveal')));

	// connect firebase actor
	events.plug(firebase(firebaseChanges));

	// connect other actors
	events.plug(
		arrayFlatMap(
			[dom, storage, url],
			actor => actor(changes)
		)
	);

	// initial state
	const init$ = Kefir.constant({ firebase: data.firebase });
	firebaseChanges.plug(init$);
	changes.plug(init$);
};


text:
using System;
using System.Linq;
using System.Windows.Input;

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

using WPF.Controls.Console.Services;

namespace WPF.Controls.Client
{
    class MainWindowViewModel : ViewModelBase
    {
        readonly ConsoleService _consoleService;

        public MainWindowViewModel(ConsoleService consoleService)
        {
            _consoleService = consoleService;

            ExecuteCommand = new RelayCommand<string>(Execute);
        }

        public ICommand ExecuteCommand
        {
            get;
            private set;
        }

        private void Execute(string commandLine)
        {
            var parts = commandLine.Split(' ');
            var command = parts[0];

            switch (command)
            {
                case "echo":
                    _consoleService.WriteLine(parts.Skip(1).Aggregate((s1, s2) => s1 + " " + s2));
                    break;

                case "time":
                    _consoleService.WriteLine(DateTime.Now.ToLongTimeString());
                    break;

                case "date":
                    _consoleService.WriteLine(DateTime.Now.ToLongDateString());
                    break;

                case "cls":
                case "clear":
                    _consoleService.Clear();
                    break;

                case "help":
                    _consoleService.WriteLine("Supported commands:");
                    _consoleService.WriteLine("\techo [text] - display text on next line");
                    _consoleService.WriteLine("\ttime        - display current time");
                    _consoleService.WriteLine("\tdate        - display current date");
                    _consoleService.WriteLine("\tclear       - clear command line");
                    break;

                default:
                    _consoleService.WriteLine("Try typing 'help' into the console and pressing enter.");
                    break;
            }
        }
    }
}


text:
local starts     = { 'Experiential truth ', 'The physical world ', 'Non-judgment ', 'Quantum physics '}
local middles    = {'nurtures an ', 'projects onto ', 'imparts reality to ', 'constructs with '}
local qualifiers = {'abundance of ', 'the barrier of ', 'self-righteous ', 'potential '}
local finishes   = {'marvel.', 'choices.', 'creativity.', 'actions.'}

print(starts[math.random( #starts )] .. middles[math.random( #middles )] .. qualifiers[math.random( #qualifiers )] .. finishes[math.random( #finishes )] .. '\n')


text:
//This is the service worker with the Cache-first network

var CACHE = 'pwabuilder-precache';
var precacheFiles = [
      /* Add an array of files to precache for your app */
    ];

//Install stage sets up the cache-array to configure pre-cache content
self.addEventListener('install', function(evt) {
  console.log('[PWA Builder] The service worker is being installed.');
  evt.waitUntil(precache().then(function() {
    console.log('[PWA Builder] Skip waiting on install');
    return self.skipWaiting();
  }));
});

//allow sw to control of current page
self.addEventListener('activate', function(event) {
  console.log('[PWA Builder] Claiming clients for current page');
  return self.clients.claim();
});

self.addEventListener('fetch', function(evt) {
  console.log('[PWA Builder] The service worker is serving the asset.'+ evt.request.url);
  evt.respondWith(fromCache(evt.request).catch(fromServer(evt.request)));
  evt.waitUntil(update(evt.request));
});

function precache() {
  return caches.open(CACHE).then(function (cache) {
    return cache.addAll(precacheFiles);
  });
}

function fromCache(request) {
  //we pull files from the cache first thing so we can show them fast
  return caches.open(CACHE).then(function (cache) {
    return cache.match(request).then(function (matching) {
      return matching || Promise.reject('no-match');
    });
  });
}

function update(request) {
  //this is where we call the server to get the newest version of the
  //file to use the next time we show view
  return caches.open(CACHE).then(function (cache) {
    return fetch(request).then(function (response) {
      return cache.put(request, response);
    });
  });
}

function fromServer(request){
  //this is the fallback if it is not in the cache to go to the server and get it
  return fetch(request).then(function(response){ return response});
}


text:
import AVATARS from '../constants/default_avatars';
const AVATARS_LENGTH = AVATARS.length;

export default(num = 0) => {
  return AVATARS[num % AVATARS_LENGTH];
};


text:
package selenium_cherkasov.applogic1;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;

import selenium_cherkasov.applogic.UserHelper;
import selenium_cherkasov.model.User;
import selenium_cherkasov.pages.EditAccountPage;

public class UserHelper1 extends DriverBasedHelper implements UserHelper {

  public UserHelper1(ApplicationManager1 manager) {
    super(manager.getWebDriver());
  }

  @Override
  public void loginAs(User user) {
    pages.loginPage.ensurePageLoaded()
      .setUsernameField(user.getUsername())
      .setPasswordField(user.getPassword())
      .clickSubmitButton();
  }

  @Override
  public void logout() {

    pages.internalPage.ensurePageLoaded()
      .clickLogoutLink();
  }

  @Override
  public boolean isLoggedIn() {
    return pages.internalPage.waitPageLoaded();
  }

  @Override
  public boolean isLoggedInAs(User user) {
    return isLoggedIn()
        && getLoggedUser().getFirstname().equals(user.getFirstname());
  }

  @Override
  public boolean isNotLoggedIn() {
    return pages.loginPage.waitPageLoaded();
  }

  private User getLoggedUser() {
	  EditAccountPage userProfile = pages.internalPage.ensurePageLoaded()
      .clickEditAccountPage()
      .ensurePageLoaded();
    return new User()
      .setFirstname(userProfile.getFirstName())
      .setLastname(userProfile.getLastName());
       }

@Override
public void createUser(User user) {
	pages.loginPage.ensurePageLoaded().clickRegisterAsANewUserLink();
	pages.registerNewUserPage.ensurePageLoaded()
	.setNameField(user.getUsername())
	.setFirstNameField(user.getFirstname())
	.setLastNameField(user.getLastname())
	.setPasswordField(user.getPassword())
	.setPasswordConfirmField(user.getPassword())
	.setRole(user.getRole())
	.clickRegisterButton();
	}

@Override
public void clickMyApplicationsLink() {
  pages.internalPage.ensurePageLoaded()
  .clickMyApplicationsPage();
}

@Override
public boolean isElementPresent(By locator) {
	try {
		driver.findElement(locator);
		return true;
	}
	catch (NoSuchElementException e)
	{
		return false;
	}
	}

}


text: ![Järjestelmän komponenttikaavio](https://raw.githubusercontent.com/theikkila/lopputili/master/doc/components.png)


text:
import { Injectable, Pipe, PipeTransform } from '@angular/core';

@Pipe({
 name: 'searchfilter'
})

@Injectable()
export class SearchFilterPipe implements PipeTransform {
    transform(pipeData:string[], pipeModifier:string): string[] {
        return pipeData.filter((eachItem) => {
          return eachItem['name'].toLowerCase().includes(pipeModifier.toLowerCase());
        });

}}


text:
% This function finds the error rate between predicted labels and actual labels
%
% Parameters
% predictedVector: Vector(N x 1)
% actualVector: Vector(N x 1)
%
% Returns
% errorRate: Scalar (1x1) contains balanced error rate

function [ errorRates ] = FindErrorRate( predictedLabels, actualLabels )

    totalErrorsOfClass2 = 0;
    totalErrorsOfClass5 = 0;
    totalErrorsOfClass7 = 0;
    totalOfClass2 = 0;
    totalOfClass5 = 0;
    totalOfClass7 = 0;

    % Loop through each Label
    for i = 1:size(predictedLabels)
        switch actualLabels(i)
            case 2
                % Calculate total classes to find the error ratio of Class 1
                totalOfClass2 = totalOfClass2 + 1;
                % Increment the error count if it was not predicted to be
                % Class 1
                if predictedLabels(i) ~= 2
                    totalErrorsOfClass2 = totalErrorsOfClass2 + 1;
                end
            case 5
                % Calculate total classes to find the error ratio of Class 2
                totalOfClass5 = totalOfClass5 + 1;
                % Increment the error count if it was not predicted to be
                % Class 2
                if predictedLabels(i) ~= 5
                    totalErrorsOfClass5 = totalErrorsOfClass5 + 1;
                end
            case 7
                % Calculate total classes to find the error ratio of Class 2
                totalOfClass7 = totalOfClass7 + 1;
                % Increment the error count if it was not predicted to be
                % Class 2
                if predictedLabels(i) ~= 7
                    totalErrorsOfClass7 = totalErrorsOfClass7 + 1;
                end
        end
    end

    errorRates(1) = totalErrorsOfClass2;
    errorRates(2) = totalErrorsOfClass5;
    errorRates(3) = totalErrorsOfClass7;
    errorRates(4) = (totalErrorsOfClass2 / totalOfClass2 + totalErrorsOfClass5 / totalOfClass5 + totalErrorsOfClass7 / totalOfClass7)/3;

end


text:
from midonetclient import resource_base
from midonetclient import vendor_media_type

class L2Insertion(resource_base.ResourceBase):

    media_type = vendor_media_type.APPLICATION_L2INSERTION_JSON

    def __init__(self, uri, dto, auth):
        super(L2Insertion, self).__init__(uri, dto, auth)

    def get_id(self):
        return self.dto['id']

    def get_port(self):
        return self.dto['portId']

    def get_srv_port(self):
        return self.dto['srvPortId']

    def get_vlan(self):
        return self.dto['vlan']

    def get_position(self):
        return self.dto['position']

    def get_fail_open(self):
        return self.dto['failOpen']

    def get_mac(self):
        return self.dto['mac']

    def id(self, id):
        self.dto['id'] = id
        return self

    def port(self, port):
        self.dto['portId'] = port
        return self

    def srv_port(self, srv_port):
        self.dto['srvPortId'] = srv_port
        return self

    def vlan(self, vlan):
        self.dto['vlan'] = vlan
        return self

    def position(self, position):
        self.dto['position'] = position
        return self

    def fail_open(self, fail_open):
        self.dto['failOpen'] = fail_open
        return self

    def mac(self, mac):
        self.dto['mac'] = mac
        return self


text:
<?php

namespace Propel\Generator\Behavior\Sortable\Component\Repository;

use Propel\Generator\Builder\Om\Component\BuildComponent;
use Propel\Generator\Builder\Om\Component\NamingTrait;

/**
 * @author Cristiano Cinotti <cristianocinotti@gmail.com>
 */
class GetSortableManagerMethod extends BuildComponent
{
    use NamingTrait;

    public function process()
    {
        $body = <<<EOF
if (!isset(\$this->sortableManager)) {
    \$this->sortableManager = new \\{$this->getObjectClassName(true)}SortableManager();
}

return \$this->sortableManager;
EOF;

        $this->addMethod('getSortableManager')
            ->setDescription('Return the Sortable entity manager object')
            ->setType('\Propel\Runtime\EntityManager\SortableManagerInterface')
            ->setBody($body)
        ;
    }
}


text:
/*----------------------------------------------------------------------------
   These are declarations for use with the Portable Arbitrary Map (PAM)
   format and the Netpbm library functions specific to them.
-----------------------------------------------------------------------------*/

#ifndef PAM_H
#define PAM_H

#include "pm.h"
#include "pnm.h"

#ifdef __cplusplus
extern "C" {
#endif
#if 0
} /* to fake out automatic code indenters */
#endif

typedef unsigned long sample;
    /* Regardless of the capacity of "unsigned long", a sample is always
       less than 1 << 16.  This is essential for some code to avoid
       arithmetic overflows.
    */

struct pam {
/* This structure describes an open PAM image file.  It consists
   entirely of information that belongs in the header of a PAM image
   and filesystem information.  It does not contain any state
   information about the processing of that image.

   This is not considered to be an opaque object.  The user of Netbpm
   libraries is free to access and set any of these fields whenever
   appropriate.  The structure exists to make coding of function calls
   easy.
*/

    /* 'size' and 'len' are necessary in order to provide forward and
       backward compatibility between library functions and calling programs
       as this structure grows.
       */
    unsigned int size;
        /* The storage size of this entire structure, in bytes */
    unsigned int len;
        /* The length, in bytes, of the information in this structure.
           The information starts in the first byte and is contiguous.
           This cannot be greater than 'size'
           */
    FILE * file;
    int format;
        /* The format code of the raw image.  This is PAM_FORMAT
           unless the PAM image is really a view of a PBM, PGM, or PPM
           image.  Then it's PBM_FORMAT, RPBM_FORMAT, etc.
           */
    unsigned int plainformat;
        /* Logical: On output, use the plain version of the format type
           indicated by 'format'.  Otherwise, use the raw version.
           (i.e., on output, the plainness information in 'format' is
           irrelevant).  Input functions set this to FALSE, for the
           convenience of programs that copy an input pam structure for
           use with output.

           Before Netpbm 10.32, this was rather different.  It simply
           described for convenience the plainness of the format indicated
           by 'format'.
        */
    int height;  /* Height of image in rows */
    int width;
        /* Width of image in number of columns (tuples per row) */
    unsigned int depth;
        /* Depth of image (number of samples in each tuple). */
    sample maxval;  /* Maximum defined value for a sample */
    unsigned int bytes_per_sample;
        /* Number of bytes used to represent each sample in the image file.
           Note that this is strictly a function of 'maxval'.  It is in a
           a separate member for computational speed.
        */
    char tuple_type[256];
        /* The tuple type string from the image header.  If the PAM image
           is really a view of a PBM, PGM, or PPM image, the value is
           PAM_PBM_TUPLETYPE, PAM_PGM_TUPLETYPE, or PAM_PPM_TUPLETYPE,
           respectively.
        */
    unsigned int allocation_depth;
        /* The number of samples for which memory is allocated for any
           'tuple' type associated with this PAM structure.  This must
           be at least as great as 'depth'.  Only the first 'depth' of
           the samples of a tuple are meaningful.

           The purpose of this is to make it possible for a program to
           change the type of a tuple to one with more or fewer
           planes.

           0 means the allocation depth is the same as the image depth.
        */
    const char ** comment_p;
        /* Pointer to a pointer to a NUL-terminated ASCII string of
           comments.  When reading an image, this contains the
           comments from the image's PAM header; when writing, the
           image gets these as comments, right after the magic number
           line.  The individual comments are delimited by newlines
           and are in the same order as in the PAM header.

           On output, NULL means no comments.

           On input, libnetpbm mallocs storage for the comments and placed
           the pointer at *comment_p.  Caller must free it.  NULL means
           libnetpbm does not return comments and does not allocate any
           storage.
        */
};

#define PAM_HAVE_ALLOCATION_DEPTH 1
#define PAM_HAVE_COMMENT_P 1

/* PAM_STRUCT_SIZE(x) tells you how big a struct pam is up through the
   member named x.  This is useful in conjunction with the 'len' value
   to determine which fields are present in the structure.
*/

/* Some compilers are really vigilant and recognize it as an error
   to cast a 64 bit address to a 32 bit type.  Hence the roundabout
   casting in PAM_MEMBER_OFFSET.
*/
#define PAM_MEMBER_OFFSET(mbrname) \
  ((size_t)(unsigned long)(char*)&((struct pam *)0)->mbrname)
#define PAM_MEMBER_SIZE(mbrname) \
  sizeof(((struct pam *)0)->mbrname)
#define PAM_STRUCT_SIZE(mbrname) \
  (PAM_MEMBER_OFFSET(mbrname) + PAM_MEMBER_SIZE(mbrname))

#define PAM_BLACK 0
#define PAM_BW_WHITE 1

#define PAM_PBM_TUPLETYPE "BLACKANDWHITE"
#define PAM_PGM_TUPLETYPE "GRAYSCALE"
#define PAM_PPM_TUPLETYPE "RGB"

#define PAM_PBM_BLACK PAM_BLACK
#define PAM_PBM_WHITE PAM_BW_WHITE
    /* These are values of samples in a PAM image that represents a black
       and white bitmap image.  They are the values of black and white,
       respectively.  For example, if you use pnm_readpamrow() to read a
       row from a PBM file, the black pixels get returned as
       PAM_PBM_BLACK.
    */

#define PAM_RED_PLANE 0
#define PAM_GRN_PLANE 1
#define PAM_BLU_PLANE 2
    /* These are plane numbers for the 3 planes of a PAM image that
       represents an RGB image (tuple type is "RGB").  So
       if 'pixel' is a tuple returned by pnmreadpamrow(), then
       pixel[PAM_GRN_PLANE] is the value of the green sample in that
       pixel.
       */
#define PAM_TRN_PLANE 3
    /* A PAM with "RGB_ALPHA" tuple type has this 4th plane
       for transparency.  0 = transparent, maxval = opaque.
    */
#define PAM_GRAY_TRN_PLANE 1
    /* For a "GRAYSCALE" tuple type, this is the transparency plane */

typedef sample *tuple;
    /* A tuple in a PAM.  This is an array such that tuple[i-1] is the
       ith sample (element) in the tuple.  It's dimension is the depth
       of the image (see pam.depth above).
    */

#define PAM_OVERALL_MAXVAL 65535

/* Note: xv uses the same "P7" signature for its thumbnail images (it
   started using it years before PAM and unbeknownst to the designer
   of PAM).  But these images are still easily distinguishable from
   PAMs
*/
#define PAM_MAGIC1 'P'
#define PAM_MAGIC2 '7'
#define PAM_FORMAT (PAM_MAGIC1 * 256 + PAM_MAGIC2)
#define PAM_TYPE PAM_FORMAT

/* Macro for turning a format number into a type number. */

#define PAM_FORMAT_TYPE(f) ((f) == PAM_FORMAT ? PAM_TYPE : PPM_FORMAT_TYPE(f))

struct pamtuples {
    struct pam * pamP;
    tuple ***    tuplesP;
};

typedef float * pnm_transformMap;
    /* This is an array of transform maps.  transform[N] is the
       array that is the map for Plane N.

       Transform maps define a transformation between PAM sample value
       to normalized libnetpbm "samplen" value, i.e. what you get back
       from pnm_readpamrown() or pass to pnm_writepamrown().
       Typically, it's a gamma transfer function generated by
       pnm_creategammatransform() or pnm_createungammatransform().

       NULL for any transform means just plain normalization -- divide
       the PAM sample value by the maxval to get the samplen, multiply
       samplen by the maxval and round to get PAM sample value.

       NULL for map table, or 'transform' member not present (pam
       structure is too small to contain it) means ALL transforms
       are plain normalization.

       Each transform map is an array indexed by a PAM sample
       value, containing 'float' values.  So it must have 'maxval'
       entries.  The sample -> samplen tranformation is just the
       obvious table lookup.  The samplen -> sample transformation is
       more complicated -- if the samplen value is between map[N]
       and map[N+1], then the sample value is N.  And only transforms
       where map[N+1] > map[N] are allowed.
    */

/* Declarations of library functions. */

/* We don't have a specific PAM function for init and nextimage, because
   one can simply use pnm_init() and pnm_nextimage() from pnm.h.
*/

unsigned int
pnm_bytespersample(sample const maxval);

int
pnm_tupleequal(const struct pam * const pamP,
               tuple              const comparand,
               tuple              const comparator);

void
pnm_assigntuple(const struct pam * const pamP,
                tuple              const dest,
                tuple              const source);

static __inline__ sample
pnm_scalesample(sample const source,
                sample const oldmaxval,
                sample const newmaxval) {

    if (oldmaxval == newmaxval)
        /* Fast path for common case */
        return source;
    else
        return (source * newmaxval + (oldmaxval/2)) / oldmaxval;
}

void
pnm_scaletuple(const struct pam * const pamP,
               tuple              const dest,
               tuple              const source,
               sample             const newmaxval);

void
pnm_scaletuplerow(const struct pam * const pamP,
                  tuple *            const destRow,
                  tuple *            const sourceRow,
                  sample             const newMaxval);

void
pnm_maketuplergb(const struct pam * const pamP,
                 tuple              const tuple);

void
pnm_makerowrgb(const struct pam * const pamP,
               tuple *            const tuplerow);

void
pnm_makearrayrgb(const struct pam * const pamP,
                 tuple **           const tuples);

void
pnm_getopacity(const struct pam * const pamP,
               int *              const haveOpacityP,
               unsigned int *     const opacityPlaneP);

void
pnm_createBlackTuple(const struct pam * const pamP, tuple * const blackTupleP);

void
createBlackTuple(const struct pam * const pamP, tuple * const blackTupleP);

tuple
pnm_allocpamtuple(const struct pam * const pamP);

#define pnm_freepamtuple(tuple) pm_freerow((char*) tuple)

tuple *
pnm_allocpamrow(const struct pam * const pamP);

#define pnm_freepamrow(tuplerow) pm_freerow((char*) tuplerow)

tuple **
pnm_allocpamarray(const struct pam * const pamP);

void
pnm_freepamarray(tuple ** const tuplearray, const struct pam * const pamP);

void
pnm_setminallocationdepth(struct pam * const pamP,
                          unsigned int const allocationDepth);

void
pnm_setpamrow(const struct pam * const pam,
              tuple *            const tuplerow,
              sample             const value);

unsigned char *
pnm_allocrowimage(const struct pam * const pamP);

void
pnm_freerowimage(unsigned char * const rowimage);

void
pnm_readpaminit(FILE *       const file,
                struct pam * const pamP,
                int          const size);

void
pnm_readpamrow(const struct pam * const pamP, tuple* const tuplerow);

tuple **
pnm_readpam(FILE *       const file,
            struct pam * const pamP,
            int          const size);

void
pnm_writepaminit(struct pam * const pamP);

void
pnm_formatpamrow(const struct pam * const pamP,
                 const tuple *      const tuplerow,
                 unsigned char *    const outbuf,
                 unsigned int *     const rowSizeP);

void
pnm_writepamrow(const struct pam * const pamP, const tuple * const tuplerow);

void
pnm_writepamrowmult(const struct pam * const pamP,
                    const tuple *      const tuplerow,
                    unsigned int       const rptcnt);

void
pnm_writepam(struct pam * const pamP, tuple ** const tuplearray);

void
pnm_checkpam(const struct pam *   const pamP,
             enum pm_check_type   const checkType,
             enum pm_check_code * const retvalP);

/*----------------------------------------------------------------------------
   Facilities for working with maxval-normalized samples.  Such samples
   are floating point quantities in the range 0..1.

   This is just a working format; there is no Netpbm image format that
   has normalized samples.
-----------------------------------------------------------------------------*/
typedef float samplen;

typedef samplen *tuplen;
    /* Same as 'tuple', except using normalized samples. */

tuplen *
pnm_allocpamrown(const struct pam * const pamP);

#define pnm_freepamrown(tuplenrow) pm_freerow((char*) tuplenrow)

tuplen *
pnm_allocpamrown(const struct pam * const pamP);

void
pnm_readpamrown(const struct pam * const pamP,
                tuplen *           const tuplenrow);

void
pnm_writepamrown(const struct pam * const pamP,
                 const tuplen *     const tuplenrow);

tuplen **
pnm_allocpamarrayn(const struct pam * const pamP);

void
pnm_freepamarrayn(tuplen **          const tuplenarray,
                  const struct pam * const pamP);

tuplen**
pnm_readpamn(FILE *       const file,
             struct pam * const pamP,
             int          const size);

void
pnm_writepamn(struct pam * const pamP,
              tuplen **    const tuplenarray);

void
pnm_normalizetuple(struct pam * const pamP,
                   tuple        const tuple,
                   tuplen       const tuplen);

void
pnm_unnormalizetuple(struct pam * const pamP,
                     tuplen       const tuplen,
                     tuple        const tuple);

void
pnm_normalizeRow(struct pam *             const pamP,
                 const tuple *            const tuplerow,
                 const pnm_transformMap * const transform,
                 tuplen *                 const tuplenrow);

void
pnm_unnormalizeRow(struct pam *             const pamP,
                   const tuplen *           const tuplenrow,
                   const pnm_transformMap * const transform,
                   tuple *                  const tuplerow);

/*----------------------------------------------------------------------------
   Facilities for working with visual images in particular
-----------------------------------------------------------------------------*/

void
pnm_gammarown(struct pam * const pamP,
              tuplen *     const row);

void
pnm_ungammarown(struct pam * const pamP,
                tuplen *     const row);

void
pnm_applyopacityrown(struct pam * const pamP,
                     tuplen *     const tuplenrow);

void
pnm_unapplyopacityrown(struct pam * const pamP,
                       tuplen *     const tuplenrow);

pnm_transformMap *
pnm_creategammatransform(const struct pam * const pamP);

void
pnm_freegammatransform(const pnm_transformMap * const transform,
                       const struct pam *       const pamP);

pnm_transformMap *
pnm_createungammatransform(const struct pam * const pamP);

#define pnm_freeungammatransform pnm_freegammatransform;

tuple
pnm_parsecolor(const char * const colorname,
               sample       const maxval);

extern double
pnm_lumin_factor[3];

void
pnm_YCbCrtuple(const tuple tuple,
               double * const YP, double * const CbP, double * const CrP);

void
pnm_YCbCr_to_rgbtuple(const struct pam * const pamP,
                      tuple              const tuple,
                      double             const Y,
                      double             const Cb,
                      double             const Cr,
                      int *              const overflowP);

#define pnm_rgbtupleisgray(tuple) \
    ((tuple)[PAM_RED_PLANE] == (tuple)[PAM_GRN_PLANE] && \
     (tuple)[PAM_RED_PLANE] == (tuple)[PAM_BLU_PLANE])

/*----------------------------------------------------------------------------
   These are meant for passing to pm_system() as Standard Input feeder
   and Standard Output accepter.
-----------------------------------------------------------------------------*/

void
pm_feed_from_pamtuples(int    const pipeToFeedFd,
                       void * const feederParm);

void
pm_accept_to_pamtuples(int    const pipeToSuckFd,
                       void * const accepterParm);

#ifdef __cplusplus
}
#endif
#endif


text:
<?php

namespace Pyrus\Installer\Role;

/**
 * Test role
 *
 * @category  Pyrus
 * @package   Pyrus
 * @author    Greg Beaver <cellog@php.net>
 * @copyright 2010 The PEAR Group
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @link      https://github.com/pyrus/Pyrus
 */
class Test extends \Pyrus\Installer\Role\Common {}
?>


text:
package privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.statistics.chart;

import android.content.Context;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.framework.utils.StringUtils;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.logic.statistics.business.domain.StatisticsQuery;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.statistics.StatisticsCache;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class PFAChart
{
    private static final int ANIMATION_DURATION = 2000;
    private BarChart chart;
    private Context context;
    private StatisticsCache cache;

    public PFAChart(StatisticsCache cache)
    {
        this.cache = cache;
        this.context = cache.getActivity().getApplicationContext();

        this.chart = cache.getChart();
        this.chart.setDrawBarShadow(false);
        this.chart.setDrawValueAboveBar(true);
        this.chart.setDescription(StringUtils.EMPTY);
        this.chart.setMaxVisibleValueCount(12);
        this.chart.setPinchZoom(false);
        this.chart.setDrawGridBackground(false);
        this.chart.getLegend().setEnabled(false);
        setupYAxis();
    }

    public void updateChart(List<Double> inputData, List<String> labels, int... colors)
    {
        int count = inputData.size();
        setupYAxis();
        setXlabels(labels);

        float start = 0f;
        chart.getXAxis().setAxisMinValue(start);
        chart.getXAxis().setAxisMaxValue(start + count + 1);

        ArrayList<BarEntry> yValues = new ArrayList<>();

        for ( int i = (int) start; i < start + count; i++ )
        {
            BigDecimal number = new BigDecimal(inputData.get(i));
            yValues.add(new BarEntry(i + 1, number.floatValue()));
        }

        BarDataSet dataSet;
        int valuesSelectedItemPos = cache.getValuesSpinner().getSelectedItemPosition();

        if ( chart.getData() != null && chart.getData().getDataSetCount() > 0 )
        {
            dataSet = (BarDataSet) chart.getData().getDataSetByIndex(0);
            dataSet.setValues(yValues);

            chart.getData().setValueFormatter(new PFAValueFormatter(context, valuesSelectedItemPos, cache.getNumberScale()));

            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
            chart.invalidate();
        }
        else
        {
            dataSet = new BarDataSet(yValues, StringUtils.EMPTY);
            dataSet.setColors(colors);

            ArrayList<IBarDataSet> dataSets = new ArrayList<>();
            dataSets.add(dataSet);

            BarData data = new BarData(dataSets);
            data.setValueFormatter(new PFAValueFormatter(context, valuesSelectedItemPos, cache.getNumberScale()));
            data.setValueTextSize(10f);
            data.setBarWidth(0.9f);
            chart.setData(data);
        }
        chart.animateY(ANIMATION_DURATION);
        chart.fitScreen();
    }

    private void setXlabels(List<String> labelList)
    {
        int valuesSelectedItemPos = cache.getValuesSpinner().getSelectedItemPosition();
        String[] labels = new String[ labelList.size() ];
        labelList.toArray(labels);

        PFAXAxisLabels xFormatter = new PFAXAxisLabels(labels);
        chart.setMarkerView(new PFAMarkerView(context, xFormatter, valuesSelectedItemPos, cache.getNumberScale()));

        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(5);
        xAxis.setValueFormatter(xFormatter);
    }

    private void setupYAxis()
    {
        int valuesSelectedItemPos = cache.getValuesSpinner().getSelectedItemPosition();
        YAxis leftAxis = this.chart.getAxisLeft();
        leftAxis.setLabelCount(10, false);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(20f);
        leftAxis.setAxisMinValue(0f);
        leftAxis.setValueFormatter(new PFAYAxisLabels(context, valuesSelectedItemPos, cache.getNumberScale()));

        if ( valuesSelectedItemPos == StatisticsQuery.QUANTITY )
        {
            leftAxis.setGranularity(1f); // interval 1
        }

        YAxis rightAxis = this.chart.getAxisRight();
        rightAxis.setEnabled(false);
    }
}


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import os

from pants_test.pants_run_integration_test import PantsRunIntegrationTest

class JunitTestsIntegrationTest(PantsRunIntegrationTest):

  def _assert_junit_output_exists_for_class(self, workdir, classname):
    self.assertTrue(os.path.exists(
      os.path.join(workdir, 'test', 'junit', '{}.out.txt'.format(classname))))
    self.assertTrue(os.path.exists(
      os.path.join(workdir, 'test', 'junit', '{}.err.txt'.format(classname))))

  def _assert_junit_output(self, workdir):
    self._assert_junit_output_exists_for_class(workdir, 'org.pantsbuild.example.hello.greet.GreetingTest')
    self._assert_junit_output_exists_for_class(workdir, 'org.pantsbuild.example.hello.welcome.WelSpec')

  def test_junit_test_custom_interpreter(self):
    with self.temporary_workdir() as workdir:
      pants_run = self.run_pants_with_workdir([
          'test',
          'examples/tests/java/org/pantsbuild/example/hello/greet',
          'examples/tests/scala/org/pantsbuild/example/hello/welcome',
          '--interpreter=CPython>=2.6,<3',
          '--interpreter=CPython>=3.3'],
          workdir)
      self.assert_success(pants_run)
      self._assert_junit_output(workdir)

  def test_junit_test(self):
    with self.temporary_workdir() as workdir:
      pants_run = self.run_pants_with_workdir([
          'test',
          'testprojects/tests/scala/org/pantsbuild/testproject/empty'],
          workdir)
      self.assert_failure(pants_run)

  def test_junit_test_with_test_option_with_relpath(self):
    with self.temporary_workdir() as workdir:
      pants_run = self.run_pants_with_workdir([
          'test',
          '--test-junit-test=examples/tests/java/org/pantsbuild/example/hello/greet/GreetingTest.java',
          'examples/tests/java/org/pantsbuild/example/hello/greet',
          'examples/tests/scala/org/pantsbuild/example/hello/welcome'],
          workdir)
      self.assert_success(pants_run)
      self._assert_junit_output_exists_for_class(workdir, 'org.pantsbuild.example.hello.greet.GreetingTest')

  def test_junit_test_with_test_option_with_dot_slash_relpath(self):
    with self.temporary_workdir() as workdir:
      pants_run = self.run_pants_with_workdir([
          'test',
          '--test-junit-test=./examples/tests/java/org/pantsbuild/example/hello/greet/GreetingTest.java',
          'examples/tests/java/org/pantsbuild/example/hello/greet',
          'examples/tests/scala/org/pantsbuild/example/hello/welcome'],
          workdir)
      self.assert_success(pants_run)
      self._assert_junit_output_exists_for_class(workdir, 'org.pantsbuild.example.hello.greet.GreetingTest')

  def test_junit_test_with_test_option_with_classname(self):
    with self.temporary_workdir() as workdir:
      pants_run = self.run_pants_with_workdir([
          'test',
          '--test-junit-test=org.pantsbuild.example.hello.greet.GreetingTest',
          'examples/tests/java/org/pantsbuild/example/hello/greet',
          'examples/tests/scala/org/pantsbuild/example/hello/welcome'],
          workdir)
      self.assert_success(pants_run)
      self._assert_junit_output_exists_for_class(workdir, 'org.pantsbuild.example.hello.greet.GreetingTest')

  def test_junit_test_requiring_cwd_fails_without_option_specified(self):
    pants_run = self.run_pants([
        'test',
        'testprojects/tests/java/org/pantsbuild/testproject/cwdexample',
        '--interpreter=CPython>=2.6,<3',
        '--interpreter=CPython>=3.3',
        '--jvm-test-junit-options=-Dcwd.test.enabled=true'])
    self.assert_failure(pants_run)

  def test_junit_test_requiring_cwd_passes_with_option_with_value_specified(self):
    pants_run = self.run_pants([
        'test',
        'testprojects/tests/java/org/pantsbuild/testproject/cwdexample',
        '--interpreter=CPython>=2.6,<3',
        '--interpreter=CPython>=3.3',
        '--jvm-test-junit-options=-Dcwd.test.enabled=true',
        '--test-junit-cwd=testprojects/src/java/org/pantsbuild/testproject/cwdexample/subdir'])
    self.assert_success(pants_run)

  def test_junit_test_requiring_cwd_fails_with_option_with_no_value_specified(self):
    pants_run = self.run_pants([
        'test',
        'testprojects/tests/java/org/pantsbuild/testproject/cwdexample',
        '--interpreter=CPython>=2.6,<3',
        '--interpreter=CPython>=3.3',
        '--jvm-test-junit-options=-Dcwd.test.enabled=true'])
    self.assert_failure(pants_run)

  def test_junit_test_deprecated_suppress_output_flag(self):
    pants_run = self.run_pants([
        'test.junit',
        '--no-suppress-output',
        'testprojects/tests/java/org/pantsbuild/testproject/dummies:passing_target'])
    self.assertIn('Hello from test1!', pants_run.stdout_data)
    self.assertIn('Hello from test2!', pants_run.stdout_data)

    pants_run = self.run_pants([
        'test.junit',
        '--suppress-output',
        'testprojects/tests/java/org/pantsbuild/testproject/dummies:passing_target'])
    self.assertNotIn('Hello from test1!', pants_run.stdout_data)
    self.assertNotIn('Hello from test2!', pants_run.stdout_data)

  def test_junit_test_output_flag(self):
    def run_test(output_mode):
      args = ['test.junit', '--no-test-junit-fail-fast']
      if output_mode is not None:
        args.append('--output-mode=' + output_mode)
      args.append('testprojects/src/java/org/pantsbuild/testproject/junit/suppressoutput:tests')
      return self.run_pants(args)

    run_with_all_output = run_test('ALL')
    self.assertIn('Failure output', run_with_all_output.stdout_data)
    self.assertIn('Success output', run_with_all_output.stdout_data)

    run_with_failure_only_output = run_test('FAILURE_ONLY')
    self.assertIn('Failure output', run_with_failure_only_output.stdout_data)
    self.assertNotIn('Success output', run_with_failure_only_output.stdout_data)

    run_with_none_output = run_test('NONE')
    self.assertNotIn('Failure output', run_with_none_output)
    self.assertNotIn('Success output', run_with_none_output)

    run_with_default_output = run_test(None)
    self.assertNotIn('Failure output', run_with_default_output)
    self.assertNotIn('Success output', run_with_default_output)

  def test_junit_test_target_cwd(self):
    pants_run = self.run_pants([
      'test',
      'testprojects/tests/java/org/pantsbuild/testproject/workdirs/onedir',
    ])
    self.assert_success(pants_run)

  def test_junit_test_annotation_processor(self):
    pants_run = self.run_pants([
      'test',
      'testprojects/tests/java/org/pantsbuild/testproject/annotation',
    ])
    self.assert_success(pants_run)

  def test_junit_test_duplicate_resources(self):
    pants_run = self.run_pants([
      'test',
      'testprojects/maven_layout/junit_resource_collision',
    ])
    self.assert_success(pants_run)

  def test_junit_test_target_cwd_overrides_option(self):
    pants_run = self.run_pants([
      'test',
      'testprojects/tests/java/org/pantsbuild/testproject/workdirs/onedir',
      '--test-junit-cwd=testprojects/tests/java/org/pantsbuild/testproject/dummies'
    ])
    self.assert_success(pants_run)

  def test_junit_test_failure_summary(self):
    with self.temporary_workdir() as workdir:
      with self.source_clone('testprojects/src/java/org/pantsbuild/testproject/junit/failing') as failing:
        pants_run = self.run_pants_with_workdir([
          'test',
          '--test-junit-failure-summary',
          os.path.join(failing, 'tests', 'org', 'pantsbuild', 'tmp', 'tests'),
        ], workdir)
        self.assert_failure(pants_run)
        expected_groups = []
        expected_groups.append([
          'org/pantsbuild/tmp/tests:one',
          'org.pantsbuild.tmp.tests.OneTest#testSingle'
        ])
        expected_groups.append([
          'org/pantsbuild/tmp/tests:two',
          'org.pantsbuild.tmp.tests.TwoTest#testTupleFirst',
          'org.pantsbuild.tmp.tests.TwoTest#testTupleSecond',
        ])
        expected_groups.append([
          'org/pantsbuild/tmp/tests:three',
          'org.pantsbuild.tmp.tests.subtest.ThreeTest#testTripleFirst',
          'org.pantsbuild.tmp.tests.subtest.ThreeTest#testTripleSecond',
          'org.pantsbuild.tmp.tests.subtest.ThreeTest#testTripleThird',
        ])
        output = '\n'.join(line.strip() for line in pants_run.stdout_data.split('\n'))
        for group in expected_groups:
          self.assertIn('\n'.join(group), output)

  def test_junit_test_no_failure_summary(self):
    with self.temporary_workdir() as workdir:
      with self.source_clone('testprojects/src/java/org/pantsbuild/testproject/junit/failing') as failing:
        pants_run = self.run_pants_with_workdir([
          'test',
          '--no-test-junit-failure-summary',
          os.path.join(failing, 'tests', 'org', 'pantsbuild', 'tmp', 'tests')
        ], workdir)
        self.assert_failure(pants_run)
        output = '\n'.join(line.strip() for line in pants_run.stdout_data.split('\n'))
        self.assertNotIn('org/pantsbuild/tmp/tests:three\n'
                         'org.pantsbuild.tmp.tests.subtest.ThreeTest#testTripleFirst',
                         output)

  def test_junit_test_successes_and_failures(self):
    with self.temporary_workdir() as workdir:
      with self.source_clone('testprojects/src/java/org/pantsbuild/testproject/junit/mixed') as mixed:
        pants_run = self.run_pants_with_workdir([
          'test',
          '--test-junit-failure-summary',
          '--no-test-junit-fail-fast',
          os.path.join(mixed, 'tests', 'org', 'pantsbuild', 'tmp', 'tests'),
        ], workdir)
        group = [
          'org/pantsbuild/tmp/tests:tests',
          'org.pantsbuild.tmp.tests.AllTests#test1Failure',
          'org.pantsbuild.tmp.tests.AllTests#test3Failure',
          'org.pantsbuild.tmp.tests.AllTests#test4Error',
        ]
        output = '\n'.join(line.strip() for line in pants_run.stdout_data.split('\n'))
        self.assertIn('\n'.join(group), output,
                      '{group}\n not found in\n\n{output}.'.format(group='\n'.join(group),
                                                                   output=output))


text:
<#
	.SYNOPSIS
	Test getting restore points from stretch databases
#>
function Test-ListStretchDatabaseRestorePoints
{
	# Setup
	$location = Get-ProviderLocation "Microsoft.Sql/servers"
	$serverVersion = "12.0";
	$rg = Create-ResourceGroupForTest $location

	try
	{
		$server = Create-ServerForTest $rg $serverVersion $location

		# Create stretch database with all parameters.
		$databaseName = Get-DatabaseName
		$stretchdb = New-AzureRmSqlDatabase -ResourceGroupName $rg.ResourceGroupName -ServerName $server.ServerName -DatabaseName $databaseName `
			-Edition Stretch -RequestedServiceObjectiveName DS100

		# Get restore points from stretch database.
		$restorePoints = Get-AzureRmSqlDatabaseRestorePoints -ResourceGroupName $rg.ResourceGroupName -ServerName $server.ServerName -DatabaseName $stretchdb.DatabaseName
		Assert-Null $restorePoints # Since the stretch database has just been created, it should not have any discrete restore points.
	}
	finally
	{
		Remove-ResourceGroupForTest $rg
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Windows - Developer Blog</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="https://AppHat.github.io/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//AppHat.github.io/themes/casper/assets/css/screen.css?v=1469954698273" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="https://AppHat.github.io/https://AppHat.github.io/tag/Windows/" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="Developer Blog" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Windows - Developer Blog" />
    <meta property="og:url" content="https://AppHat.github.io/https://AppHat.github.io/tag/Windows/" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Windows - Developer Blog" />
    <meta name="twitter:url" content="https://AppHat.github.io/https://AppHat.github.io/tag/Windows/" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="Developer Blog" href="https://AppHat.github.io/rss/" />

Windows

                    A 1-post collection

        Page 1 of 1

Web-Multimessengers

Here are some new multi-messengers which support WhatsApp, Facebook Messenger, Telegram, Skype, Hangout, Slack, Inbox, GMail, Steam and more. 1. Rambox Open-Source alternative link: »

            Andreas Gehle
             on Web,  Messenger,  App,  Android,  Windows,  Unix
            <time class="post-date" datetime="2016-07-30">30 July 2016</time>

        Page 1 of 1

Developer Blog © 2016

Proudly published with HubPress


text:
"""
Testing the omex module.
"""
from __future__ import absolute_import, print_function
import os
import tempfile
import shutil
import pytest

from tellurium.tests.testdata import TESTDATA_DIR
from tellurium.tests.testdata import OMEX_SHOWCASE
from tellurium.utils import omex

def test_omex_extractCombineArchive1(tmpdir):
    omex.extractCombineArchive(omexPath=OMEX_SHOWCASE, directory=str(tmpdir), method="zip")

def test_omex_extractCombineArchive2(tmpdir):
    omex.extractCombineArchive(omexPath=OMEX_SHOWCASE, directory=str(tmpdir), method="omex")

def test_omex_extractCombineArchive3(tmpdir):
    tmp_dir = tempfile.mkdtemp()
    omex.extractCombineArchive(omexPath=OMEX_SHOWCASE, directory=str(tmpdir), method="zip")
    files = [f for f in os.listdir(tmp_dir) if os.path.isfile(os.path.join(tmp_dir, f))]
    assert files is not None

def test_omex_extractCombineArchive4(tmpdir):
    tmp_dir = tempfile.mkdtemp()
    omex.extractCombineArchive(omexPath=OMEX_SHOWCASE, directory=str(tmpdir), method="omex")
    files = [f for f in os.listdir(tmp_dir) if os.path.isfile(os.path.join(tmp_dir, f))]
    assert files is not None

# testing the omex based methods
def test_getLocationsByFormat1():
    locations = omex.getLocationsByFormat(omexPath=OMEX_SHOWCASE, formatKey="sed-ml")
    assert len(locations) == 2

def test_getLocationsByFormat2():
    locations = omex.getLocationsByFormat(omexPath=OMEX_SHOWCASE, formatKey="sbml")
    assert len(locations) == 1

def test_getLocationsByFormat3():
    locations = omex.getLocationsByFormat(omexPath=OMEX_SHOWCASE, formatKey="cellml")
    assert len(locations) == 1

def test_getLocationsByFormat4():
    locations = omex.getLocationsByFormat(omexPath=OMEX_SHOWCASE, formatKey="sed-ml")
    assert len(locations) == 2
    # master=True file first
    assert locations[0].endswith("Calzone2007-simulation-figure-1B.xml")
    # master=False afterwards
    assert locations[1].endswith("Calzone2007-default-simulation.xml")

# test the zip based methods
def test_getLocationsByFormat1_zip():
    locations = omex.getLocationsByFormat(omexPath=OMEX_SHOWCASE, formatKey="sed-ml", method="zip")
    assert len(locations) == 2

def test_getLocationsByFormat2_zip():
    locations = omex.getLocationsByFormat(omexPath=OMEX_SHOWCASE, formatKey="sbml", method="zip")
    assert len(locations) == 1

def test_getLocationsByFormat3_zip():
    locations = omex.getLocationsByFormat(omexPath=OMEX_SHOWCASE, formatKey="cellml", method="zip")
    assert len(locations) == 1

def test_getLocationsByFormat4_zip():
    locations = omex.getLocationsByFormat(omexPath=OMEX_SHOWCASE, formatKey="sed-ml", method="zip")
    assert len(locations) == 2
    # in case of zip files no master file exists, so the order of the entries depends on
    # filenames and how they are returned from the zip
    assert "experiment/Calzone2007-simulation-figure-1B.xml" in locations
    assert "experiment/Calzone2007-default-simulation.xml" in locations

def test_listContents():
    contents = omex.listContents(omexPath=OMEX_SHOWCASE, method="omex")
    assert len(contents) == 20

def test_printContents():
    omex.printContents(omexPath=OMEX_SHOWCASE)

def test_createCombineArchiveFromDirectory():
    """ Testing if COMBINE archive can be created from directory."""
    omexPath = tempfile.NamedTemporaryFile(suffix="omex")
    directory = os.path.join(TESTDATA_DIR, "utils", "omex_from_zip")
    omex.combineArchiveFromDirectory(omexPath=omexPath.name, directory=directory)
    assert omexPath is not None
    # TODO: additional checks via extracting information from the archive again


text:
LIST=VARIANT
ifndef QRECURSE
QRECURSE=recurse.mk
ifdef QCONFIG
QRDIR=$(dir $(QCONFIG))
endif
endif
include $(QRDIR)$(QRECURSE)


text:
<?php

namespace Test\Files\Storage\Wrapper;

use OC\Files\Storage\Common;
use OCP\Files\Storage\IStorage;
use OCP\Files\Storage\IVersionedStorage;

class JailTest extends \Test\Files\Storage\Storage {

	/**
	 * @var \OC\Files\Storage\Temporary
	 */
	private $sourceStorage;

	public function setUp(): void {
		parent::setUp();
		$this->sourceStorage = new \OC\Files\Storage\Temporary([]);
		$this->sourceStorage->mkdir('foo');
		$this->instance = new \OC\Files\Storage\Wrapper\Jail([
			'storage' => $this->sourceStorage,
			'root' => 'foo'
		]);
	}

	public function tearDown(): void {
		// test that nothing outside our jail is touched
		$contents = [];
		$dh = $this->sourceStorage->opendir('');
		while ($file = \readdir($dh)) {
			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
				$contents[] = $file;
			}
		}
		$this->assertEquals(['foo'], $contents);
		$this->sourceStorage->cleanUp();
		parent::tearDown();
	}

	public function testMkDirRooted() {
		$this->instance->mkdir('bar');
		$this->assertTrue($this->sourceStorage->is_dir('foo/bar'));
	}

	public function testFilePutContentsRooted() {
		$this->instance->file_put_contents('bar', 'asd');
		$this->assertEquals('asd', $this->sourceStorage->file_get_contents('foo/bar'));
	}

	public function providesVersionMethods() {
		return [
			['getContentOfVersion', 1014],
			['restoreVersion', 1014],
			['saveVersion'],
			['getVersions'],
			['getVersion', 1014],
		];
	}

	/**
	 * @dataProvider providesVersionMethods
	 */
	public function testCallsSourceVersionMethods($method, $extraArg = null) {
		$sourceStorage = $this->createMock(Common::class);
		$instance = new \OC\Files\Storage\Wrapper\Jail([
			'storage' => $sourceStorage,
			'root' => 'foo'
		]);

		$matcher = $sourceStorage->expects($this->once())
			->method($method);
		// FIXME: normalize path...
		if ($extraArg !== null) {
			$matcher = $matcher->with('foo//bar', $extraArg);
		} else {
			$matcher = $matcher->with('foo//bar');
		}
		$matcher->willReturn('returnValue');

		$this->assertEquals('returnValue', $instance->$method('/bar', $extraArg));
	}
}


text:
'use strict';

var assign = require('object-assign');
var through = require('through2');
var gs = require('glob-stream');
var File = require('vinyl');
var duplexify = require('duplexify');
var merge = require('merge-stream');
var sourcemaps = require('gulp-sourcemaps');
var filterSince = require('../filterSince');
var isValidGlob = require('is-valid-glob');

var getContents = require('./getContents');
var resolveSymlinks = require('./resolveSymlinks');

function createFile(globFile, enc, cb) {
  cb(null, new File(globFile));
}

function src(glob, opt) {
  var options = assign({
    read: true,
    buffer: true,
    sourcemaps: false,
    passthrough: false,
    followSymlinks: true
  }, opt);

  var inputPass;

  if (!isValidGlob(glob)) {
    throw new Error('Invalid glob argument: ' + glob);
  }

  var globStream = gs.create(glob, options);

  var outputStream = globStream
    .pipe(resolveSymlinks(options))
    .pipe(through.obj(createFile));

  if (options.since != null) {
    outputStream = outputStream
      .pipe(filterSince(options.since));
  }

  if (options.read !== false) {
    outputStream = outputStream
      .pipe(getContents(options));
  }

  if (options.passthrough === true) {
    inputPass = through.obj();
    outputStream = duplexify.obj(inputPass, merge(outputStream, inputPass));
  }
  if (options.sourcemaps === true) {
    outputStream = outputStream
      .pipe(sourcemaps.init({loadMaps: true}));
  }
  globStream.on('error', outputStream.emit.bind(outputStream, 'error'));
  return outputStream;
}

module.exports = src;


text:
layout: page
title: Ramos Pink Studios Party
date: 2016-05-24
author: Heather Stevenson
tags: weekly links, java
status: published
summary: Cras tempus nibh neque. Morbi quis.
banner: images/banner/people.jpg
booking:
  startDate: 06/16/2019
  endDate: 06/20/2019
  ctyhocn: MSYDTHX
  groupCode: RPSP
published: true
---
Maecenas aliquet libero non libero eleifend maximus. Praesent ornare venenatis metus sed faucibus. Curabitur eu diam erat. Nulla facilisi. Nunc rhoncus interdum hendrerit. Etiam varius suscipit justo, lobortis aliquam elit accumsan sit amet. Aliquam maximus, mi eget porttitor sodales, risus erat sollicitudin massa, at accumsan libero justo consequat tortor. Sed varius iaculis nisi, vitae efficitur sem egestas vel. Proin ultricies ac odio eget egestas.

* Nam bibendum lacus sit amet feugiat ullamcorper
* Nunc vulputate tellus quis mi tempor, ut laoreet mi efficitur
* Sed vel tortor eu nunc lacinia ultricies eu sit amet tellus
* Maecenas vehicula tortor ac risus finibus condimentum
* Donec fringilla nibh cursus nulla ultrices, a venenatis mauris faucibus
* Sed porttitor nibh et dolor posuere, sed eleifend quam ultricies.

Ut vitae erat id risus scelerisque laoreet nec ullamcorper dolor. Quisque arcu elit, consequat in convallis eu, tempus sed diam. Phasellus suscipit purus neque, in viverra est sollicitudin ac. Vivamus euismod turpis at purus facilisis sagittis. Maecenas tempus, orci vel ultricies faucibus, neque mauris eleifend nisl, non blandit magna diam id sem. Cras vitae nisi eget ex hendrerit placerat. Sed mollis hendrerit ex, sit amet consequat quam venenatis eget. Fusce eget imperdiet lectus. Pellentesque eget fringilla massa. Etiam aliquam iaculis tincidunt. Praesent ut urna luctus, vulputate nulla quis, pulvinar enim. Cras feugiat orci nec lectus aliquam egestas. Sed facilisis non lectus eu blandit.


text:
package org.apache.cassandra.concurrent;

/**
 * Centralized location for shared executors
 */
public class ScheduledExecutors
{
    /**
     * This pool is used for periodic short (sub-second) tasks.
     */
     public static final DebuggableScheduledThreadPoolExecutor scheduledTasks = new DebuggableScheduledThreadPoolExecutor("ScheduledTasks");

    /**
     * This executor is used for tasks that can have longer execution times, and usually are non periodic.
     */
    public static final DebuggableScheduledThreadPoolExecutor nonPeriodicTasks = new DebuggableScheduledThreadPoolExecutor("NonPeriodicTasks");
    static
    {
        nonPeriodicTasks.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    }

    /**
     * This executor is used for tasks that do not need to be waited for on shutdown/drain.//wxc pro 2015-8-7:13:43:32 这里的wait与否在哪里体现?
     */
    public static final DebuggableScheduledThreadPoolExecutor optionalTasks = new DebuggableScheduledThreadPoolExecutor("OptionalTasks");
}


text:
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
)

var robotsTxtHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Last-Modified", "sometime")
	fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
})

func BenchmarkSingleFetch(b *testing.B) {
	ts := httptest.NewServer(robotsTxtHandler)
	defer ts.Close()
	for i := 0; i < b.N; i++ {
		fetch(ts.URL)
	}
}
func BenchmarkParallelFetch(b *testing.B) {
	ts := httptest.NewServer(robotsTxtHandler)
	defer ts.Close()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			fetch(ts.URL)
		}
	})
}