text:
using namespace std;
using Eigen::MatrixXd;
using Eigen::VectorXd;
using std::vector;

void CheckArguments(int argc, char* argv[]);
void ReadMeasurements(string in_file_name, vector<MeasurementPackage> &measurement_pack_list,
                       vector<GroundTruthPackage>& gt_pack_list);
void CheckFiles(const string& in_name, const string& out_name);
void TestUkf(const string& in_file_name, const string& out_file_name);
void RunUkf(const vector<MeasurementPackage>& measurement_pack_list,
            const vector<GroundTruthPackage>& gt_pack_list,
            const string& out_file_name);

void RunUkfWithFileOutputOptimizedForPythonAndSimulatorVisualization(const vector<MeasurementPackage>& measurement_pack_list,
            const vector<GroundTruthPackage>& gt_pack_list,
            const string& out_file_name);

using namespace std;

int main(int argc, char* argv[]) {
  //check validity of arguments
  CheckArguments(argc, argv);

  string in_file_name = argv[1];
  string out_file_name = argv[2];
  //validate files existence
  CheckFiles(in_file_name, out_file_name);

  TestUkf(in_file_name, out_file_name);

	return 0;
}

void TestUkf(const string& in_file_name, const string& out_file_name) {
  vector<MeasurementPackage> measurement_pack_list;
  vector<GroundTruthPackage> gt_pack_list;
  ReadMeasurements(in_file_name, measurement_pack_list, gt_pack_list);

  RunUkf(measurement_pack_list, gt_pack_list, out_file_name);
}

void RunUkf(const vector<MeasurementPackage>& measurement_pack_list,
            const vector<GroundTruthPackage>& gt_pack_list,
            const string& out_file_name) {

  ofstream out_file(out_file_name, ofstream::out);
  if (!out_file.is_open()) {
    std::cerr << "Error opening file: " << out_file_name << std::endl;
    exit(EXIT_FAILURE);
  }

  // column names for output file
  out_file << "time_stamp" << "\t";
  out_file << "px_state" << "\t";
  out_file << "py_state" << "\t";
  out_file << "v_state" << "\t";
  out_file << "yaw_angle_state" << "\t";
  out_file << "yaw_rate_state" << "\t";
  out_file << "sensor_type" << "\t";
  out_file << "NIS" << "\t";
  out_file << "px_measured" << "\t";
  out_file << "py_measured" << "\t";
  out_file << "px_ground_truth" << "\t";
  out_file << "py_ground_truth" << "\t";
  out_file << "vx_ground_truth" << "\t";
  out_file << "vy_ground_truth" << "\n";

  // Create a UKF instance
  UKF ukf;

  // used to compute the RMSE later
  vector<VectorXd> estimations;
  vector<VectorXd> ground_truth;

  //Call the UKF-based fusion
  size_t N = measurement_pack_list.size();
  for (size_t k = 0; k < N; ++k) {
    //check to see if this sensor type is enabled
    if(!ukf.IsSensorEnabled(measurement_pack_list[k].sensor_type_)) {
      continue;
    }

    // start filtering from the second frame (the speed is unknown in the first
    // frame)
    ukf.ProcessMeasurement(measurement_pack_list[k]);

    // timestamp
    out_file << measurement_pack_list[k].timestamp_ << "\t"; // pos1 - est

    // output the estimation
    VectorXd x = ukf.GetMeanState();
    out_file << x(0) << "\t"; //px
    out_file << x(1) << "\t"; //py
    out_file << x(2) << "\t"; //speed
    out_file << x(3) << "\t"; //yaw
    out_file << x(4) << "\t"; //yaw_rate

    // output the measurements
    if (measurement_pack_list[k].sensor_type_ == MeasurementPackage::LASER) {
      // sensor type
      out_file << "lidar" << "\t";
      // NIS value
      out_file << ukf.GetLaserNIS() << "\t";

      // output the estimation
      out_file << measurement_pack_list[k].raw_measurements_(0) << "\t"; //p1_meas
      out_file << measurement_pack_list[k].raw_measurements_(1) << "\t"; //p2_meas

    } else if (measurement_pack_list[k].sensor_type_ == MeasurementPackage::RADAR) {
      // sensor type
      out_file << "radar" << "\t";

      // NIS value
      out_file << ukf.GetRadarNIS() << "\t";

      // output the estimation in the cartesian coordinates
      float ro = measurement_pack_list[k].raw_measurements_(0);
      float phi = measurement_pack_list[k].raw_measurements_(1);
      out_file << ro * cos(phi) << "\t"; // p1_meas
      out_file << ro * sin(phi) << "\t"; // ps_meas
    }

    // output the ground truth packages
    out_file << gt_pack_list[k].gt_values_(0) << "\t"; //p1
    out_file << gt_pack_list[k].gt_values_(1) << "\t"; //p2
    out_file << gt_pack_list[k].gt_values_(2) << "\t"; //vx
    out_file << gt_pack_list[k].gt_values_(3) << "\n"; //vy

    // convert ukf x vector to cartesian to compare to ground truth
    VectorXd ukf_x_cartesian_ = VectorXd(4);

    x = ukf.GetMeanState();
    float x_estimate_ = x(0);
    float y_estimate_ = x(1);
    float vx_estimate_ = x(2) * cos(x(3));
    float vy_estimate_ = x(2) * sin(x(3));

    ukf_x_cartesian_ << x_estimate_, y_estimate_, vx_estimate_, vy_estimate_;

    estimations.push_back(ukf_x_cartesian_);
    ground_truth.push_back(gt_pack_list[k].gt_values_);
  }

  // compute the accuracy (RMSE)
  cout << "RMSE" << endl << Tools::CalculateRMSE(estimations, ground_truth) << endl;

  if (out_file.is_open()) {
    out_file.close();
  }
}

