text:
import os
from itertools import permutations, combinations

import gasteiger
from pysimm.system import Angle, Dihedral, Improper
from forcefield import Forcefield

class Tip3p(Forcefield):
    """pysimm.forcefield.Tip3p

    Forcefield object with typing rules for Tip3p model.
    By default reads data file in forcefields subdirectory.

    Attributes:
        ff_name: tip3p
        pair_style: lj
        ff_class: 1
    """
    def __init__(self, db_file=None):
        if not db_file and db_file is not False:
            db_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                   os.pardir, os.pardir, 'dat', 'forcefields', 'tip3p.xml')
        Forcefield.__init__(self, db_file)
        self.name = 'tip3p'
        self.pair_style = 'lj'
        self.ff_class = '1'

    def assign_ptypes(self, s):
        """pysimm.forcefield.Tip3p.assign_ptypes

        Tip3p specific particle typing rules.
        Requires :class:`~pysimm.system.System` object :class:`~pysimm.system.Particle` objects have bonds defined.
        *** use System.add_particle_bonding() to ensure this ***

        Args:
            s: :class:`~pysimm.system.System`

        Returns:
            None
        """
        all_types = set()
        s.pair_style = self.pair_style
        for p in s.particles:
            p.bonded_to = [x.a if p is x.b else x.b for x in p.bonds]
            p.bond_orders = [x.order for x in p.bonds]
            if None in p.bond_orders:
                error_print('error: bond orders are not set')
            p.bond_elements = [x.a.elem if p is x.b else x.b.elem for x in
                               p.bonds]
            p.nbonds = len(p.bond_elements)
        for p in s.particles:
            if p.elem == 'H':
                p.type_name = 'hw'
            elif p.elem == 'O':
                p.type_name = 'ow'
            else:
                print 'cant type particle %s' % p.tag
                return p

            type_ = self.particle_types.get(p.type_name)
            if not type_:
                print(p.tag, p.elem, p.type_name)

            all_types.add(self.particle_types.get(p.type_name)[0])

        for pt in all_types:
            pt = pt.copy()
            s.particle_types.add(pt)

        for p in s.particles:
            pt = s.particle_types.get(p.type_name)
            if pt:
                p.type = pt[0]

    def assign_btypes(self, s):
        """pysimm.forcefield.Tip3p.assign_btypes

        Tip3p specific bond typing rules.
        Requires :class:`~pysimm.system.System` object :class:`~pysimm.system.Particle` objects have type and type.name defined.
        *** use after assign_ptypes ***

        Args:
            s: :class:`~pysimm.system.System`

        Returns:
            None
        """
        all_types = set()
        for b in s.bonds:
            bt = self.bond_types.get('%s,%s' % (b.a.type.name, b.b.type.name))
            if bt:
                b.type_name = bt[0].name
            else:
                print ('couldnt type this bond %s,%s'
                       % (b.a.type.name, b.b.type.name))
                return b
            all_types.add(self.bond_types.get(b.type_name)[0])

        for bt in all_types:
            bt = bt.copy()
            s.bond_types.add(bt)

        for b in s.bonds:
            bt = s.bond_types.get(b.type_name)
            if bt:
                b.type = bt[0]

    def assign_atypes(self, s):
        """pysimm.forcefield.Tip3p.assign_atypes

        Tip3p specific angle typing rules.
        Requires :class:`~pysimm.system.System` object :class:`~pysimm.system.Particle` objects have bonds, type and type.name defined.
        *** use after assign_ptypes ***

        Args:
            s: :class:`~pysimm.system.System`

        Returns:
            None
        """
        all_types = set()
        for p in s.particles:
            p.bonded_to = [x.a if p is x.b else x.b for x in p.bonds]
            for p1 in p.bonded_to:
                for p2 in p.bonded_to:
                    if p1 is not p2:
                        unique = True
                        for a in s.angles:
                            if ((a.a is p1 and a.b is p and a.c is p2) or
                                    (a.a is p2 and a.b is p and a.c is p1)):
                                unique = False
                        if unique:
                            at = self.angle_types.get('%s,%s,%s'
                                                      % (p1.type.name,
                                                         p.type.name,
                                                         p2.type.name))
                            if at:
                                s.angles.add(Angle(type_name=at[0].name,
                                                   a=p1, b=p, c=p2))
                                all_types.add(at[0])
                            else:
                                print ('I cant type this angle %s,%s,%s'
                                       % (p1.type.name,
                                          p.type.name,
                                          p2.type.name))

        for at in all_types:
            at = at.copy()
            s.angle_types.add(at)

        for a in s.angles:
            at = s.angle_types.get(a.type_name)
            if at:
                a.type = at[0]

    def assign_dtypes(self, s):
        """pysimm.forcefield.Tip3p.assign_dtypes

        Tip3p specific dihedral typing rules.
        There are none.

        Args:
            s: :class:`~pysimm.system.System`

        Returns:
            None
        """
        pass

    def assign_itypes(self, s):
        """pysimm.forcefield.Tip3p.assign_itypes

        Tip3p specific improper typing rules.
        There are none.

        Args:
            s: :class:`~pysimm.system.System`

        Returns:
            None
        """
        pass

    def assign_charges(self, s, charges='default'):
        """pysimm.forcefield.Tip3p.assign_charges

        Tip3p specific charge assignment.
        There are none.

        Args:
            s: :class:`~pysimm.system.System`
            charges: default

        Returns:
            None
        """
        if charges == 'gasteiger':
            print('adding gasteiger charges')
            gasteiger.set_charges(s)
        elif charges == 'default':
            print('adding default TIP3P charges')
            for p in s.particles:
                p.charge = 0
            for b in s.bonds:
                n1 = b.a.type.eq_bond or b.a.type.name
                n2 = b.b.type.eq_bond or b.b.type.name
                btype = self.bond_types.get('%s,%s' % (n1, n2))
                if btype:
                    btype = btype[0]
                    if btype.name == '%s,%s' % (n1, n2):
                        b.a.charge += float(btype.q1)
                        b.b.charge += float(btype.q2)
                    elif btype.name == '%s,%s' % (n2, n1):
                        b.a.charge += float(btype.q2)
                        b.b.charge += float(btype.q1)


