text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.move;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nullable;

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author ven
 */
public final class MoveInstanceMembersUtil {
  private static final Logger LOG = Logger.getInstance(MoveInstanceMembersUtil.class);

  /**
   * @param member  nonstatic class member to search for class references in
   * @return Set<PsiMember> in result map may be null in case no member is needed, but class itself is.
   */
  public static Map<PsiClass, Set<PsiMember>> getThisClassesToMembers(final PsiMember member) {
    Map<PsiClass, Set<PsiMember>> map = new LinkedHashMap<>();
    getThisClassesToMembers (member, map, member);
    return map;
  }

  private static void getThisClassesToMembers(final PsiElement scope, final Map<PsiClass, Set<PsiMember>> map, final PsiMember refMember) {
    if (scope instanceof PsiExpression) {
      final PsiExpression expression = (PsiExpression)scope;
      if (!(scope instanceof PsiReferenceExpression) || !((PsiReferenceExpression)scope).isReferenceTo(refMember)) {
        final Pair<PsiMember, PsiClass> pair = getMemberAndClassReferencedByThis(expression);
        if (pair != null) {
          PsiClass refClass = pair.getSecond();
          PsiMember member = pair.getFirst();
          if (refClass != null) {
            boolean inherited = false;
            PsiClass parentClass = PsiTreeUtil.getParentOfType(scope, PsiClass.class, true);
            while (parentClass != null && PsiTreeUtil.isAncestor(refMember, parentClass, false)) {
              if (parentClass == refClass || parentClass.isInheritor(refClass, true)) {
                inherited = true;
                break;
              }
              parentClass = PsiTreeUtil.getParentOfType(parentClass, PsiClass.class, true);
            }
            if (!inherited && !PsiTreeUtil.isAncestor(refMember, member, false)) {
              addReferencedMember(map, refClass, member);
            }
          }
        }

        if (expression instanceof PsiThisExpression) {
          final PsiJavaCodeReferenceElement thisQualifier = ((PsiThisExpression)expression).getQualifier();
          PsiClass thisClass = thisQualifier == null ? PsiTreeUtil.getParentOfType(expression, PsiClass.class, true) : ((PsiClass)thisQualifier.resolve());
          if (thisClass != null && !PsiTreeUtil.isAncestor( refMember,thisClass, false)) {
            addReferencedMember(map, thisClass, null);
          }
        }
      }
    }

    final PsiElement[] children = scope.getChildren();
    for (PsiElement child : children) {
      getThisClassesToMembers(child, map, refMember);
    }
  }

  private static void addReferencedMember(final Map<PsiClass, Set<PsiMember>> map, final PsiClass classReferenced, final PsiMember member) {
    Set<PsiMember> members = map.get(classReferenced);
    if (members == null) {
      members = new HashSet<>();
      map.put(classReferenced, members);
    }
    members.add(member);
  }

  @Nullable
  private static Pair<PsiMember, PsiClass> getMemberAndClassReferencedByThis(final PsiExpression expression) {
    if (expression instanceof PsiReferenceExpression) {
      final PsiExpression qualifier = ((PsiReferenceExpression)expression).getQualifierExpression();
      if (qualifier == null || qualifier instanceof PsiThisExpression) {
        final PsiElement resolved = ((PsiReferenceExpression)expression).resolve();
        if (resolved instanceof PsiMember && !((PsiMember)resolved).hasModifierProperty(PsiModifier.STATIC)) {
          PsiClass referencedClass = getReferencedClass((PsiMember)resolved, qualifier, expression);
          return Pair.create((PsiMember)resolved, referencedClass);
        }
      }
    } else if (expression instanceof PsiNewExpression) {
      final PsiNewExpression newExpression = (PsiNewExpression)expression;
      final PsiExpression qualifier = newExpression.getQualifier();
      if (qualifier == null || qualifier instanceof PsiThisExpression) {
        PsiJavaCodeReferenceElement classReference = newExpression.getClassOrAnonymousClassReference();
        if (classReference != null) {
          final PsiClass resolved = (PsiClass)classReference.resolve();
          if (resolved != null && !resolved.hasModifierProperty(PsiModifier.STATIC)) {
            PsiClass referencedClass = getReferencedClass(resolved, qualifier, expression);
            return new Pair<>(resolved, referencedClass);
          }
        }
      }
    }

    return null;
  }

  @Nullable
  private static PsiClass getReferencedClass(final PsiMember member, final PsiExpression exprQualifier, final PsiExpression expression) {
    if (exprQualifier != null) {
      final PsiType type = exprQualifier.getType();
      if (type instanceof PsiClassType) {
        return ((PsiClassType)type).resolve();
      }
      return null;
    } else {
      PsiClass referencedClass = member.getContainingClass();
      if (referencedClass == null) return null;
      final PsiClass parentClass = PsiTreeUtil.getParentOfType(expression, PsiClass.class);
      assert parentClass != null;
      if (InheritanceUtil.isInheritorOrSelf(parentClass, referencedClass, false)) {
        referencedClass = parentClass;
      }
      return referencedClass;
    }
  }

  @Nullable
  public static PsiClass getClassReferencedByThis(final PsiExpression expression) {
    PsiClass enclosingClass = PsiTreeUtil.getParentOfType(expression, PsiClass.class);
    if (enclosingClass == null) return null;
    final Pair<PsiMember, PsiClass> pair = getMemberAndClassReferencedByThis(expression);
    if (pair != null) return pair.getSecond();

    if (expression instanceof PsiThisExpression) {
      final PsiJavaCodeReferenceElement thisQualifier = ((PsiThisExpression)expression).getQualifier();
      if (thisQualifier == null) {
        return enclosingClass;
      }
      else {
        return (PsiClass)thisQualifier.resolve();
      }
    }
    return null;
  }