void RunUkfWithFileOutputOptimizedForPythonAndSimulatorVisualization(const vector<MeasurementPackage>& measurement_pack_list,
            const vector<GroundTruthPackage>& gt_pack_list,
            const string& out_file_name) {

  ofstream out_file(out_file_name, ofstream::out);
  if (!out_file.is_open()) {
    std::cerr << "Error opening file: " << out_file_name << std::endl;
    exit(EXIT_FAILURE);
  }

  // Create a UKF instance
  UKF ukf;

  // used to compute the RMSE later
  vector<VectorXd> estimations;
  vector<VectorXd> ground_truth;

  //Call the UKF-based fusion
  size_t N = measurement_pack_list.size();
  for (size_t k = 0; k < N; ++k) {
    // start filtering from the second frame (the speed is unknown in the first
    // frame)
    ukf.ProcessMeasurement(measurement_pack_list[k]);

    // output the estimation
    VectorXd x = ukf.GetMeanState();
    out_file << x(0) << "\t"; //px
    out_file << x(1) << "\t"; //py
    out_file << x(2) << "\t"; //speed
    out_file << x(3) << "\t"; //yaw
    out_file << x(4) << "\t"; //yaw_rate

    double NIS_laser = 0;
    double NIS_radar = 0;

    // output the measurements
    if (measurement_pack_list[k].sensor_type_ == MeasurementPackage::LASER) {
      // NIS value
      NIS_laser = ukf.GetLaserNIS();

      // output the estimation
      out_file << measurement_pack_list[k].raw_measurements_(0) << "\t"; //p1_meas
      out_file << measurement_pack_list[k].raw_measurements_(1) << "\t"; //p2_meas

    } else if (measurement_pack_list[k].sensor_type_ == MeasurementPackage::RADAR) {
      // NIS value
      NIS_radar = ukf.GetRadarNIS();

      // output the estimation in the cartesian coordinates
      float ro = measurement_pack_list[k].raw_measurements_(0);
      float phi = measurement_pack_list[k].raw_measurements_(1);
      out_file << ro * cos(phi) << "\t"; // p1_meas
      out_file << ro * sin(phi) << "\t"; // ps_meas
    }

    // output the ground truth packages
    out_file << gt_pack_list[k].gt_values_(0) << "\t"; //p1
    out_file << gt_pack_list[k].gt_values_(1) << "\t"; //p2
    out_file << gt_pack_list[k].gt_values_(2) << "\t"; //vx
    out_file << gt_pack_list[k].gt_values_(3) << "\t"; //vy

    out_file << NIS_laser << "\t";
    out_file << NIS_radar << "\n";

    // convert ukf x vector to cartesian to compare to ground truth
    VectorXd ukf_x_cartesian_ = VectorXd(4);

    x = ukf.GetMeanState();
    float x_estimate_ = x(0);
    float y_estimate_ = x(1);
    float vx_estimate_ = x(2) * cos(x(3));
    float vy_estimate_ = x(2) * sin(x(3));

    ukf_x_cartesian_ << x_estimate_, y_estimate_, vx_estimate_, vy_estimate_;

    estimations.push_back(ukf_x_cartesian_);
    ground_truth.push_back(gt_pack_list[k].gt_values_);
  }

  // compute the accuracy (RMSE)
  cout << "RMSE" << endl << Tools::CalculateRMSE(estimations, ground_truth) << endl;

  if (out_file.is_open()) {
    out_file.close();
  }
}

