text:
package com.sun.org.apache.bcel.internal.classfile;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *    "Apache BCEL" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    "Apache BCEL", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

import  com.sun.org.apache.bcel.internal.Constants;
import  java.io.*;

/**
 * This class is derived from Attribute and declares this class as
 * `synthetic', i.e., it needs special handling.  The JVM specification
 * states "A class member that does not appear in the source code must be
 * marked using a Synthetic attribute."  It may appear in the ClassFile
 * attribute table, a field_info table or a method_info table.  This class
 * is intended to be instantiated from the
 * Attribute.readAttribute() method.
 *
 * @author  M. Dahm
 * @see     Attribute
 */
public final class Synthetic extends Attribute {
  private byte[] bytes;

  /**
   * Initialize from another object. Note that both objects use the same
   * references (shallow copy). Use copy() for a physical copy.
   */
  public Synthetic(Synthetic c) {
    this(c.getNameIndex(), c.getLength(), c.getBytes(), c.getConstantPool());
  }

  /**
   * @param name_index Index in constant pool to CONSTANT_Utf8, which
   * should represent the string "Synthetic".
   * @param length Content length in bytes - should be zero.
   * @param bytes Attribute contents
   * @param constant_pool The constant pool this attribute is associated
   * with.
   */
  public Synthetic(int name_index, int length, byte[] bytes,
                   ConstantPool constant_pool)
  {
    super(Constants.ATTR_SYNTHETIC, name_index, length, constant_pool);
    this.bytes         = bytes;
  }

  /**
   * Construct object from file stream.
   * @param name_index Index in constant pool to CONSTANT_Utf8
   * @param length Content length in bytes
   * @param file Input stream
   * @param constant_pool Array of constants
   * @throws IOException
   */
  Synthetic(int name_index, int length, DataInputStream file,
            ConstantPool constant_pool) throws IOException
  {
    this(name_index, length, (byte [])null, constant_pool);

    if(length > 0) {
      bytes = new byte[length];
      file.readFully(bytes);
      System.err.println("Synthetic attribute with length > 0");
    }
  }
  /**
   * Called by objects that are traversing the nodes of the tree implicitely
   * defined by the contents of a Java class. I.e., the hierarchy of methods,
   * fields, attributes, etc. spawns a tree of objects.
   *
   * @param v Visitor object
   */
  public void accept(Visitor v) {
    v.visitSynthetic(this);
  }
  /**
   * Dump source file attribute to file stream in binary format.
   *
   * @param file Output file stream
   * @throws IOException
   */
  public final void dump(DataOutputStream file) throws IOException
  {
    super.dump(file);
    if(length > 0)
      file.write(bytes, 0, length);
  }
  /**
   * @return data bytes.
   */
  public final byte[] getBytes() { return bytes; }

  /**
   * @param bytes.
   */
  public final void setBytes(byte[] bytes) {
    this.bytes = bytes;
  }

  /**
   * @return String representation.
   */
  public final String toString() {
    StringBuffer buf = new StringBuffer("Synthetic");

    if(length > 0)
      buf.append(" " + Utility.toHexString(bytes));

    return buf.toString();
  }

  /**
   * @return deep copy of this attribute
   */
  public Attribute copy(ConstantPool constant_pool) {
    Synthetic c = (Synthetic)clone();

    if(bytes != null)
      c.bytes = (byte[])bytes.clone();

    c.constant_pool = constant_pool;
    return c;
  }
}


text:
package com.amee.calculation.service;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Map;

public class ServiceFinder {

    private Map<String, Service> serviceMap;
    private Map<String, Object> values;
    private ProfileFinder profileFinder;

    public ServiceFinder(Map<String, Service> serviceMap) {
        this.serviceMap = serviceMap;
    }

    public Service getService(String serviceName) {
        Service service = serviceMap.get(serviceName);
        service.setValues(values);
        service.setProfileFinder(profileFinder);
        return service;
    }

    public void setValues(Map<String, Object> values) {
        this.values = values;
    }