  public static void moveInitializerToConstructor(PsiElementFactory factory, PsiMethod constructor, PsiField field) {
    final PsiExpression initializer = field.getInitializer();
    PsiExpression initializerCopy = (PsiExpression)initializer.copy();
    final PsiCodeBlock body = constructor.getBody();
    if (body != null) {
      try {
        String fieldName = field.getName();
        final PsiReferenceExpression refExpr = (PsiReferenceExpression)factory.createExpressionFromText(fieldName, body);
        if (refExpr.resolve() != null) fieldName = "this." + fieldName;
        PsiExpressionStatement statement = (PsiExpressionStatement)factory.createStatementFromText(fieldName + "= y;", null);
        if (initializerCopy instanceof PsiArrayInitializerExpression) {
          PsiType type = initializer.getType();
          PsiNewExpression newExpression =
            (PsiNewExpression)factory.createExpressionFromText("new " + type.getCanonicalText() + "{}", body);
          newExpression.getArrayInitializer().replace(initializerCopy);
          initializerCopy = newExpression;
        }
        ((PsiAssignmentExpression)statement.getExpression()).getRExpression().replace(initializerCopy);
        statement = (PsiExpressionStatement)CodeStyleManager.getInstance(field.getManager().getProject()).reformat(statement);
        body.add(statement);
        initializer.delete();
      }
      catch (IncorrectOperationException e) {
        LOG.error(e);
      }
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.traccar;

import io.netty.buffer.ByteBuf;
import org.traccar.database.MediaManager;

import java.util.HashMap;
import java.util.Map;

public class BaseTest {

    public static class MockMediaManager extends MediaManager {
        Map<String, ByteBuf> files = new HashMap<>();

        MockMediaManager() {
            super("");
        }

        @Override
        public String writeFile(String uniqueId, ByteBuf buf, String extension) {
            String fileName = uniqueId + "/mock." + extension;
            files.put(fileName, buf);
            return fileName;
        }

        public ByteBuf readFile(String fileName) {
            return files.get(fileName);
        }
    }

    static {
        Context.init(new TestIdentityManager(), new MockMediaManager());
    }

}


text:
package org.drools.compiler;

import org.drools.builder.ResourceConfiguration;
import org.drools.builder.ResourceType;
import org.drools.io.Resource;

public interface ResourceTypeBuilder {

    void setPackageBuilder(PackageBuilder packageBuilder);

    void addKnowledgeResource(Resource resource, ResourceType type, ResourceConfiguration configuration) throws Exception;

}


text:
package i_introduction._9_Extension_Functions;

import util.JavaCode;

public class JavaCode8 extends JavaCode {
    public void useExtension() {
        char c = ExtensionFunctionsKt.lastChar("abc");
    }
}


text:
Object.defineProperty(exports, "__esModule", { value: true });
var transition_1 = require("./transition");
var platform_1 = require("../../platform");
var screenWidth = platform_1.screen.mainScreen.widthDIPs;
var screenHeight = platform_1.screen.mainScreen.heightDIPs;
var leftEdge = CGAffineTransformMakeTranslation(-screenWidth, 0);
var rightEdge = CGAffineTransformMakeTranslation(screenWidth, 0);
var topEdge = CGAffineTransformMakeTranslation(0, -screenHeight);
var bottomEdge = CGAffineTransformMakeTranslation(0, screenHeight);
var SlideTransition = (function (_super) {
    __extends(SlideTransition, _super);
    function SlideTransition(direction, duration, curve) {
        var _this = _super.call(this, duration, curve) || this;
        _this._direction = direction;
        return _this;
    }
    SlideTransition.prototype.animateIOSTransition = function (containerView, fromView, toView, operation, completion) {
        var originalToViewTransform = toView.transform;
        var originalFromViewTransform = fromView.transform;
        var fromViewEndTransform;
        var toViewBeginTransform;
        var push = (operation === 1);
        switch (this._direction) {
            case "left":
                toViewBeginTransform = push ? rightEdge : leftEdge;
                fromViewEndTransform = push ? leftEdge : rightEdge;
                break;
            case "right":
                toViewBeginTransform = push ? leftEdge : rightEdge;
                fromViewEndTransform = push ? rightEdge : leftEdge;
                break;
            case "top":
                toViewBeginTransform = push ? bottomEdge : topEdge;
                fromViewEndTransform = push ? topEdge : bottomEdge;
                break;
            case "bottom":
                toViewBeginTransform = push ? topEdge : bottomEdge;
                fromViewEndTransform = push ? bottomEdge : topEdge;
                break;
        }
        toView.transform = toViewBeginTransform;
        fromView.transform = CGAffineTransformIdentity;
        switch (operation) {
            case 1:
                containerView.insertSubviewAboveSubview(toView, fromView);
                break;
            case 2:
                containerView.insertSubviewBelowSubview(toView, fromView);
                break;
        }
        var duration = this.getDuration();
        var curve = this.getCurve();
        UIView.animateWithDurationAnimationsCompletion(duration, function () {
            UIView.setAnimationCurve(curve);
            toView.transform = CGAffineTransformIdentity;
            fromView.transform = fromViewEndTransform;
        }, function (finished) {
            toView.transform = originalToViewTransform;
            fromView.transform = originalFromViewTransform;
            completion(finished);
        });
    };
    return SlideTransition;
}(transition_1.Transition));
exports.SlideTransition = SlideTransition;
//# sourceMappingURL=slide-transition.ios.js.map


text:
package com.myjavaworld.jftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SealedObject;
import javax.crypto.spec.SecretKeySpec;

/**
 * A Class used to serialize/deserialize favourite FTP sites. This is the
 * central point that contains all the IO logic required to
 * retrieve/store/add/edit/delete favouritre FTP sites.
 *
 * @author Sai Pullabhotla, psai [at] jMethods [dot] com
 * @version 2.0
 */
public class FavoritesManager {

	/**
	 * Serialized file that stores the favourite FTP sites.
	 */
	private static final File FAV_FILE = new File(JFTP.DATA_HOME,
			"favorites.ser");

	/**
	 * Returns the list of favourite FTP sites. The list is generated by reading
	 * the serialized file, FAV_FILE.
	 *
	 * @return List of favourite FTP sites.
	 * @exception IOException
	 *                if an IO error occurs while reading the file
	 * @exception ClassNotFoundException
	 *                We should never get this exception. If we get this, it
	 *                means that the software is not installed correctly.
	 */
	public static List getFavorites() throws IOException,
			ClassNotFoundException, IllegalBlockSizeException,
			BadPaddingException {
		List favorites = new ArrayList();
		FileInputStream fin = null;
		ObjectInputStream in = null;
		try {
			checkFavFile();
			fin = new FileInputStream(FAV_FILE);
			if (fin.available() > 0) {
				in = new ObjectInputStream(fin);
				Object obj = in.readObject();
				if (obj instanceof List) {
					favorites = (List) obj;
					saveFavorites(favorites);
				} else {
					SealedObject so = (SealedObject) obj;
					favorites = (List) so
							.getObject(getCipher(Cipher.DECRYPT_MODE));
				}
			}
			return favorites;
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException exp) {
			}
			try {
				if (fin != null) {
					fin.close();
				}
			} catch (IOException exp) {
			}
			in = null;
			fin = null;
		}
	}

	/**
	 * Saves the given list of favourite FTP sites to the favorite file.
	 *
	 * @param favorites
	 *            List of favorites to be searialized
	 * @exception IOException
	 *                if an IO error occurs
	 */
	public static void saveFavorites(List favorites) throws IOException,
			IllegalBlockSizeException {
		if (favorites == null) {
			favorites = new ArrayList();
		}
		checkDataHome();
		ObjectOutputStream out = null;
		try {
			out = new ObjectOutputStream(new FileOutputStream(FAV_FILE));
			Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
			if (cipher == null) {
				// We do not have AES provider. so just save the favorites
				// unencrypted.
				out.writeObject(favorites);
			} else {
				SealedObject so = new SealedObject((Serializable) favorites,
						cipher);
				out.writeObject(so);
			}
		} finally {
			if (out != null) {
				out.close();
			}
			out = null;
		}
	}

	/**
	 * Adds the given favourite to the list of previously stored favorites and
	 * saves them back to the favorites file.
	 *
	 * @param host
	 *            Favorite FTP site
	 * @exception IOException
	 *                if an IO error occurs
	 * @exception ClassNotFoundException
	 */
	public static void addFavorite(RemoteHost host) throws IOException,
			ClassNotFoundException, IllegalBlockSizeException,
			BadPaddingException {
		List favorites = getFavorites();
		favorites.add(host);
		saveFavorites(favorites);
	}

	private static void checkDataHome() {
		if (!JFTP.DATA_HOME.exists() || !JFTP.DATA_HOME.isDirectory()) {
			JFTP.DATA_HOME.mkdirs();
		}
	}

	private static void checkFavFile() throws IOException {
		checkDataHome();
		if (!FAV_FILE.exists() || !FAV_FILE.isFile()) {
			FAV_FILE.createNewFile();
		}
	}

	private static Cipher getCipher(int mode) {
		final byte[] encodedKey = { 28, -9, -23, 35, -93, -47, -28, 55, -83,
				-82, 101, -79, 36, 59, 77, -121 };
		Cipher cipher = null;
		try {
			cipher = Cipher.getInstance("AES");
			SecretKeySpec spec = new SecretKeySpec(encodedKey, "AES");
			cipher.init(mode, spec);
			return cipher;
		} catch (InvalidKeyException exp) {
			exp.printStackTrace();
		} catch (NoSuchAlgorithmException exp) {
			exp.printStackTrace();
		} catch (NoSuchPaddingException exp) {
			exp.printStackTrace();
		}
		return null;
	}
}


text:
package todomvc.example

import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport

import com.greencatsoft.angularjs.{ Angular, injectable }

@JSExport
object TodoApp extends JSApp {

  override def main() {
    val module = Angular.module("todomvc")

    module
      .controller[TodoCtrl]
      .directive[TodoItemDirective]
      .directive[EscapeDirective]
      .directive[FocusDirective]
      .filter[StatusFilter]
      .factory[TaskServiceFactory]
  }
}


text:
set -eo pipefail -o nounset

## Get .genome file
genome=https://raw.githubusercontent.com/gogetdata/ggd-recipes/master/genomes/Homo_sapiens/hg38/hg38.genome

## Get the chromomsome mapping file
chr_mapping=$(ggd get-files hg38-chrom-mapping-ensembl2ucsc-ncbi-v1 --pattern "*.txt")

## Process GTF file
wget --quiet ftp://ftp.ensembl.org/pub/release-100/gtf/homo_sapiens/Homo_sapiens.GRCh38.100.gtf.gz

cat <(zgrep "^#" Homo_sapiens.GRCh38.100.gtf.gz) <(echo -e "#chrom\tsource\tfeature\tstart\tend\tscore\tstrand\tframe\tattribute") <(zgrep -E "five_prime_utr|three_prime_utr" Homo_sapiens.GRCh38.100.gtf.gz) \
    | gsort --chromosomemappings $chr_mapping /dev/stdin $genome \
    | bgzip -c > hg38-utr-only-features-ensembl-v1.gtf.gz

tabix hg38-utr-only-features-ensembl-v1.gtf.gz

rm Homo_sapiens.GRCh38.100.gtf.gz


text:
<?xml version="1.0" encoding="UTF-8"?>
<ApexComponent xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>40.0</apiVersion>
    <label>UTIL_FormField</label>
</ApexComponent>


text:
package edu.jhu.pacaya.gm.train;

import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.Test;

import edu.jhu.pacaya.autodiff.AbstractModuleTest;
import edu.jhu.pacaya.autodiff.AbstractModuleTest.OneToOneFactory;
import edu.jhu.pacaya.autodiff.Identity;
import edu.jhu.pacaya.autodiff.Module;
import edu.jhu.pacaya.autodiff.Tensor;
import edu.jhu.pacaya.gm.inf.Beliefs;
import edu.jhu.pacaya.gm.model.Var;
import edu.jhu.pacaya.gm.model.Var.VarType;
import edu.jhu.pacaya.gm.model.VarConfig;
import edu.jhu.pacaya.gm.model.VarSet;
import edu.jhu.pacaya.gm.model.VarTensor;
import edu.jhu.pacaya.util.collections.QLists;
import edu.jhu.pacaya.util.semiring.Algebra;
import edu.jhu.pacaya.util.semiring.RealAlgebra;

public class L2DistanceTest {

    private VarConfig goldConfig;
    private Identity<Beliefs> id1;
    private Algebra s = RealAlgebra.getInstance();

    @Before
    public void setUp() {
        Var t0 = new Var(VarType.PREDICTED, 2, "t0", QLists.getList("N", "V"));
        Var t1 = new Var(VarType.PREDICTED, 2, "t1", QLists.getList("N", "V"));
        t0.setId(0);
        t1.setId(1);

        goldConfig = new VarConfig();
        goldConfig.put(t0, 0);
        goldConfig.put(t1, 1);

        Beliefs b = new Beliefs(s);
        b.varBeliefs = new VarTensor[2];
        b.facBeliefs = new VarTensor[0];
        b.varBeliefs[0] = new VarTensor(s, new VarSet(t0), 0.0);
        b.varBeliefs[1] = new VarTensor(s, new VarSet(t1), 0.0);

        b.varBeliefs[0].setValue(0, 0.3); // Gold value
        b.varBeliefs[0].setValue(1, 0.7);
        b.varBeliefs[1].setValue(0, 0.4);
        b.varBeliefs[1].setValue(1, 0.6); // Gold value

        id1 = new Identity<Beliefs>(b);
    }

    @Test
    public void testSimple() {
        Algebra s = RealAlgebra.getInstance();
        L2Distance mse = new L2Distance(id1, goldConfig);

        Tensor out = mse.forward();
        assertEquals(sq(1-0.3)+sq(0-.7)+sq(0-.4)+sq(1-.6), out.getValue(0), 1e-13);

        mse.getOutputAdj().setValue(0, 2.2);
        mse.backward();
        Beliefs inAdj = id1.getOutputAdj();
        assertEquals(2.2 * 2 * (.3-1), inAdj.varBeliefs[0].getValue(0), 1e-13);
        assertEquals(2.2 * 2 * (.7-0), inAdj.varBeliefs[0].getValue(1), 1e-13);
        assertEquals(2.2 * 2 * (.4-0), inAdj.varBeliefs[1].getValue(0), 1e-13);
        assertEquals(2.2 * 2 * (.6-1), inAdj.varBeliefs[1].getValue(1), 1e-13);
    }

    private double sq(double d) {
        return d*d;
    }

    @Test
    public void testGradByFiniteDiffsAllSemirings() {
        OneToOneFactory<Beliefs,Tensor> fact = new OneToOneFactory<Beliefs,Tensor>() {
            public Module<Tensor> getModule(Module<Beliefs> m1) {
                return new L2Distance(m1, goldConfig);
            }
        };
        AbstractModuleTest.evalOneToOneByFiniteDiffsAbs(fact, id1);
    }

}


text:
package org.araneaframework.uilib.list.structure.filter.field;

import java.util.Map;
import org.apache.commons.lang.ObjectUtils;
import org.araneaframework.backend.list.memorybased.Expression;
import org.araneaframework.uilib.form.Control;
import org.araneaframework.uilib.form.FormElement;
import org.araneaframework.uilib.list.structure.filter.FilterContext;
import org.araneaframework.uilib.list.util.ExpressionUtil;
import org.araneaframework.uilib.list.util.FilterFormUtil;

public abstract class NullFilter extends BaseFieldFilter {

  public static NullFilter getIdNullInstance(FilterContext ctx, String fieldId, String valueId, Object conditionValue) {
    IsNull filter = new IsNull();
    filter.setFieldId(fieldId);
    filter.setValueId(valueId);
    filter.setConditionValue(conditionValue);
    return filter;
  }

  public static NullFilter getIsNullConstantInstance(FilterContext ctx, String fieldId) {
    IsNullConstant filter = new IsNullConstant();
    filter.setFieldId(fieldId);
    return filter;
  }

  public static NullFilter getNotNullInstance(FilterContext ctx, String fieldId, String valueId, Object conditionValue) {
    NotNull filter = new NotNull();
    filter.setFieldId(fieldId);
    filter.setValueId(valueId);
    filter.setConditionValue(conditionValue);
    return filter;
  }

  public static NullFilter getNotNullConstantInstance(FilterContext ctx, String fieldId) {
    NotNullConstant filter = new NotNullConstant();
    filter.setFieldId(fieldId);
    return filter;
  }

  public static void addToForm(FilterContext ctx, String id, FormElement<?, ?> element) {
    ctx.getForm().addElement(id, element);
  }

  public static void addToForm(FilterContext ctx, String id, Control<?> control) {
    addToForm(ctx, id, FilterFormUtil.createElement(ctx, id, control));
  }

  public static void addToForm(FilterContext ctx, String id) {
    addToForm(ctx, id, FilterFormUtil.createElement(ctx, id));
  }

  static abstract class ConditionValue extends NullFilter {

    private Object conditionValue;

    public Object getConditionValue() {
      return this.conditionValue;
    }

    public void setConditionValue(Object conditionValue) {
      this.conditionValue = conditionValue;
    }
  }

  static class IsNull extends ConditionValue {

    public Expression buildExpression(Map<String, Object> data) {
      if (equals(data.get(getValueId()), getConditionValue())) {
        return ExpressionUtil.isNull(buildVariableExpression());
      }
      return null;
    }
  }

  static class IsNullConstant extends NullFilter {

    public Expression buildExpression(Map<String, Object> data) {
      return ExpressionUtil.isNull(buildVariableExpression());
    }
  }

  static class NotNull extends ConditionValue {

    public Expression buildExpression(Map<String, Object> data) {
      if (equals(data.get(getValueId()), getConditionValue())) {
        return ExpressionUtil.notNull(buildVariableExpression());
      }
      return null;
    }
  }

  static class NotNullConstant extends NullFilter {

    public Expression buildExpression(Map<String, Object> data) {
      return ExpressionUtil.notNull(buildVariableExpression());
    }
  }

  static boolean equals(Object o1, Object o2) {
    return ObjectUtils.equals(o1, o2);
  }

}


text:
<?php

namespace Openl10n\Bundle\InfraBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class LanguageType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('locale', 'openl10n_locale_choice')
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'openl10n_language';
    }
}