void ReadMeasurements(string in_file_name, vector<MeasurementPackage> &measurement_pack_list,
                       vector<GroundTruthPackage>& gt_pack_list) {
  ifstream in_file(in_file_name.c_str(), ifstream::in);

  if (!in_file.is_open()) {
    std::cerr << "Can not open file: " << in_file_name << std::endl;
    exit(EXIT_FAILURE);
  }

  // prep the measurement packages (each line represents a measurement at a
  // timestamp)
  string line;
  while (getline(in_file, line) && !in_file.eof()) {

    string sensor_type;
    MeasurementPackage meas_package;
    GroundTruthPackage gt_package;
    istringstream iss(line);
    long timestamp;

    // reads first element from the current line
    iss >> sensor_type;
    if (sensor_type.compare("L") == 0) {
      // LASER MEASUREMENT

      // read measurements at this timestamp
      meas_package.sensor_type_ = MeasurementPackage::LASER;
      meas_package.raw_measurements_ = VectorXd(2);
      float x;
      float y;
      iss >> x;
      iss >> y;
      meas_package.raw_measurements_ << x, y;
      iss >> timestamp;
      meas_package.timestamp_ = timestamp;
      measurement_pack_list.push_back(meas_package);
    } else if (sensor_type.compare("R") == 0) {
      // RADAR MEASUREMENT
      // read measurements at this timestamp
      meas_package.sensor_type_ = MeasurementPackage::RADAR;
      meas_package.raw_measurements_ = VectorXd(3);
      float ro;
      float phi;
      float ro_dot;
      iss >> ro;
      iss >> phi;
      iss >> ro_dot;
      meas_package.raw_measurements_ << ro, phi, ro_dot;
      iss >> timestamp;
      meas_package.timestamp_ = timestamp;
      measurement_pack_list.push_back(meas_package);
    }

    // read ground truth data to compare later
    float x_gt;
    float y_gt;
    float vx_gt;
    float vy_gt;
    iss >> x_gt;
    iss >> y_gt;
    iss >> vx_gt;
    iss >> vy_gt;
    gt_package.gt_values_ = VectorXd(4);
    gt_package.gt_values_ << x_gt, y_gt, vx_gt, vy_gt;
    gt_pack_list.push_back(gt_package);
  }

  if (in_file.is_open()) {
    in_file.close();
  }
}

void CheckArguments(int argc, char* argv[]) {
  string usage_instructions = "Usage instructions: ";
  usage_instructions += argv[0];
  usage_instructions += " path/to/input.txt output.txt";

  bool has_valid_args = false;

  // make sure the user has provided input and output files
  if (argc == 1) {
    cerr << usage_instructions << endl;
  } else if (argc == 2) {
    cerr << "Please include an output file.\n" << usage_instructions << endl;
  } else if (argc == 3) {
    has_valid_args = true;
  } else if (argc > 3) {
    cerr << "Too many arguments.\n" << usage_instructions << endl;
  }

  if (!has_valid_args) {
    exit(EXIT_FAILURE);
  }
}