text:
package com.google.template.soy.data;

import com.google.template.soy.data.restricted.BooleanData;
import com.google.template.soy.data.restricted.FloatData;
import com.google.template.soy.data.restricted.IntegerData;
import com.google.template.soy.data.restricted.NullData;
import com.google.template.soy.data.restricted.StringData;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * Abstract base class for all nodes in a Soy data tree.
 *
 * <p>Important: Even though this class is not marked 'final', do not extend this class.
 *
 */
public abstract class SoyData extends SoyAbstractValue {

  /**
   * Creates deprecated SoyData objects from standard Java data structures.
   *
   * @param obj The existing object or data structure to convert.
   * @return A SoyData object or tree that corresponds to the given object.
   * @throws SoyDataException If the given object cannot be converted to SoyData.
   * @deprecated It's best to pass whatever object you have directly to the Soy templates you're
   *     using -- Soy understands primitives, lists, and maps natively, and if you install runtime
   *     support you can also pass protocol buffers. If you're interacting directly with the Soy
   *     runtime and need SoyValue objects, use SoyValueConverter instead.
   */
  @Deprecated
  public static SoyData createFromExistingData(Object obj) {

    // Important: This is frozen for backwards compatibility, For future changes (pun not intended),
    // use SoyValueConverter, which works with the new interfaces SoyValue and SoyValueProvider.

    if (obj == null) {
      return NullData.INSTANCE;
    } else if (obj instanceof SoyData) {
      return (SoyData) obj;
    } else if (obj instanceof String) {
      return StringData.forValue((String) obj);
    } else if (obj instanceof Boolean) {
      return BooleanData.forValue((Boolean) obj);
    } else if (obj instanceof Integer) {
      return IntegerData.forValue((Integer) obj);
    } else if (obj instanceof Long) {
      return IntegerData.forValue((Long) obj);
    } else if (obj instanceof Map<?, ?>) {
      @SuppressWarnings("unchecked")
      Map<String, ?> objCast = (Map<String, ?>) obj;
      return new SoyMapData(objCast);
    } else if (obj instanceof Iterable<?>) {
      return new SoyListData((Iterable<?>) obj);
    } else if (obj instanceof Double) {
      return FloatData.forValue((Double) obj);
    } else if (obj instanceof Float) {
      // Automatically convert float to double.
      return FloatData.forValue((Float) obj);
    } else if (obj instanceof Future<?>) {
      // Note: In the old SoyData, we don't support late-resolution of Futures. We immediately
      // resolve the Future object here. For late-resolution, use SoyValueConverter.convert().
      try {
        return createFromExistingData(((Future<?>) obj).get());
      } catch (InterruptedException e) {
        throw new SoyDataException(
            "Encountered InterruptedException when resolving Future object.", e);
      } catch (ExecutionException e) {
        throw new SoyDataException(
            "Encountered ExecutionException when resolving Future object.", e);
      }
    } else {
      throw new SoyDataException(
          "Attempting to convert unrecognized object to Soy data (object type "
              + obj.getClass().getName()
              + ").");
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Inventory\Application\Export\Transaction;

use Application\Domain\Util\JsonErrors;
use Inventory\Application\Export\Transaction\Contracts\AbstractSaveAs;
use Inventory\Application\Export\Transaction\Contracts\RowsSaveAsInterface;
use Inventory\Application\Export\Transaction\Formatter\AbstractRowFormatter;

/**
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
class TrxRowsSaveAsArray extends AbstractSaveAs implements RowsSaveAsInterface
{

    /**
     *
     * {@inheritdoc}
     * @see \Procure\Application\Service\Output\Contract\RowsSaveAsInterface::saveAs()
     */
    public function saveAs($rows, AbstractRowFormatter $formatter)
    {
        try {

            $n = 0;
            foreach ($rows as $row) {

                $formattedRow = $formatter->format($row);

                json_encode($formattedRow);
                if (JsonErrors::getErrorMessage(json_last_error()) != null) {
                    $this->logInfo(\sprintf("%s=> %s", $row->getId() . $row->getItemName1(), JsonErrors::getErrorMessage(json_last_error())));
                }

                $output[] = $formattedRow;
                $n ++;
            }
            $this->logInfo(\sprintf("TrxRowsSaveAsArray: %s formatted!", $n));
            return $output;
        } catch (\Exception $e) {
            $this->logException($e);
        }
    }
}


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

#include "BitmapInfo.h"
#include "CachedImage.h"
#include "GraphicsContextCG.h"
#include "HWndDC.h"
#include "Image.h"

#include <CoreGraphics/CoreGraphics.h>
#include <wtf/RetainPtr.h>

#include <windows.h>

namespace WebCore {

void deallocContext(CGContextRef target)
{
    CGContextRelease(target);
}

HBITMAP allocImage(HDC dc, IntSize size, CGContextRef *targetRef)
{
    BitmapInfo bmpInfo = BitmapInfo::create(size);

    LPVOID bits;
    HBITMAP hbmp = CreateDIBSection(dc, &bmpInfo, DIB_RGB_COLORS, &bits, 0, 0);

    if (!targetRef)
        return hbmp;

    CGContextRef bitmapContext = CGBitmapContextCreate(bits, bmpInfo.bmiHeader.biWidth, bmpInfo.bmiHeader.biHeight, 8,
                                                       bmpInfo.bmiHeader.biWidth * 4, deviceRGBColorSpaceRef(),
                                                       kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst);
    if (!bitmapContext) {
        DeleteObject(hbmp);
        return 0;
    }

    *targetRef = bitmapContext;
    return hbmp;
}

static CGContextRef createCgContextFromBitmap(HBITMAP bitmap)
{
    BITMAP info;
    GetObject(bitmap, sizeof(info), &info);
    ASSERT(info.bmBitsPixel == 32);

    CGContextRef bitmapContext = CGBitmapContextCreate(info.bmBits, info.bmWidth, info.bmHeight, 8,
                                                       info.bmWidthBytes, deviceRGBColorSpaceRef(), kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst);
    return bitmapContext;
}

DragImageRef scaleDragImage(DragImageRef image, FloatSize scale)
{
    // FIXME: due to the way drag images are done on windows we need
    // to preprocess the alpha channel <rdar://problem/5015946>

    if (!image)
        return 0;
    CGContextRef targetContext;
    CGContextRef srcContext;
    CGImageRef srcImage;
    IntSize srcSize = dragImageSize(image);
    IntSize dstSize(static_cast<int>(srcSize.width() * scale.width()), static_cast<int>(srcSize.height() * scale.height()));
    HBITMAP hbmp = 0;
    HWndDC dc(0);
    HDC dstDC = CreateCompatibleDC(dc);
    if (!dstDC)
        goto exit;

    hbmp = allocImage(dstDC, dstSize, &targetContext);
    if (!hbmp)
        goto exit;

    srcContext = createCgContextFromBitmap(image);
    srcImage = CGBitmapContextCreateImage(srcContext);
    CGRect rect;
    rect.origin.x = 0;
    rect.origin.y = 0;
    rect.size = dstSize;
    CGContextDrawImage(targetContext, rect, srcImage);
    CGImageRelease(srcImage);
    CGContextRelease(srcContext);
    CGContextRelease(targetContext);
    ::DeleteObject(image);
    image = 0;

exit:
    if (!hbmp)
        hbmp = image;
    if (dstDC)
        DeleteDC(dstDC);
    return hbmp;
}

DragImageRef createDragImageFromImage(Image* img, RespectImageOrientationEnum)
{
    HBITMAP hbmp = 0;
    HWndDC dc(0);
    HDC workingDC = CreateCompatibleDC(dc);
    CGContextRef drawContext = 0;
    if (!workingDC)
        goto exit;

    hbmp = allocImage(workingDC, img->size(), &drawContext);

    if (!hbmp)
        goto exit;

    if (!drawContext) {
        ::DeleteObject(hbmp);
        hbmp = 0;
    }

    CGImageRef srcImage = img->getCGImageRef();
    CGRect rect;
    rect.size = img->size();
    rect.origin.x = 0;
    rect.origin.y = -rect.size.height;
    static const CGFloat white [] = {1.0, 1.0, 1.0, 1.0};
    CGContextScaleCTM(drawContext, 1, -1);
    CGContextSetFillColor(drawContext, white);
    CGContextFillRect(drawContext, rect);
    CGContextSetBlendMode(drawContext, kCGBlendModeNormal);
    CGContextDrawImage(drawContext, rect, srcImage);
    CGContextRelease(drawContext);

exit:
    if (workingDC)
        DeleteDC(workingDC);
    return hbmp;
}

}


text:
package com.akjava.gwt.lib.client;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * @deprecated
 * @author aki
 *
 */
public class ValueUtils {
	private ValueUtils(){}

	/**
	 * use Values Utils.toDouble
	 * @param bool
	 * @param defaultValue
	 * @return
	 */
public static boolean getBoolean(String bool,boolean defaultValue){
	if(bool==null || bool.equals("")){
		return defaultValue;
	}
	boolean ret=defaultValue;
	if( bool.toLowerCase().equals("true")){
		ret=true;
	}else if( bool.toLowerCase().equals("false")){
		ret=false;
	}
	return ret;
}
/**
 * @deprecated
 * use CSVUtils
 */
public static String toNLineSeparator(String text){
	String ret=text.replace("\r\n", "\n");
	ret= ret.replace("\r", "\n");
	return ret;
}
/**
 * @deprecated
 * use CSVUtils
 */
public static String[] splitLines(String text){
    text=toNLineSeparator(text);
    String[] lines=text.split("\n");
    return lines;
}
public static String[][] csvToArray(String line,char separator){
	line=ValueUtils.toNLineSeparator(line);
	String[] lines=line.split("\n");
	String ret[][]=new String[lines.length][0];
	for (int i = 0; i < lines.length; i++) {
		String csv[]=lines[i].split(""+separator);
		ret[i]=new String[csv.length];
		for (int j = 0; j < csv.length; j++) {
			ret[i][j]=csv[j];
		}
	}
	return ret;
}

public static List<String[]> csvToArrayList(String line,char separator){
	line=ValueUtils.toNLineSeparator(line);
	String[] lines=line.split("\n");

	List<String[]> ret=new ArrayList<String[]>();
	for (int i = 0; i < lines.length; i++) {
		String csv[]=lines[i].split(""+separator);
		ret.add(csv);
	}
	return ret;
}

public static String joinOn(Iterable<String> values,String separator){
	StringBuilder builder=new StringBuilder();

	Iterator<String> itor=values.iterator();
	while(itor.hasNext()){
		builder.append(itor.next());
		if(itor.hasNext()){
			builder.append(separator);
		}
	}

	return builder.toString();
}

public static String[][] csvToArray(String line){
	return csvToArray(line,',');
}

public static String removeEmptyLine(String line){
	line=ValueUtils.toNLineSeparator(line);
	String[] lines=line.split("\n");
	String ret="";
	for (int i = 0; i < lines.length; i++) {
		if(!lines[i].equals("")){
			ret+=lines[i];
			if(i!=lines.length-1){
				ret+="\n";
			}else{
				ret+="\n";
			}
		}
	}
	return ret;
}

/**
 * use GWTHTMLUtils
 * @deprecated
 *
 * @param id
 * @param defaultValue
 * @return
 */
public static String getFormValueById(String id,String defaultValue){
	String ret=defaultValue;
	RootPanel panel=RootPanel.get(id);
	if(panel!=null){
		String data=panel.getElement().getAttribute("value");
		if(data!=null && !data.equals("") && !data.equals("None")){
			ret=data;
		}
	}
	   return ret;
}

public static String tabbed(Iterable<String> iter){
	StringBuilder builder=new StringBuilder();
	Iterator<String> itor=iter.iterator();
	while(itor.hasNext()){
		builder.append(itor.next());
		if(itor.hasNext()){
			builder.append("\t");
		}
	}
	return builder.toString();
}

public static String[] untabbed(String line){
	return line.split("\t");
}

public static Map<String,String> loadCsvAsMap(String text){
	return loadCsvAsMap(text,",");
}
public static Map<String,String> loadCsvAsMap(String text,String separator){
	Map<String,String> map=new LinkedHashMap<String,String>();
	String[] lines=splitLines(text);
for(String line:lines){
	if(line.isEmpty()){
		continue;
	}
	int sp=line.indexOf(separator);
	if(sp!=-1){
		map.put(line.substring(0,sp),line.substring(sp+separator.length()));
	}else{
		map.put(line, "");
	}
}
	return map;
}

public static native String reverse(String value) /*-{
return value.split('').reverse().join('');
}-*/;

/**
 * Use ArrayUtils
 * for gwt convert
 * @param vs
 * @return
 */
public static String[] iterableToArray(Iterable<String> vs){
	Collection<String> collection =  Lists.newArrayList(vs);
    String[] array = new String[collection.size()];
    return collection.toArray(array);
}
}


text:
Astro.utils = {};

Astro.utils.warn = function(warning) {
  if (console && console.warn && Astro.config.verbose) {
    console.warn(warning);
  }
};

Astro.utils.string = {};

Astro.utils.string.ucfirst = function(str) {
  return str.charAt(0).toUpperCase() + str.substr(1);
};

Astro.utils.object = {};

Astro.utils.object.deepMerge = function(target, source, key) {
  var self = this;

  var mergeKey = function(key) {
    var targetValue = target[key];
    var sourceValue = source[key];

    if (_.has(target, key)) {
      result[key] = self.deepMerge(targetValue, sourceValue, key);
    } else {
      if (
        _.isObject(sourceValue) &&
        !_.isArray(sourceValue) &&
        !_.isFunction(sourceValue)
      ) {
        result[key] = self.deepMerge({}, sourceValue, key);
      } else {
        result[key] = sourceValue;
      }
    }
  };

  if (_.isArray(source) && _.isArray(target)) {
    return [].concat(target, source);
  } else if (_.isObject(target) && _.isObject(source)) {
    var result = _.extend({}, target);
    _.each(_.keys(source), mergeKey);
    return result;
  } else {
    return source;
  }
};

Astro.utils.class = {};

Astro.utils.class.transform = function(transformFunction) {
  return LocalCollection.wrapTransform(transformFunction);
};

Astro.utils.class.transformToClass = function(className) {
  return LocalCollection.wrapTransform(function(attrs) {
    var Class = Astro.getClass(className);

    if (Class) {
      var typeField = Class.getTypeField();
      if (typeField) {
        var TypeClass = Astro.getClass(attrs[typeField]);
        if (TypeClass) {
          Class = TypeClass;
        }
      }

      var doc = new Class(attrs);
      doc._isNew = false;
      return doc;
    }

    return attrs;
  });
};

Astro.utils.class.inherits = function(Child, Parent) {
  Child.prototype = Object.create(Parent.prototype);
  Child.prototype.constructor = Child;
};


text:
from models import IPWhitelist
from flask import current_app

def get_reports(c):
    ip_whitelist = [x.cidr_ip for x in IPWhitelist.query.all()]
    excluded_groups = current_app.config['CONFIG']['sgaudit']['excluded_groups']
    excluded_ips = current_app.config['CONFIG']['sgaudit']['excluded_ips']
    groups = [x for x in c.get_all_security_groups() if not x.name in excluded_groups]
    empty_groups = list()
    report = dict()
    for group in groups:
        report[group.name] = list()
        if not group.rules:
            del report[group.name]
            empty_groups.append(group.name)
            continue
        for rule in group.rules:
            for grant in rule.grants:
                if grant.cidr_ip is None or grant.cidr_ip is False:
                    continue
                else:
                    if not grant.cidr_ip in ip_whitelist and not grant.cidr_ip in excluded_ips:
                        if rule.from_port is None:
                            rule.from_port = 'ALL'
                        if rule.to_port is None:
                            rule.to_port = 'ALL'
                        report[group.name].append(
                            [grant.cidr_ip, rule.from_port, rule.to_port])
        if not report[group.name]:
            del report[group.name]
    return report, empty_groups

def add_description(sg_obj):
    """This feels wrong but I need to add metadata from DB whitelist to
    the boto object so I can access it from the template in a simple way.
    Sorry"""
    excluded_ips = current_app.config['CONFIG']['sgaudit']['excluded_ips']
    for i in sg_obj:
        for rule in i.rules:
            for grant in rule.grants:
                if grant.cidr_ip:
                    record = IPWhitelist.query.filter_by(cidr_ip=grant.cidr_ip).first()
                    if record:
                        grant.description = record.description
                    else:
                        if grant.cidr_ip in excluded_ips:
                            grant.description = "Explicitly excluded from whitelist in config"
                        else:
                            grant.description = "Not in whitelist. Unknown"
                else:
                    continue
    return sg_obj


text:
<?xml version="1.0" encoding="utf-8"?>
        <!DOCTYPE hibernate-mapping PUBLIC
                "-//Hibernate/Hibernate Mapping DTD//EN"
                "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.bugtrack.entity.group" table="groups">
    <id column="groupid" name="id" type="java.lang.Integer">
        <generator class="increment"/>
    </id>
    <property column="groupname" name="name" type="java.lang.String"/>
    <property column="description" name="description" type="java.lang.String"/>
</class>
</hibernate-mapping>