text:
<!DOCTYPE html>
<html>
<script>
if (window.testRunner)
    testRunner.dumpAsText();

var docElement = document.documentElement;
function crash() {
    svgAnimAttributeElement1 = document.createElementNS("http://www.w3.org/2000/svg", "animattributeattrs");
    mathElement1 = document.createElementNS("http://www.w3.org/1998/Math/MathML", "math");
    mathElement1.setAttribute("class", "c0");
    svgAnimateElement1 = document.createElementNS("http://www.w3.org/2000/svg", "animate");
    svgTestcaseElement1 = document.createElementNS("http://www.w3.org/2000/svg", "svgtestcase");
    svgEllipseElement1 = document.createElementNS("http://www.w3.org/2000/svg", "ellipse");
    mathElement2 = document.createElementNS("http://www.w3.org/1998/Math/MathML", "math");
    docElement.appendChild(mathElement2);
    svgLineElement1 = document.createElementNS("http://www.w3.org/2000/svg", "line");
    textNode1 = document.createTextNode("mNfma;B N`p0ag     ");
    svgEllipseElement1.addEventListener("touchcancel", function () {}, false);
    document1 = document.implementation.createDocument("", null);
    svgAnimateElement1.appendChild(svgEllipseElement1);
    mathElement1.attributes[0].appendChild(textNode1);
    mathElement2.appendChild(svgAnimateElement1);
    document1.appendChild(svgLineElement1);
    svgLineElement1.appendChild(svgTestcaseElement1);
    mathElement1.attributes[0].addEventListener("DOMSubtreeModified", function () { document.open(); }, false);
    svgTestcaseElement1.appendChild(svgAnimAttributeElement1);
    document2 = document.implementation.createDocument("http://www.w3.org/1999/xhtml", "html"); document2.adoptNode(textNode1);
    svgAnimAttributeElement1.appendChild(mathElement2);
    svgEllipseElement1.parentNode.removeChild(svgEllipseElement1);
    delete svgEllipseElement1;
    gc();
    document.open();
    document.write("Passed. Test didn't crash.");
    document.close();
}
document.addEventListener("DOMContentLoaded", crash, false);
</script>
</html>