void CheckFiles(const string& in_name, const string& out_name) {
  ifstream in_file(in_name.c_str(), ifstream::in);

  if (!in_file.is_open()) {
    cerr << "Cannot open input file: " << in_name << endl;
    exit(EXIT_FAILURE);
  }
  in_file.close();

  ofstream out_file(out_name.c_str(), ofstream::out);
  if (!out_file.is_open()) {
    cerr << "Cannot open output file: " << out_name << endl;
    exit(EXIT_FAILURE);
  }
  out_file.close();
}

redpajama_set_name: RedPajamaGithub


text:
package cz.znj.kvr.sw.exp.java.concurrencyexp.primitives.scheduled;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * Created by rat on 2015-09-20.
 */
public class ScheduledExecutor
{
	public static void		main(String[] args)
	{
		System.exit(new ScheduledExecutor().run(args));
	}

	public int			run(String[] args)
	{
		ScheduledExecutorService executor = Executors.newScheduledThreadPool(4);
		ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
			System.out.println("hello");
		}, 0, 100, TimeUnit.MILLISECONDS);
		new Thread(() -> {
			try {
				Thread.sleep(550);
				future.cancel(true);
			}
			catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
		}).start();
		try {
			future.get();
			throw new IllegalStateException();
		}
		catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
		catch (ExecutionException e) {
			throw new RuntimeException(e);
		}
		catch (CancellationException e) {
			// ok
		}
		System.out.println("ok, done");
		return 0;
	}
}


text:
#ifndef MG811_H
#define MG811_H

#include <stdint.h>

#define DC_GAIN (8.5)   // DC gain of the amplifier

/* Software Related Macros */
#define		READ_SAMPLE_INTERVAL		(10)    // number of samples
#define		READ_SAMPLE_TIMES			(1)     // time interval between samples

/* Application Related Macros */
/* These two values differ from sensor to sensor. User should derermine this value. */
#define		ZERO_POINT_VOLTAGE		(0.220) 	// sensor output in volts when the concentration of CO2 is 400PPM
#define		REACTION_VOLTGAE		(0.020) 	// voltage drop of the sensor when moving it into 1000ppm medium

/* Gas characteristic */
extern float CO2Curve[3];

void initMG811(void);
float MG811_ReadVolts(void);
uint32_t MG811_ReadPPM(float volts, float * pcurve);

#endif


text:
package net.collaud.fablab.manager.audit;

import lombok.extern.slf4j.Slf4j;
import net.collaud.fablab.manager.data.*;
import net.collaud.fablab.manager.data.type.AuditAction;
import net.collaud.fablab.manager.data.type.AuditObject;
import net.collaud.fablab.manager.data.type.LoginResult;
import net.collaud.fablab.manager.exceptions.FablabException;
import net.collaud.fablab.manager.service.AuditService;
import net.collaud.fablab.manager.service.SecurityService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author Gaetan Collaud <gaetancollaud@gmail.com>
 */