    public void setProfileFinder(ProfileFinder profileFinder) {
        this.profileFinder = profileFinder;
    }

    public static void main(String[] args) throws Exception {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-algorithmServices.xml");
        ServiceFinder service = (ServiceFinder) ctx.getBean("serviceFinder");
        Service rs = service.getService("train-route-finder-service");
        System.out.println(rs.invoke());
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.models.ApiAuthenticationConfigurationBase;
import com.microsoft.graph.models.Entity;

import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Identity Api Connector.
 */
public class IdentityApiConnector extends Entity implements IJsonBackedObject {

    /**
     * The Authentication Configuration.
     * The object which describes the authentication configuration details for calling the API. Basic and PKCS 12 client certificate are supported.
     */
    @SerializedName(value = "authenticationConfiguration", alternate = {"AuthenticationConfiguration"})
    @Expose
	@Nullable
    public ApiAuthenticationConfigurationBase authenticationConfiguration;

    /**
     * The Display Name.
     * The name of the API connector.
     */
    @SerializedName(value = "displayName", alternate = {"DisplayName"})
    @Expose
	@Nullable
    public String displayName;

    /**
     * The Target Url.
     * The URL of the API endpoint to call.
     */
    @SerializedName(value = "targetUrl", alternate = {"TargetUrl"})
    @Expose
	@Nullable
    public String targetUrl;

    /**
     * Sets the raw JSON object
     *
     * @param serializer the serializer
     * @param json the JSON object to set this object to
     */
    public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {

    }
}


text:
package com.baidubce.services.vca.model;

import java.util.Date;
import java.util.List;

import com.baidubce.model.AbstractBceResponse;

public class ImageAnalyzeResponse extends AbstractBceResponse {
    private String source;
    private String title;
    private String preset;
    private String status;
    private Date publishTime; // finish time
    private String error; // exists only when status = ERROR
    private List<ImageAnalyzeResult> results; // exists only when status = FINISHED

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("ImageAnalyzeResponse{");
        sb.append("source='").append(source).append('\'');
        sb.append(", title='").append(title).append('\'');
        sb.append(", preset='").append(preset).append('\'');
        sb.append(", status='").append(status).append('\'');
        sb.append(", finishTime='").append(publishTime).append('\'');
        sb.append(", results='").append(results).append('\'');
        sb.append(", error=").append(error);
        sb.append('}');
        return sb.toString();
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getTitle() {
        return title;
    }

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

    public String getPreset() {
        return preset;
    }

    public void setPreset(String preset) {
        this.preset = preset;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Date getPublishTime() {
        return publishTime;
    }

    public void setPublishTime(Date publishTime) {
        this.publishTime = publishTime;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    public List<ImageAnalyzeResult> getResults() {
        return results;
    }

    public void setResults(List<ImageAnalyzeResult> results) {
        this.results = results;
    }
}


text:
package sso.foo;

import java.util.ArrayList;

import sso.gauss.GParticle;
import sso.gauss.Point;

public class TestCorrect {

	public static void main(String[] args) {

		ArrayList<Double> ddd = new ArrayList<Double>();
		for (int i = 0; i < 4; i++) {
			ddd.add(0.5);
		}
		//ddd.add(0.61);
		System.out.println(ddd);
		System.out.println("	...correct:...");
		GParticle.correct(ddd);
		System.out.println(ddd);
		System.out.println("	...correctKocka:...");
		GParticle.correctKocka(ddd);
		System.out.println(ddd);

	}

}


text:
package com.google.gwt.inject.rebind.adapter;

import com.google.gwt.inject.client.binder.GinAnnotatedElementBuilder;
import com.google.gwt.inject.client.binder.PrivateGinBinder;
import com.google.gwt.inject.rebind.GinjectorBindings;
import com.google.inject.Key;
import com.google.inject.PrivateBinder;
import com.google.inject.TypeLiteral;

/**
 * Provides the {@link PrivateGinBinder} interface and adapts it to a regular Guice
 * {@link PrivateBinder}.
 */
public class PrivateBinderAdapter extends BinderAdapter implements PrivateGinBinder {

  private final PrivateBinder privateBinder;

  PrivateBinderAdapter(PrivateBinder privateBinder, GinjectorBindings bindings) {
    super(privateBinder, bindings);
    this.privateBinder = privateBinder;
  }

  public void expose(Key<?> key) {
    privateBinder.expose(key);
  }

  public GinAnnotatedElementBuilder expose(Class<?> type) {
    return new AnnotatedElementBuilderAdapter(privateBinder.expose(type));
  }

  public GinAnnotatedElementBuilder expose(TypeLiteral<?> type) {
    return new AnnotatedElementBuilderAdapter(privateBinder.expose(type));
  }
}


text:
package cmwell.blueprints.jena

import org.apache.jena.rdf.model._
import com.tinkerpop.blueprints.Element

import scala.collection.JavaConversions._
import scala.collection.mutable.ListBuffer
import Extensions._

abstract class JenaElement(val model: Model, val rdfNode: RDFNode) extends Element {

  private val propertiesSelector = new SimpleSelector {
    override def selects(s: Statement) = s.getSubject.id == rdfNode.id && s.getObject.isLiteral
  }

  override def getProperty[T](key: String): T = {
    val it = model.listStatements(propertiesSelector)
    val values = ListBuffer[Any]()
    while (it.hasNext) {
      val next = it.next
      if (next.getPredicate.id == key)
        values += next.getObject.asLiteral.getValue
    }

    (values.size match {
      case 0 => null
      case 1 => values.head
      case _ => values.toArray
    }).asInstanceOf[T]
  }

  override def getPropertyKeys: java.util.Set[String] =
    model.listStatements(propertiesSelector).map(_.getPredicate.id.toString).toSet[String]

  override def equals(obj: Any): Boolean = {
    (obj != null) &&
    (getClass eq obj.getClass) && {
      val other: JenaVertex = obj.asInstanceOf[JenaVertex]
       (rdfNode != null)       &&
       (other.rdfNode != null) &&
       (rdfNode == other.rdfNode)
    }
  }

  override def hashCode: Int = {
    31 + (if (rdfNode == null) 0 else rdfNode.hashCode)
  }

  override def removeProperty[T](key: String): T = throw new UnsupportedOperationException("RDF Edge has no Props")
  override def setProperty(key: String, value: Object) =
    throw new UnsupportedOperationException("RDF Edge has no Props")
}


text:
#include "harness_defs.h"

#if __TBB_TEST_SKIP_AFFINITY
#define HARNESS_NO_PARSE_COMMAND_LINE 1
#include "harness.h"
int TestMain() {
    return Harness::Skipped;
}
#else /* affinity mask can be set and used by TBB */

#include "harness.h"
#include "harness_concurrency.h"

#include "tbb/task_scheduler_init.h"
#include "tbb/tbb_thread.h"
#include "tbb/enumerable_thread_specific.h"

// The declaration of a global ETS object is needed to check that
// it does not initialize the task scheduler, and in particular
// does not set the default thread number. TODO: add other objects
// that should not initialize the scheduler.
tbb::enumerable_thread_specific<std::size_t> ets;

int TestMain () {
    int maxProcs = Harness::GetMaxProcs();

    if ( maxProcs < 2 )
        return Harness::Skipped;

    int availableProcs = maxProcs/2;
    ASSERT( Harness::LimitNumberOfThreads( availableProcs ) == availableProcs, "LimitNumberOfThreads has not set the requested limitation." );
    ASSERT( tbb::task_scheduler_init::default_num_threads() == availableProcs, NULL );
    ASSERT( (int)tbb::tbb_thread::hardware_concurrency() == availableProcs, NULL );
    return Harness::Done;
}
#endif /* __TBB_TEST_SKIP_AFFINITY */


text:
package org.antlr.v4.codegen.model.chunk;

import org.antlr.v4.codegen.model.decl.StructDecl;

public abstract class SymbolRefChunk extends ActionChunk {
	public final String name;
	public final String escapedName;

	public SymbolRefChunk(StructDecl ctx, String name, String escapedName) {
		super(ctx);
		this.name = name;
		this.escapedName = escapedName;
	}
}


text:
import matplotlib.pyplot as plt
import numpy as np

fig=plt.figure(1)

# Create the first subplot (first of 3 rows)
fig1=plt.subplot(311)

# Axes labels (vertical labels on the left)
plt.xlabel(  '$t$')
plt.ylabel('$S(t)$', rotation='horizontal')

# Load the data as arrays. We take the transpose because each array must be homogeneous
# The first (index 0) is always the time
redent = (np.loadtxt('RED-ENTROPY.dat')).T
cpent  = (np.loadtxt( 'CP-ENTROPY.dat')).T

# Plot the the graphs
rfig = plt.plot(redent[0], redent[1], color='red',
        label='Redfield dynamics entropy')
cfig = plt.plot(cpent[0],  cpent[1],  color='blue',
        label='Completely positive dynamics entropy')

# Draw the grid
fig1.grid(True)

# Write the legend
plt.legend(('Redfield dynamics entropy',
    'Completely positive dynamics entropy'), loc='upper left',
    bbox_to_anchor=(0.2, 0.95))

# Create another label for the right vertical axis, leaving unaltered the horizontal one
ax = plt.twinx()
plt.ylabel('$\sigma(t)$', rotation='horizontal')

# Load the entropy production data into arrays
redprod = (np.loadtxt('RED-ENTROPY-PROD.dat')).T
cpprod  = (np.loadtxt('CP-ENTROPY-PROD.dat')).T

# Plot the graphs, draw the grid and write the legend
rpfig = plt.plot(redprod[0], redprod[1], 'y-', label='Redfield entropy production')
cpfig = plt.plot(cpprod[0], cpprod[1], 'c-', label='Completely positive entropy prod.')

plt.grid(True)
plt.legend(('Redfield entropy prod.', 'Completely posit. entropy prod.'),
        loc='upper left', bbox_to_anchor=(0.2, 0.6))

# Second subplot: time-evolution of the states in the Redfield dynamics
fig2 = plt.subplot(312)
redstat = (np.loadtxt('RED-EVOLUTION.dat')).T

# Every component of the Bloch vector must be plotted separetely
plt.plot(redstat[0],redstat[1])
plt.plot(redstat[0],redstat[2])
plt.plot(redstat[0],redstat[3])

fig2.grid(True)

# Third subplot: time-evolution of the states in the CP dynamics
fig3=plt.subplot(313)
cpstat = (np.loadtxt('CP-EVOLUTION.dat')).T

plt.plot(cpstat[0],cpstat[1])
plt.plot(cpstat[0],cpstat[2])
plt.plot(cpstat[0],cpstat[3])

fig3.grid(True)

plt.show()


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Admin_adduser_model extends CI_Model {

	function adduser($data){
		$this->db->insert('user', $data);
	}
}


text:
@interface NSDictionary(Utility)
- (id)objectForKeyNotNull:(id)key;
@end


text:
package org.motechproject.server.config;

import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.motechproject.config.core.exception.MotechConfigurationException;
import org.motechproject.config.service.ConfigurationService;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import static junit.framework.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

public class SettingsFacadeTest {

    private static final String BUNDLE_NAME = "org.motechproject.motech-module-bundle";
    private static final String BUNDLE_VERSION = "";
    private static final String FILENAME = "settings.properties";
    private static final String LANGUAGE_PROP = "system.language";
    private static final String LANGUAGE_VALUE = "en";
    private static final String TEST_PROP = "test";
    private static final String TEST_VAL = "test-val";
    private static final String MOCK_FILENAME = "testfile";

    SettingsFacade settingsFacade = new SettingsFacade();

    @Mock
    Properties props;

    @Mock
    ConfigurationService configurationService;

    @Mock
    BundleContext bundleContext;

    @Mock
    Bundle bundle;

    @Mock
    ServiceReference ref;

    @Before
    public void setUp() {
        initMocks(this);
    }

    @Test
    public void testSetConfig() throws IOException {
        when(configurationService.getBundleProperties(eq(BUNDLE_NAME), eq(FILENAME), any(Properties.class))).thenReturn(null);
        when(props.getProperty(LANGUAGE_PROP)).thenReturn(LANGUAGE_VALUE);
        when(props.containsKey(LANGUAGE_PROP)).thenReturn(true);

        setUpConfig();

        ArgumentCaptor<Properties> argument = ArgumentCaptor.forClass(Properties.class);
        verify(configurationService).addOrUpdateProperties(eq(BUNDLE_NAME), eq(BUNDLE_VERSION), eq(FILENAME),
                argument.capture(), any(Properties.class));
        assertEquals(LANGUAGE_VALUE, argument.getValue().getProperty(LANGUAGE_PROP));
    }

    @Test
    public void testAsProperties() throws IOException {
        setUpConfig();
        Properties otherProps = new Properties();
        otherProps.put(TEST_PROP, TEST_VAL);
        settingsFacade.saveConfigProperties(MOCK_FILENAME, otherProps);
        settingsFacade.afterPropertiesSet();

        Properties result = settingsFacade.asProperties();

        assertEquals(2, result.size());
        assertEquals(TEST_VAL, result.get(TEST_PROP));
        assertEquals(LANGUAGE_VALUE, result.get(LANGUAGE_PROP));
    }

    @Test(expected = MotechConfigurationException.class)
    public void shouldThrowExceptionsComingFromService() throws IOException {
        when(configurationService.registersProperties(anyString(), anyString()))
                .thenThrow(new MotechConfigurationException("file could not be read"));
        setUpConfig();
    }

    private void setUpConfig() throws IOException {
        setUpOSGiEnv();

        Properties properties = new Properties();
        properties.put(LANGUAGE_PROP, LANGUAGE_VALUE);

        when(configurationService.getBundleProperties(BUNDLE_NAME, FILENAME, properties)).thenReturn(properties);

        List<Resource> configFiles = new ArrayList<>();
        configFiles.add(new ClassPathResource(FILENAME));
        settingsFacade.setConfigFiles(configFiles);

        verify(configurationService).registersProperties(BUNDLE_NAME, FILENAME);
        verify(configurationService).addOrUpdateProperties(BUNDLE_NAME, BUNDLE_VERSION, FILENAME,
                properties, properties);
    }

    private void setUpOSGiEnv() {
        when(bundleContext.getBundle()).thenReturn(bundle);
        when(bundle.getSymbolicName()).thenReturn(BUNDLE_NAME);

        settingsFacade.setBundleContext(bundleContext);

        when(bundleContext.getServiceReference(ConfigurationService.class.getName())).thenReturn(ref);
        when(bundleContext.getService(ref)).thenReturn(configurationService);

        settingsFacade.afterPropertiesSet();
    }
}


text:
<?php
class SampleExceptionFlow extends Flow{
	public function throw_method(){
		throw new LogicException('error');
	}
}


text:
package com.zerodes.bta.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zerodes.bta.dao.CategoryAssignmentDAO;
import com.zerodes.bta.domain.CategoryAssignment;
import com.zerodes.bta.domain.User;

@Repository
@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
public class CategoryAssignmentDAOImpl extends AbstractJpaDao<CategoryAssignment> implements CategoryAssignmentDAO {

	@PersistenceContext(unitName = "entityManagerFactory")
	private EntityManager entityManager;

	@Override
	public EntityManager getEntityManager() {
		return entityManager;
	}

	@Override
	public CategoryAssignment findByVendorAndDescription(final User user, final String vendor, final String description) {
		Query query = createNamedQuery("findByVendorAndDescription", user, vendor, description);
		List<CategoryAssignment> results = query.getResultList();
		if (results.size() == 0) {
			return null;
		}
		return results.get(0);
	}

	@Override
	public List<CategoryAssignment> findByUser(final User user) {
		Query query = createNamedQuery("findByUser", user);
		return query.getResultList();
	}
}


text:
package org.datavec.spark.transform.rank;

import org.apache.spark.api.java.function.Function;
import org.datavec.api.writable.LongWritable;
import org.datavec.api.writable.Writable;
import scala.Tuple2;

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

public class UnzipForCalculateSortedRankFunction
                implements Function<Tuple2<Tuple2<Writable, List<Writable>>, Long>, List<Writable>> {
    @Override
    public List<Writable> call(Tuple2<Tuple2<Writable, List<Writable>>, Long> v1) throws Exception {
        List<Writable> inputWritables = new ArrayList<>(v1._1()._2());
        inputWritables.add(new LongWritable(v1._2()));
        return inputWritables;
    }
}


text:
@interface UTAnalytics : NSObject

+(UTAnalytics *) getInstance;

-(void) setAppVersion:(NSString *) pAppVersion;

-(void) setChannel:(NSString *) pChannel;

-(void) updateUserAccount:(NSString *) pNick userid:(NSString *) pUserId;

-(void) userRegister:(NSString *) pUsernick;

-(void) updateSessionProperties:(NSDictionary *) pDict;

-(UTTracker *) getDefaultTracker;

-(UTTracker *) getTracker:(NSString *)  pTrackId;

-(void) setRequestAuthentication:(id<UTIRequestAuthentication> ) pRequestAuth;

-(void) turnOnDebug;

-(void) turnOffCrashHandler;

-(void) setCrashCaughtListener:(id<UTICrashCaughtListener>) aListener;

@end


text:
/******************************************************************************************************/
/*                                                                                */
/*    Infinidat Ltd.  -  Proprietary and Confidential Material                                        */
/*                                                                                */
/*    Copyright (C) 2013, Infinidat Ltd. - All Rights Reserved                                        */
/*                                                                                */
/*    NOTICE: All information contained herein is, and remains the property of Infinidat Ltd.         */
/*    All information contained herein is protected by trade secret or copyright law.                 */
/*    The intellectual and technical concepts contained herein are proprietary to Infinidat Ltd.,     */
/*    and may be protected by U.S. and Foreign Patents, or patents in progress.                       */
/*                                                                                */
/*    Redistribution or use, in source or binary forms, with or without modification,                 */
/*    are strictly forbidden unless prior written permission is obtained from Infinidat Ltd.          */
/*                                                                                */
/*                                                                                */
/******************************************************************************************************/

package org.mestor.util;

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

import com.google.common.primitives.Primitives;

/**
 * This class contains type conversion and discovery utilities
 * @author alexr
 */
public class TypeUtil {
	private static Class<?>[] compatibility = new Class[] {
		double.class, float.class, long.class, int.class, short.class, byte.class
	};

	private static Map<Class<?>, Integer> compatibilityMap = new HashMap<>();
	static {
		for (int i = 0; i < compatibility.length; i++) {
			compatibilityMap.put(compatibility[i], i);
		}
	}

	/**
	 * This method is an "extension" of {@link Class#isAssignableFrom(Class)} but supports primitives and primitive
	 * wrappers as well.
	 * <br/>
	 * The method returns {@code true} if {@code left.isAssignableFrom(right)} is true or if unwrapped version of both
	 * classes are equal or if both classes represent numeric type and {@code right} can be assigned to {@code left}
	 * using natural conversion, e.g. {@code int} can be assigned to {@code long} but {@code long} cannot be assigned to
	 * {@code int} without casting and possible presision lost.
	 *
	 * @param left
	 * @param right
	 * @return true if right is assignable to left
	 */
	public static boolean isCompatibleTo(final Class<?> left, final Class<?> right) {
		if (left.isAssignableFrom(right)) {
			return true;
		}

		final Class<?> l = Primitives.unwrap(left);
		final Class<?> r = Primitives.unwrap(right);

		if (l == null || r == null) {
			return false;  // at list one of them is not primitive
		}

		// both are primitives

		// if both primitive types are the same they are definitly compatible
		if (l.equals(r)) {
			return true;
		}

		// check in chain of compatibility
		final Integer leftCompIndex = compatibilityMap.get(l);
		final Integer rightCompIndex = compatibilityMap.get(r);

		if (leftCompIndex == null || rightCompIndex == null) {
			// at least one of them is not numeric
			return false;
		}

		return leftCompIndex < rightCompIndex;
	}

	public static boolean compareTypes(final Class<?> declaredType, final Class<?> actualType){
		return isCompatibleTo(declaredType, actualType);
		/*
		if(declaredType.isAssignableFrom(actualType)){
			return true;
		}
		return declaredType.isPrimitive() && declaredType.equals(Primitives.unwrap(actualType));
		*/
	}
}


text:
package com.example.android.sunshine.app;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.json.JSONException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * Created by Guilherme on 30/08/2016.
 */
public class ForecastFragment extends Fragment {
    private static final String TAG = ForecastFragment.class.getSimpleName();

    private static final String PREF_LOCATION_DEFAULT_VALUE = "location";
    public static final String DETAILS_EXTRAS = "weather";

    private static final int MY_PERMISSIONS_REQUEST_INTERNET = 1;
    public ArrayAdapter<String> mForecastAdapter;
    public ListView mListView;

    public ForecastFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        mForecastAdapter = new ArrayAdapter<>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textView, new ArrayList<String>());
        mListView = (ListView) rootView.findViewById(R.id.listView_forecast);
        mListView.setAdapter(mForecastAdapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Create an intent to start the Detail Activity for a list item.
                String forecast = (String) parent.getItemAtPosition(position);
                Intent intent = new Intent(getActivity(), DetailActivity.class);
                intent.putExtra(DETAILS_EXTRAS, forecast);
                startActivity(intent);
            }
        });

        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED) {
            updateWeather();
        } else {
            //Ask the user for internet permission.
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.READ_CONTACTS},
                    MY_PERMISSIONS_REQUEST_INTERNET);
        }

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.forecast_fragment, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {

        switch (menuItem.getItemId()) {
            case R.id.action_refresh:
                //Check whether it has the permission to use the internet connection.
                if (ContextCompat.checkSelfPermission(getActivity(),
                        Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED) {
                    updateWeather();
                } else {
                    //Ask the user for internet permission.
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[]{Manifest.permission.READ_CONTACTS},
                            MY_PERMISSIONS_REQUEST_INTERNET);
                }
                break;
        }
        return super.onOptionsItemSelected(menuItem);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_INTERNET: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    updateWeather();
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    // Temporary code - should be replaced.
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[]{Manifest.permission.READ_CONTACTS},
                            MY_PERMISSIONS_REQUEST_INTERNET);
                }
                return;
            }
        }
    }

    public void updateWeather() {
        //Make a check for internet connection before starting the task.
        ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();

        //Check if the internet permission is active.
        if (networkInfo != null && networkInfo.isConnected()) {
            //Get the user's shared preferences through the SharedPreferences file.
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
            //Read the user's preference value.
            String preference = preferences.getString(getString(R.string.pref_location_key), PREF_LOCATION_DEFAULT_VALUE);
            //Start the AsyncTask related to the weather fetching.
            new FetchWeatherTask().execute(preference);
        } else {
            Log.e(TAG, "Can't connect to the internet");
        }
    }

    class FetchWeatherTask extends AsyncTask<String, Void, String[]> {

        private String OWM_AUTHORITY = "api.openweathermap.org";
        private String OWM_LOCATION = "q";
        private String OWM_UNITS = "units";
        private String OWM_APP_ID = "appid";
        private String OWM_MODE = "mode";
        private String OWM_DAYS_COUNT = "cnt";

        private static final String TAG = "FetchWeatherTask";

        @Override
        protected String[] doInBackground(String... params) {
            HttpURLConnection conn = null;
            InputStream is;
            BufferedReader reader = null;
            String forecastJsonStr;
            String[] forecastArray = null;

            if (params[0] == null) {
                return null;
            }

            String postalCode = params[0];

            try {
                // Build a URL to access the OpenWeatherMap API with the following query parameters:
                //q=94043,us&units=metric&appid=b6fb1780ef33770bd276bea15e7ea414&mode=json&cnt=7
                Uri.Builder builder = new Uri.Builder();
                builder.scheme("http");
                builder.authority(OWM_AUTHORITY);
                builder.appendPath("data").appendPath("2.5").appendPath("forecast").appendPath("daily");
                builder.appendQueryParameter(OWM_LOCATION, postalCode);
                builder.appendQueryParameter(OWM_UNITS, getString(R.string.pref_temperature_units_default));
                builder.appendQueryParameter(OWM_APP_ID, "b6fb1780ef33770bd276bea15e7ea414");
                builder.appendQueryParameter(OWM_MODE, "json");
                builder.appendQueryParameter(OWM_DAYS_COUNT, "7");

                URL url = new URL(builder.build().toString());

                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.connect();

                is = conn.getInputStream();

                if (is == null) {
                    //Error handling
                    return null;
                }

                reader = new BufferedReader(new InputStreamReader(is));

                if (reader == null) {
                    //Error Handling
                    return null;
                }
                String line;
                StringBuffer buffer = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    //Only append the lines from the reader if they are not null, right to the end of the stream.
                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    //Error handling
                    return null;
                }
                forecastJsonStr = buffer.toString();
                try {
                    WeatherDataParser parser = new WeatherDataParser();
                    //Get the user's shared preferences
                    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    //Get the temperature unit
                    String temperatureUnits = preferences.getString(getString(R.string.pref_temperature_units_key), getString(R.string.pref_temperature_units_default));
                    //Parse the data based on the temperature unit
                    forecastArray = parser.getWeatherDataFromJsonString(forecastJsonStr, temperatureUnits);
                } catch (JSONException e) {
                    Log.e(TAG, "Error on JSON parsing:", e);
                }

            } catch (Exception e) {
                Log.e(TAG, "Error: ", e);

                return null;

            } finally {
                if (conn != null) {
                    conn.disconnect();
                }

                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        Log.e(TAG, "Error closing the stream: ", e);
                    }
                }
            }
            return forecastArray;
        }

        @Override
        protected void onPostExecute(String[] strings) {
            super.onPostExecute(strings);
            if (strings != null) {
                mForecastAdapter.clear();
                mForecastAdapter.addAll(Arrays.asList(strings));
            }
        }
    }
}