text:
package org.kududb.mapred;

/**
 * Created by bimal on 4/13/16.
 */
import org.apache.hadoop.hive.kududb.KuduHandler.HiveKuduWritable;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordWriter;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.util.Progressable;
import org.kududb.Schema;
import org.kududb.annotations.InterfaceAudience;
import org.kududb.annotations.InterfaceStability;
import org.kududb.client.*;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapred.OutputFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@InterfaceAudience.Public
@InterfaceStability.Evolving
public class HiveKuduTableOutputFormat implements OutputFormat, Configurable {

    private static final Logger LOG = LoggerFactory.getLogger(HiveKuduTableOutputFormat.class);

    /** Job parameter that specifies the output table. */
    static final String OUTPUT_TABLE_KEY = "kudu.mapreduce.output.table";

    /** Job parameter that specifies where the masters are */
    static final String MASTER_ADDRESSES_KEY = "kudu.mapreduce.master.addresses";

    /** Job parameter that specifies how long we wait for operations to complete */
    static final String OPERATION_TIMEOUT_MS_KEY = "kudu.mapreduce.operation.timeout.ms";

    /** Number of rows that are buffered before flushing to the tablet server */
    static final String BUFFER_ROW_COUNT_KEY = "kudu.mapreduce.buffer.row.count";