@Aspect
@Slf4j
@Component
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class AuditAspect {

	@Autowired
	private AuditService auditService;

	@Autowired
	private SecurityService securityService;

	//	@Around("@within(net.collaud.fablab.manager.audit.Audit) || @annotation(net.collaud.fablab.manager.audit.Audit)")
//	@Around("@annotation(net.collaud.fablab.manager.audit.Audit)")
	@Around("execution(* net.collaud.fablab.manager.service.*.*(..))")
	public Object serviceAction(ProceedingJoinPoint pjp) throws Throwable {
		final Method method = ((MethodSignature) pjp.getSignature()).getMethod();
		if (method.isAnnotationPresent(Audit.class)) {
			// perform the monitoring actions
			return aroudAudit(pjp, method);
		}
		return pjp.proceed();
	}

	protected Object aroudAudit(ProceedingJoinPoint pjp, Method method) throws Throwable {
		LOG.info("Intercepted method " + method.getName());
		Audit ann = method.getAnnotation(Audit.class);
		try {
			Object result = pjp.proceed();
			try {
				Object object = getObjectOutOfResultAndParameters(ann, result, pjp.getArgs());
				Long id = getIdOfObject(object);
				addEntry(ann.action(), ann.object(), id, true, getReadableMessage(ann.object(), ann.action(), object, pjp.getArgs()), null);
			} catch (Exception ex) {
				LOG.error("Cannot add login for themod " + method.getName(), ex);
			}
			return result;
		} catch (Exception ex) {
			Object entity = getObjectOutOfResultAndParameters(ann, null, pjp.getArgs());
			Long id = getIdOfObject(entity);
			addEntry(ann.action(), ann.object(), id, true, "Error while " + ann.action() + " " + ann.object() + " with id  " + id, ex.getMessage());
			throw ex;
		}
	}

	private void addEntry(AuditAction action, AuditObject object, Long objectId, boolean success, String content, String detail) throws FablabException {
		if (detail != null && detail.isEmpty()) {
			detail = null;
		}
		auditService.addEntry(new AuditEO(securityService.getCurrentUser().orElse(null), action, object, objectId, new Date(), success, content, detail));
	}

	private Object getObjectOutOfResultAndParameters(Audit ann, Object result, Object[] parameters) {
		if (ann.action().equals(AuditAction.INSERT)
				|| ann.action().equals(AuditAction.UPDATE)) {
			if (result instanceof AbstractDataEO) {
				return (AbstractDataEO) result;
			}
		} else if (ann.action().equals(AuditAction.DELETE)) {
			//take the first parameter
			if (parameters.length > 0 && parameters[0] instanceof AbstractDataEO) {
				return (AbstractDataEO) parameters[0];
			}
		}
		if (result != null) {
			return result;
		}
		return null;
	}

	private Long getIdOfObject(Object entity) {
		if (entity instanceof AbstractDataEO) {
			return (Long) ((AbstractDataEO) entity).getId();
		}
		return null;
	}

	private String getReadableMessage(AuditObject obj, AuditAction action, Object res, Object[] args) {
		switch (obj) {
			case USAGE:
				return getReadableMessage(action, (UsageEO) res);
			case PAYMENT:
				return getReadableMessage(action, (PaymentEO) res);
			case USER:
				return getReadableMessage(action, (UserEO) res);
			case SECURITY:
				return getReadableMessageForSecurity(action, res, args);
//			case ACCESS_DOOR:
//				return getReadableMessage(action, (AccessDoorResponse) res);
			case SUBSCRIPTION:
				return getReadableMessage(action, (SubscriptionEO) res);
			case MACHINE:
				return getReadableMessage(action, (MachineEO) res);
			case ASSET:
				return getReadableMessage(action, (AssetEO) res);
			default:
				return "ERROR object " + obj + " not implemented yet";
		}
	}

	//FIXME take care of action
	private String getReadableMessage(AuditAction action, UsageEO usage) {
		StringBuilder sb = new StringBuilder();
		sb.append(usage.getUser().getFirstLastName());
		sb.append(" used the asset ");
		sb.append(usage.getMachine().getName());
		sb.append(" for ");
		sb.append(usage.getAmount()).append(usage.getUnit().getTextUnit());
		sb.append(" with ");
		if (usage.getAdditionalCost() == 0) {
			sb.append("no additional cost");
		} else {
			sb.append(usage.getAdditionalCost()).append("CHF of additional cost");
		}
		return sb.toString();
	}

	//FIXME take care of action
	private String getReadableMessage(AuditAction action, PaymentEO payment) {
		StringBuilder sb = new StringBuilder();
		if (action == AuditAction.INSERT) {
			sb.append(payment.getUser().getFirstLastName());
			sb.append(" paid ");
			sb.append(payment.getTotal());
			sb.append("CHF ");
		} else if (action == AuditAction.DELETE) {
			sb.append("Payment of ");
			sb.append(payment.getTotal());
			sb.append(" by ");
			sb.append(payment.getUser().getFirstLastName());
			sb.append(" was removed");
		}
		return sb.toString();
	}

	private String getReadableMessage(AuditAction action, UserEO user) {
		StringBuilder sb = new StringBuilder();
		sb.append("User ");
		sb.append(user.getEmail());
		switch (action) {
			case INSERT:
				sb.append(" inserted : ");
				break;
			case UPDATE:
				sb.append(" edited : ");
				break;
			case DELETE:
				sb.append(" deleted : ");
				break;
		}
		sb.append("firstname=");
		sb.append(user.getFirstname());
		sb.append(" lastname=");
		sb.append(user.getLastname());
		sb.append(" rfid=");
		sb.append(user.getRfid());
		sb.append(" authMachine=[");
		sb.deleteCharAt(sb.length() - 1);//remove last coma
		sb.append("]");
		return sb.toString();
	}

	private String getReadableMessageForSecurity(AuditAction action, Object result, Object[] args) {
		StringBuilder sb = new StringBuilder();
		if (action == AuditAction.LOGIN) {
			sb.append("Login result=");
			LoginResult res = (LoginResult) result;
			sb.append(res);
		} else if (action == AuditAction.LOGOUT) {
			sb.append("Logout");
		} else {
			sb.append("Unknown security action : ").append(action);
		}
		return sb.toString();
	}

	//	private String getReadableMessage(AuditAction action, AccessDoorResponse res) {
//		StringBuilder sb = new StringBuilder();
//		if (res.getUser() != null) {
//			sb.append("User ");
//			sb.append(res.getUser().getFirstLastName());
//		} else {
//			sb.append("Unknown ");
//			sb.append(res.getRfid());
//		}
//		if (res.isGranted()) {
//			sb.append(" oppened the door");
//		} else {
//			sb.append(" could not open the door");
//		}
//		return sb.toString();
//	}
	private String getReadableMessage(AuditAction action, SubscriptionEO subscription) {
		StringBuilder sb = new StringBuilder();
		sb.append("User ");
		sb.append(subscription.getUser().getEmail());
		sb.append(" confirmed his asset");
		return sb.toString();
	}

	private String getReadableMessage(AuditAction action, MachineEO machine) {
		StringBuilder sb = new StringBuilder();
		sb.append("Machine name=");
		sb.append(machine.getName());
		sb.append(" intro=");
		sb.append(machine.getIntroduction());
		return sb.toString();
	}

	private String getReadableMessage(AuditAction action, AssetEO asset) {
		StringBuilder sb = new StringBuilder();
		sb.append("Asset title=");
		sb.append(asset.getTitle());
		sb.append(" mime=");
		sb.append(asset.getMime());
		sb.append(" size=");
		sb.append(asset.getSize());
		return sb.toString();
	}

}