text:
require "googleauth"

module Google
  module Cloud
    module Vision
      ##
      # # Credentials
      #
      # Represents the authentication and authorization used to connect to the
      # Vision API.
      #
      # @example
      #   require "google/cloud/vision"
      #
      #   keyfile = "/path/to/keyfile.json"
      #   creds = Google::Cloud::Vision::Credentials.new keyfile
      #
      #   vision = Google::Cloud::Vision.new(
      #     project_id: "my-project",
      #     credentials: creds
      #   )
      #
      #   vision.project_id #=> "my-project"
      #
      class Credentials < Google::Auth::Credentials
        SCOPE = ["https://www.googleapis.com/auth/cloud-platform"].freeze
        PATH_ENV_VARS = %w[VISION_CREDENTIALS
                           VISION_KEYFILE
                           GOOGLE_CLOUD_CREDENTIALS
                           GOOGLE_CLOUD_KEYFILE
                           GCLOUD_KEYFILE].freeze
        JSON_ENV_VARS = %w[VISION_CREDENTIALS_JSON
                           VISION_KEYFILE_JSON
                           GOOGLE_CLOUD_CREDENTIALS_JSON
                           GOOGLE_CLOUD_KEYFILE_JSON
                           GCLOUD_KEYFILE_JSON].freeze
        DEFAULT_PATHS = \
          ["~/.config/gcloud/application_default_credentials.json"].freeze
      end
    end
  end
end