    /**
     * Job parameter that specifies which key is to be used to reach the HiveKuduTableOutputFormat
     * belonging to the caller
     */
    static final String MULTITON_KEY = "kudu.mapreduce.multitonkey";

    /**
     * This multiton is used so that the tasks using this output format/record writer can find
     * their KuduTable without having a direct dependency on this class,
     * with the additional complexity that the output format cannot be shared between threads.
     */
    private static final ConcurrentHashMap<String, HiveKuduTableOutputFormat> MULTITON = new
            ConcurrentHashMap<String, HiveKuduTableOutputFormat>();

    /**
     * This counter helps indicate which task log to look at since rows that weren't applied will
     * increment this counter.
     */
    public enum Counters { ROWS_WITH_ERRORS }

    private Configuration conf = null;

    private KuduClient client;
    private KuduTable table;
    private KuduSession session;
    private long operationTimeoutMs;

    @Override
    public void setConf(Configuration entries) {
        LOG.warn("I was called : setConf");
        this.conf = new Configuration(entries);

        String masterAddress = this.conf.get(MASTER_ADDRESSES_KEY);
        String tableName = this.conf.get(OUTPUT_TABLE_KEY);
        this.operationTimeoutMs = this.conf.getLong(OPERATION_TIMEOUT_MS_KEY,
                AsyncKuduClient.DEFAULT_OPERATION_TIMEOUT_MS);
        int bufferSpace = this.conf.getInt(BUFFER_ROW_COUNT_KEY, 1000);

        LOG.warn(" the master address here is " + masterAddress);

        this.client = new KuduClient.KuduClientBuilder(masterAddress)
                .defaultOperationTimeoutMs(operationTimeoutMs)
                .build();
        try {
            this.table = client.openTable(tableName);
        } catch (Exception ex) {
            throw new RuntimeException("Could not obtain the table from the master, " +
                    "is the master running and is this table created? tablename=" + tableName + " and " +
                    "master address= " + masterAddress, ex);
        }
        this.session = client.newSession();
        this.session.setFlushMode(AsyncKuduSession.FlushMode.AUTO_FLUSH_BACKGROUND);
        this.session.setMutationBufferSpace(bufferSpace);
        this.session.setIgnoreAllDuplicateRows(true);
        String multitonKey = String.valueOf(Thread.currentThread().getId());
        assert(MULTITON.get(multitonKey) == null);
        MULTITON.put(multitonKey, this);
        entries.set(MULTITON_KEY, multitonKey);
    }