text:
from __future__ import absolute_import

from . import Filter

__all__ = ('CSSSlimmer',)

class Slimmer(Filter):

    def setup(self):
        super(Slimmer, self).setup()
        import slimmer
        self.slimmer = slimmer

class CSSSlimmer(Slimmer):
    """Minifies CSS by removing whitespace, comments etc., using the Python
    `slimmer <http://pypi.python.org/pypi/slimmer/>`_ library.
    """

    name = 'css_slimmer'

    def output(self, _in, out, **kw):
        out.write(self.slimmer.css_slimmer(_in.read()))


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/device_swipe_refresh_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.soxfmr.realtemp.ui.DeviceActivity">

    <ListView
        android:id="@+id/device_listview_device"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.v4.widget.SwipeRefreshLayout>


text:
package io.apicurio.hub.core.auth.impl;

import io.apicurio.hub.core.auth.IAuthorizationService;
import io.apicurio.hub.core.config.HubConfiguration;
import io.apicurio.hub.core.storage.IStorage;
import io.apicurio.hub.core.storage.StorageException;
import io.apicurio.studio.shared.beans.StudioRole;
import io.apicurio.studio.shared.beans.User;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Default;
import javax.inject.Inject;

@ApplicationScoped
@Default
public class AuthorizationService implements IAuthorizationService {

    @Inject
    private HubConfiguration config;
    @Inject
    private IStorage storage;

    /**
     * @see IAuthorizationService#hasWriteAllPermission(User)
     */
    @Override
    public boolean hasWriteAllPermission(User user) {
        return config.isShareForEveryone();
    }

    /**
     * @see IAuthorizationService#hasWritePermission(User, String)
     */
    @Override
    public boolean hasWritePermission(User user, String designId) throws StorageException {
        return hasWriteAllPermission(user)
                || hasPersonalWritePermission(user, designId);
    }

    /**
     * @see IAuthorizationService#hasPersonalWritePermission(User, String)
     */
    @Override
    public boolean hasPersonalWritePermission(User user, String designId) throws StorageException {
        return this.storage.hasWritePermission(user.getLogin(), designId);
    }

    /**
     * @see IAuthorizationService#hasOwnerPermission(User, String)
     */
    @Override
    public boolean hasOwnerPermission(User user, String designId) throws StorageException {
        return hasPersonalOwnerPermission(user, designId);
    }

    /**
     * @see IAuthorizationService#hasPersonalOwnerPermission(User, String)
     */
    @Override
    public boolean hasPersonalOwnerPermission(User user, String designId) throws StorageException {
        return this.storage.hasOwnerPermission(user.getLogin(), designId);
    }

    /**
     * @see IAuthorizationService#hasTemplateCreationPermission(User)
     */
    @Override
    public boolean hasTemplateCreationPermission(User user) {
        return user.hasRole(StudioRole.APICURIO_ADMIN);
    }
}


text:
package com.amazonaws.adapters.types;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import com.amazonaws.SdkClientException;
import com.amazonaws.annotation.SdkProtectedApi;
import com.amazonaws.util.StringInputStream;

@SdkProtectedApi
public class StringToInputStreamAdapter implements TypeAdapter<String, InputStream> {

    @Override
    public InputStream adapt(String source) {
        if (source == null) {
            return null;
        }
        try {
            return new StringInputStream(source);
        } catch (UnsupportedEncodingException e) {
            throw new SdkClientException(e);
        }
    }
}


text:
"""Some tools for working with MongoDB server versions."""

class Version(tuple):

    def __new__(cls, *version):
        padded_version = cls._padded(version, 4)
        return super(Version, cls).__new__(cls, tuple(padded_version))

    @classmethod
    def _padded(cls, iter, length, padding=0):
        l = list(iter)
        if len(l) < length:
            for _ in range(length - len(l)):
                l.append(padding)
        return l

    @classmethod
    def from_string(cls, version_string):
        mod = 0
        bump_patch_level = False
        if version_string.endswith("+"):
            version_string = version_string[0:-1]
            mod = 1
        elif version_string.endswith("-pre-"):
            version_string = version_string[0:-5]
            mod = -1
        elif version_string.endswith("-"):
            version_string = version_string[0:-1]
            mod = -1
        # Deal with '-rcX' substrings
        if '-rc' in version_string:
            version_string = version_string[0:version_string.find('-rc')]
            mod = -1
        # Deal with git describe generated substrings
        elif '-' in version_string:
            version_string = version_string[0:version_string.find('-')]
            mod = -1
            bump_patch_level = True

        version = [int(part) for part in version_string.split(".")]
        version = cls._padded(version, 3)
        # Make from_string and from_version_array agree. For example:
        # MongoDB Enterprise > db.runCommand('buildInfo').versionArray
        # [ 3, 2, 1, -100 ]
        # MongoDB Enterprise > db.runCommand('buildInfo').version
        # 3.2.0-97-g1ef94fe
        if bump_patch_level:
            version[-1] += 1
        version.append(mod)

        return Version(*version)

    @classmethod
    def from_version_array(cls, version_array):
        version = list(version_array)
        if version[-1] < 0:
            version[-1] = -1
        version = cls._padded(version, 3)
        return Version(*version)

    @classmethod
    def from_client(cls, client):
        info = client.server_info()
        if 'versionArray' in info:
            return cls.from_version_array(info['versionArray'])
        return cls.from_string(info['version'])

    def at_least(self, *other_version):
        return self >= Version(*other_version)

    def __str__(self):
        return ".".join(map(str, self))


text:
package space.dotcat.assistant.content.webSocketModel;

import com.google.gson.annotations.SerializedName;

public class SubscribeBody {

    @SerializedName("target_topic")
    private String targetTopic;

    @SerializedName("retain_messages")
    private boolean messagesRetained;

    public SubscribeBody(String targetTopic, boolean messagesRetained) {
        this.targetTopic = targetTopic;

        this.messagesRetained = messagesRetained;
    }

    public String getTargetTopic() {
        return targetTopic;
    }

    public void setTargetTopic(String targetTopic) {
        this.targetTopic = targetTopic;
    }

    public boolean isMessagesRetained() {
        return messagesRetained;
    }

    public void setMessagesRetained(boolean messagesRetained) {
        this.messagesRetained = messagesRetained;
    }
}