    private void shutdownClient() throws IOException {
        LOG.warn("I was called : shutdownClient");
        try {
            client.shutdown();
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    public static KuduTable getKuduTable(String multitonKey) {
        LOG.warn("I was called : getKuduTable");
        return MULTITON.get(multitonKey).getKuduTable();
    }

    private KuduTable getKuduTable() {
        LOG.warn("I was called : getKuduTable");
        return this.table;
    }

    @Override
    public Configuration getConf() {
        LOG.warn("I was called : getConf");
        return conf;
    }

    @Override
    public RecordWriter getRecordWriter(FileSystem fileSystem, JobConf jobConf, String s, Progressable progressable)
            throws IOException {
        LOG.warn("I was called : getRecordWriter");
        return new TableRecordWriter(this.session);
    }

    @Override
    public void checkOutputSpecs(FileSystem fileSystem, JobConf jobConf) throws IOException {
        LOG.warn("I was called : checkOutputSpecs");
        shutdownClient();
    }

    /*
    @Override
    public OutputCommitter getOutputCommitter(TaskAttemptContext taskAttemptContext) throws
            IOException, InterruptedException {
        return new KuduTableOutputCommitter();
    }
    */

    protected class TableRecordWriter implements RecordWriter<NullWritable, HiveKuduWritable> {

        private final AtomicLong rowsWithErrors = new AtomicLong();
        private final KuduSession session;

        public TableRecordWriter(KuduSession session) {
            LOG.warn("I was called : TableRecordWriter");
            this.session = session;
        }

        private Operation getOperation(HiveKuduWritable hiveKuduWritable)
            throws IOException{
            LOG.warn("I was called : getOperation");
            int recCount = hiveKuduWritable.getColCount();
            Schema schema = table.getSchema();
            int colCount = schema.getColumnCount();
            if (recCount != colCount) {
                throw new IOException("Kudu table column count of " + colCount + " does not match "
                        + "with Serialized object record count of " + recCount);
            }
            //TODO: Find out if the record needs to be updated or deleted.
            //Assume only insert

            Insert insert = table.newInsert();
            PartialRow row = insert.getRow();

            for (int i = 0; i < recCount; i++) {
                Object obj = hiveKuduWritable.get(i);
                LOG.warn("From Writable Column value of " + i + " is " + obj.toString() + " and type is " + hiveKuduWritable.getType(i).name());
                LOG.warn("From Schema Column name of " + i + " is " + schema.getColumnByIndex(i).getName());
                switch(hiveKuduWritable.getType(i)) {
                    case STRING: {
                        LOG.warn("I was called : STRING");
                        String s = obj.toString();
                        row.addString(i, s);
                        break;
                    }
                    case FLOAT: {
                        LOG.warn("I was called : FLOAT");
                        Float f = (Float) obj;
                        row.addFloat(i, f);
                        break;
                    }
                    case DOUBLE: {
                        LOG.warn("I was called : DOUBLE");
                        Double d = (Double) obj;
                        row.addDouble(i, d);
                        break;
                    }
                    case BOOL: {
                        LOG.warn("I was called : BOOL");
                        Boolean b = (Boolean) obj;
                        row.addBoolean(i, b);
                        break;
                    }
                    case INT8: {
                        LOG.warn("I was called : INT8");
                        Byte b = (Byte) obj;
                        row.addByte(i, b);
                        break;
                    }
                    case INT16: {
                        LOG.warn("I was called : INT16");
                        Short s = (Short) obj;
                        row.addShort(i, s);
                        break;
                    }
                    case INT32: {
                        LOG.warn("I was called : INT32");
                        Integer x = (Integer) obj;
                        row.addInt(i, x);
                        break;
                    }
                    case INT64: {
                        LOG.warn("I was called : INT64");
                        Long l = (Long) obj;
                        row.addLong(i, l);
                        break;
                    }
                    case TIMESTAMP: {
                        LOG.warn("I was called : TIMESTAMP");
                        Long time = (Long) obj;
                        row.addLong(i, time);
                        break;
                    }
                    case BINARY: {
                        LOG.warn("I was called : BINARY");
                        byte[] b = (byte[]) obj;
                        row.addBinary(i, b);
                        break;
                    }
                    default:
                        throw new IOException("Cannot write Object '"
                                + obj.getClass().getSimpleName() + "' as type: " + hiveKuduWritable.getType(i).name());
                }
            }

            return insert;
        }
        @Override
        public void write(NullWritable key, HiveKuduWritable kw)
                throws IOException {
            try {
                LOG.warn("I was called : write");
                Operation operation = getOperation(kw);
                session.apply(operation);

                //read from Kudu if the insert was successful
                List<String> projectColumns = new ArrayList<>(2);
                projectColumns.add("id");
                projectColumns.add("name");
                KuduScanner scanner = client.newScannerBuilder(table)
                        .setProjectedColumnNames(projectColumns)
                        .build();

                while (scanner.hasMoreRows()) {
                    RowResultIterator results = scanner.nextRows();
                    while (results.hasNext()) {
                        RowResult result = results.next();
                        LOG.warn("Returned from kudu" + result.getInt(0) + ":" +result.getString(1));
                    }
                }

                LOG.warn("applying operation");

            } catch (Exception e) {
                throw new IOException("Encountered an error while writing", e);
            }
        }

        @Override
        public void close(Reporter reporter) throws IOException {
            try {
                LOG.warn("I was called : close");
                processRowErrors(session.close());
                shutdownClient();
            } catch (Exception e) {
                throw new IOException("Encountered an error while closing this task", e);
            } finally {
                if (reporter != null) {
                    // This is the only place where we have access to the context in the record writer,
                    // so set the counter here.
                    reporter.getCounter(Counters.ROWS_WITH_ERRORS).setValue(rowsWithErrors.get());
                }
            }
        }

        private void processRowErrors(List<OperationResponse> responses) {
            LOG.warn("I was called : processRowErrors");
            List<RowError> errors = OperationResponse.collectErrors(responses);
            if (!errors.isEmpty()) {
                int rowErrorsCount = errors.size();
                rowsWithErrors.addAndGet(rowErrorsCount);
                LOG.warn("Got per errors for " + rowErrorsCount + " rows, " +
                        "the first one being " + errors.get(0).getStatus());
            }
        }
    }
}


text:
class AddDispensaryMenuIdToSpecials < ActiveRecord::Migration
  def change
    add_column :specials, :dispensary_menu_id, :integer
  end
end


text:
import logging

from ..all_steps.event_handler import EventHandler as TopEventHandler
from ..step1.data_handler import DataHandler
from ..step1.plot import Step1Plot
from .gui_handler import Step3GuiHandler

from ..utilities.retrieve_data_infos import RetrieveGeneralDataInfos

from .. import DataType

class EventHandler(TopEventHandler):

    def import_button_clicked(self):
        logging.info(f"{self.data_type} import button clicked")

        self.parent.loading_flag = True
        o_load = DataHandler(parent=self.parent,
                             data_type=self.data_type)
        _folder = o_load.select_folder()
        o_load.import_files_from_folder(folder=_folder, extension=[".tif", ".fits", ".tiff"])
        o_load.import_time_spectra()

        if not (self.parent.data_metadata[self.data_type]['data'] is None):
            self.update_ui_after_loading_data(folder=_folder)

        self.check_time_spectra_status()

    def sample_list_selection_changed(self):
        if not self.parent.loading_flag:
            o_retrieve_data_infos = RetrieveGeneralDataInfos(parent=self.parent, data_type=DataType.normalized)
            o_retrieve_data_infos.update()
            self.parent.roi_normalized_image_view_changed(mouse_selection=False)
        else:
            self.parent.loading_flag = False

    def import_button_clicked_automatically(self, folder=None):

        o_load = DataHandler(parent=self.parent,
                             data_type=self.data_type)
        o_load.import_files_from_folder(folder=folder, extension=[".tif", ".fits", ".tiff"])
        o_load.import_time_spectra()

        if self.parent.data_metadata[self.data_type]['data'].any():
            self.update_ui_after_loading_data(folder=folder)

    def update_ui_after_loading_data(self, folder=None):
        self.parent.data_metadata[self.data_type]['folder'] = folder
        self.parent.select_load_data_row(data_type=self.data_type, row=0)
        self.parent.retrieve_general_infos(data_type=self.data_type)
        self.parent.retrieve_general_data_infos(data_type=self.data_type)
        o_plot = Step1Plot(parent=self.parent, data_type=self.data_type)
        o_plot.initialize_default_roi()
        o_plot.display_bragg_edge(mouse_selection=False)
        o_gui = Step3GuiHandler(parent=self.parent)
        o_gui.check_widgets()
        self.check_time_spectra_status()

    def check_time_spectra_status(self):
        if str(self.parent.ui.time_spectra_2.text()):
            self.parent.ui.display_warning_2.setVisible(False)
        else:
            self.parent.ui.display_warning_2.setVisible(True)


text:
A one-node dialogue system for Godot 2.x

I have originally made this for a game of my own, given that I wanted to have something that wouldn't require any additional nodes to use. I tried out the two systems available for Godot at the AssetLib, but neither fit my needs. And so here we are, with this script.

Features capability for drawing text with effects, like *wave, bounce, shake* or even altering the delay, all inside one string.

I've distributed this code under the *MIT License*. I'd be happy to see contributions to make this system work even better or have my name be mentioned somewhere for the effort of making this.

Check out how it looks like here: https://twitter.com/ArcOfDream/status/833823158503370752

###How to use
To set this up for use, you need to first attach this script to a Control node, such as NinePatchFrame or ColorFrame.  You also need to set up a font, prefferably a DynamicFont which allows changing sizes, which you then save as a resource file. That resource file is what you use inside the script for use.

To start a dialog, you use the **run_dialog()** method with an array holding the dialogue passed as a parameter. I've left out an example inside to show how that looks like.

To progress with the dialogue, you will have to set up an input process to handle that with the use of **next_line()**, and when the whole dialogue is done, a **dialog_end** signal is emitted.


text:
function camelCase(name) {
    return name.charAt(0).toLowerCase() + name.slice(1);
}
var ValueConverterResource = (function () {
    function ValueConverterResource(name) {
        this.name = name;
    }
    ValueConverterResource.convention = function (name) {
        if (name.endsWith('ValueConverter')) {
            return new ValueConverterResource(camelCase(name.substring(0, name.length - 14)));
        }
    };
    ValueConverterResource.prototype.analyze = function (container, target) {
        this.instance = container.get(target);
    };
    ValueConverterResource.prototype.register = function (registry, name) {
        registry.registerValueConverter(name || this.name, this.instance);
    };
    ValueConverterResource.prototype.load = function (container, target) {
        return Promise.resolve(this);
    };
    return ValueConverterResource;
})();
exports.ValueConverterResource = ValueConverterResource;


text:
package com.orientechnologies.orient.core.command.script;

import com.orientechnologies.common.concur.resource.OPartitionedObjectPool;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.command.OCommandExecutorAbstract;
import com.orientechnologies.orient.core.command.OCommandRequest;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.function.OFunction;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.ORule;

import javax.script.*;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Executes Script Commands.
 *
 * @see OCommandScript
 * @author Luca Garulli
 *
 */
public class OCommandExecutorFunction extends OCommandExecutorAbstract {
  protected OCommandFunction request;

  public OCommandExecutorFunction() {
  }

  @SuppressWarnings("unchecked")
  public OCommandExecutorFunction parse(final OCommandRequest iRequest) {
    request = (OCommandFunction) iRequest;
    return this;
  }

  public Object execute(final Map<Object, Object> iArgs) {
    return executeInContext(null, iArgs);
  }

  public Object executeInContext(final OCommandContext iContext, final Map<Object, Object> iArgs) {

    parserText = request.getText();

    ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.INSTANCE.get();
    final OFunction f = db.getMetadata().getFunctionLibrary().getFunction(parserText);

    db.checkSecurity(ORule.ResourceGeneric.FUNCTION, ORole.PERMISSION_READ, f.getName());

    final OScriptManager scriptManager = Orient.instance().getScriptManager();

    final OPartitionedObjectPool.PoolEntry<ScriptEngine> entry = scriptManager.acquireDatabaseEngine(db.getName(), f.getLanguage());
    final ScriptEngine scriptEngine = entry.object;
    try {
      final Bindings binding = scriptManager.bind(scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE), (ODatabaseDocumentTx) db,
          iContext, iArgs);

      try {
        final Object result;

        if (scriptEngine instanceof Invocable) {
          // INVOKE AS FUNCTION. PARAMS ARE PASSED BY POSITION
          final Invocable invocableEngine = (Invocable) scriptEngine;
          Object[] args = null;
          if (iArgs != null) {
            args = new Object[iArgs.size()];
            int i = 0;
            for (Entry<Object, Object> arg : iArgs.entrySet())
              args[i++] = arg.getValue();
          }
          result = invocableEngine.invokeFunction(parserText, args);

        } else {
          // INVOKE THE CODE SNIPPET
          final Object[] args = iArgs == null ? null : iArgs.values().toArray();
          result = scriptEngine.eval(scriptManager.getFunctionInvoke(f, args), binding);
        }

        return OCommandExecutorUtility.transformResult(result);

      } catch (ScriptException e) {
        throw new OCommandScriptException("Error on execution of the script", request.getText(), e.getColumnNumber(), e);
      } catch (NoSuchMethodException e) {
        throw new OCommandScriptException("Error on execution of the script", request.getText(), 0, e);
      } catch (OCommandScriptException e) {
        // PASS THROUGH
        throw e;

      } finally {
        scriptManager.unbind(binding, iContext, iArgs);
      }
    } finally {
      scriptManager.releaseDatabaseEngine(f.getLanguage(), db.getName(), entry);
    }
  }

  public boolean isIdempotent() {
    return false;
  }

  @Override
  protected void throwSyntaxErrorException(String iText) {
    throw new OCommandScriptException("Error on execution of the script: " + iText, request.getText(), 0);
  }
}


text:
package main

import (
	"encoding/gob"
	"flag"
	"fmt"
	"github.com/golang/glog"
	"github.com/monmohan/xferspdy"
	"os"
	"path/filepath"
)

var (
	fPath   = flag.String("file", "", "File path to create the fingerprint, REQUIRED ")
	blockSz = flag.Uint64("blocksz", 2*1024, "Block Size, default block size is 2KB")
	verify  = flag.Bool("verify", false, "Verify fingerprint on creation")
)

func main() {
	flag.Parse()
	if *fPath == "" {
		fmt.Println("Missing File parameter")
		flag.Usage()
		return
	}
	glog.V(2).Infof("File path %s , Block Size %d \n", *fPath, *blockSz)

	fgprt := xferspdy.NewFingerprint(*fPath, uint32(*blockSz))
	glog.V(4).Infof("Signature  %s \n", *fgprt)

	dir, fname := filepath.Split(*fPath)

	fname = filepath.Join(dir, fname+".fingerprint")

	fpfile, err := os.OpenFile(fname, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)

	if err != nil {
		glog.Fatalf("Error in creating finger print file %v \n, Error :%s", filepath.Join(dir, fname+".fingerprint"), err)
	}

	enc := gob.NewEncoder(fpfile)
	enc.Encode(*fgprt)
	fmt.Printf("Fingerprint for file: %v \nGenerated:  %v \n ", *fPath, fpfile.Name())
	fpfile.Close()

	fpfile, err = os.Open(fname)
	defer fpfile.Close()

	var fp xferspdy.Fingerprint
	dec := gob.NewDecoder(fpfile)
	err = dec.Decode(&fp)
	if *verify {
		glog.V(4).Infof("Verifying signature , created %v\n decoded from file %v\n", *fgprt, fp)

		if err != nil || (len(fgprt.BlockMap) != len(fp.BlockMap)) {
			glog.Fatalf("Failed to decode finger print during verification %v\n", err)
		}
	}
	glog.Flush()

}