// The libMesh Finite Element Library.
// Copyright (C) 2002-2020 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// Local includes
#include "libmesh/edge_edge4.h"
#include "libmesh/enum_io_package.h"
#include "libmesh/enum_order.h"

namespace libMesh
{

// Edge4 class static member initializations
const int Edge4::num_nodes;
const int Edge4::num_sides;
const int Edge4::num_edges;
const int Edge4::num_children;
const int Edge4::nodes_per_side;
const int Edge4::nodes_per_edge;

#ifdef LIBMESH_ENABLE_AMR

const float Edge4::_embedding_matrix[Edge4::num_children][Edge4::num_nodes][Edge4::num_nodes] =
  {
    // embedding matrix for child 0

    {
      // 0       1       2        3        // Shape function index
      {1.0,      0.0,    0.0,     0.0},    // left,  xi = -1
      {-0.0625, -0.0625, 0.5625,  0.5625}, // right, xi = 0
      {0.3125,   0.0625, 0.9375, -0.3125}, // middle left,  xi = -2/3
      {0.0,      0.0,    1.0,     0.0}     // middle right, xi = -1/3
    },

    // embedding matrix for child 1
    {
      // 0       1        2        3        // Shape function index
      {-0.0625, -0.0625,  0.5625,  0.5625}, // left,  xi = 0
      {0.0,      1.0,     0.0,     0.0},    // right, xi = 1
      {0.0,      0.0,     0.0,     1.0},    // middle left,  xi = 1/3
      {0.0625,   0.3125, -0.3125,  0.9375}  // middle right, xi = 2/3
    }
  };

#endif

bool Edge4::is_vertex(const unsigned int i) const
{
  return (i==0) || (i==1);
}

bool Edge4::is_edge(const unsigned int i) const
{
  return (i==2) || (i==3);
}

bool Edge4::is_face(const unsigned int ) const
{
  return false;
}

bool Edge4::is_node_on_side(const unsigned int n,
                            const unsigned int s) const
{
  libmesh_assert_less (s, 2);
  libmesh_assert_less (n, Edge4::num_nodes);
  return (s == n);
}

bool Edge4::is_node_on_edge(const unsigned int,
                            const unsigned int libmesh_dbg_var(e)) const
{
  libmesh_assert_equal_to (e, 0);
  return true;
}

bool Edge4::has_affine_map() const
{
  if (!this->point(2).relative_fuzzy_equals
      ((this->point(0)*2. + this->point(1))/3.))
    return false;
  if (!this->point(3).relative_fuzzy_equals
      ((this->point(0) + this->point(1)*2.)/3.))
    return false;
  return true;
}

Order Edge4::default_order() const
{
  return THIRD;
}

void Edge4::connectivity(const unsigned int sc,
                         const IOPackage iop,
                         std::vector<dof_id_type> & conn) const
{
  libmesh_assert_less_equal (sc, 2);
  libmesh_assert_less (sc, this->n_sub_elem());
  libmesh_assert_not_equal_to (iop, INVALID_IO_PACKAGE);

  // Create storage
  conn.resize(2);

  switch(iop)
    {
    case TECPLOT:
      {
        switch (sc)
          {
          case 0:
            conn[0] = this->node_id(0)+1;
            conn[1] = this->node_id(2)+1;
            return;

          case 1:
            conn[0] = this->node_id(2)+1;
            conn[1] = this->node_id(3)+1;
            return;

          case 2:
            conn[0] = this->node_id(3)+1;
            conn[1] = this->node_id(1)+1;
            return;

          default:
            libmesh_error_msg("Invalid sc = " << sc);
          }

      }

    case VTK:
      {

        switch (sc)
          {
          case 0:
            conn[0] = this->node_id(0);
            conn[1] = this->node_id(2);
            return;

          case 1:
            conn[0] = this->node_id(2);
            conn[1] = this->node_id(3);
            return;

          case 2:
            conn[0] = this->node_id(3);
            conn[1] = this->node_id(1);
            return;

          default:
            libmesh_error_msg("Invalid sc = " << sc);
          }
      }

    default:
      libmesh_error_msg("Unsupported IO package " << iop);
    }
}

BoundingBox Edge4::loose_bounding_box () const
{
  // This might be a curved line through 2-space or 3-space, in which
  // case the full bounding box can be larger than the bounding box of
  // just the nodes.
  //
  // FIXME - I haven't yet proven the formula below to be correct for
  // cubics - RHS
  Point pmin, pmax;

  for (unsigned d=0; d<LIBMESH_DIM; ++d)
    {
      Real center = (this->point(2)(d) + this->point(3)(d))/2;
      Real hd = std::max(std::abs(center - this->point(0)(d)),
                         std::abs(center - this->point(1)(d)));

      pmin(d) = center - hd;
      pmax(d) = center + hd;
    }

  return BoundingBox(pmin, pmax);
}

dof_id_type Edge4::key () const
{
  return this->compute_key(this->node_id(0),
                           this->node_id(1),
                           this->node_id(2),
                           this->node_id(3));
}

Real Edge4::volume () const
{
  // Make copies of our points.  It makes the subsequent calculations a bit
  // shorter and avoids dereferencing the same pointer multiple times.
  Point
    x0 = point(0),
    x1 = point(1),
    x2 = point(2),
    x3 = point(3);

  // Construct constant data vectors.
  // \vec{x}_{\xi}  = \vec{a1}*xi**2 + \vec{b1}*xi + \vec{c1}
  // This is copy-pasted directly from the output of a Python script.
  Point
    a1 = -27*x0/16 + 27*x1/16 + 81*x2/16 - 81*x3/16,
    b1 = 9*x0/8 + 9*x1/8 - 9*x2/8 - 9*x3/8,
    c1 = x0/16 - x1/16 - 27*x2/16 + 27*x3/16;

  // 4 point quadrature, 7th-order accurate
  const unsigned int N = 4;
  const Real q[N] = {-std::sqrt(525 + 70*std::sqrt(30.)) / 35,
                     -std::sqrt(525 - 70*std::sqrt(30.)) / 35,
                     std::sqrt(525 - 70*std::sqrt(30.)) / 35,
                     std::sqrt(525 + 70*std::sqrt(30.)) / 35};
  const Real w[N] = {(18 - std::sqrt(30.)) / 36,
                     (18 + std::sqrt(30.)) / 36,
                     (18 + std::sqrt(30.)) / 36,
                     (18 - std::sqrt(30.)) / 36};

  Real vol=0.;
  for (unsigned int i=0; i<N; ++i)
    vol += w[i] * (q[i]*q[i]*a1 + q[i]*b1 + c1).norm();

  return vol;
}

} // namespace libMesh

{'repo_name': 'libMesh/libmesh', 'stars': '398', 'repo_language': 'C', 'file_name': 'libmesh_citations.py', 'mime_type': 'text/x-python', 'hash': 8465851560417462944, 'source_dataset': 'data'}


// SPDX-License-Identifier: GPL-2.0-only
/*
 * drivers/regulator/ab3100.c
 *
 * Copyright (C) 2008-2009 ST-Ericsson AB
 * Low-level control of the AB3100 IC Low Dropout (LDO)
 * regulators, external regulator and buck converter
 * Author: Mattias Wallin <mattias.wallin@stericsson.com>
 * Author: Linus Walleij <linus.walleij@stericsson.com>
 */

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/regulator/driver.h>
#include <linux/mfd/ab3100.h>
#include <linux/mfd/abx500.h>
#include <linux/of.h>
#include <linux/regulator/of_regulator.h>

/* LDO registers and some handy masking definitions for AB3100 */
#define AB3100_LDO_A		0x40
#define AB3100_LDO_C		0x41
#define AB3100_LDO_D		0x42
#define AB3100_LDO_E		0x43
#define AB3100_LDO_E_SLEEP	0x44
#define AB3100_LDO_F		0x45
#define AB3100_LDO_G		0x46
#define AB3100_LDO_H		0x47
#define AB3100_LDO_H_SLEEP_MODE	0
#define AB3100_LDO_H_SLEEP_EN	2
#define AB3100_LDO_ON		4
#define AB3100_LDO_H_VSEL_AC	5
#define AB3100_LDO_K		0x48
#define AB3100_LDO_EXT		0x49
#define AB3100_BUCK		0x4A
#define AB3100_BUCK_SLEEP	0x4B
#define AB3100_REG_ON_MASK	0x10

/**
 * struct ab3100_regulator
 * A struct passed around the individual regulator functions
 * @platform_device: platform device holding this regulator
 * @dev: handle to the device
 * @plfdata: AB3100 platform data passed in at probe time
 * @regreg: regulator register number in the AB3100
 */
struct ab3100_regulator {
	struct device *dev;
	struct ab3100_platform_data *plfdata;
	u8 regreg;
};

/* The order in which registers are initialized */
static const u8 ab3100_reg_init_order[AB3100_NUM_REGULATORS+2] = {
	AB3100_LDO_A,
	AB3100_LDO_C,
	AB3100_LDO_E,
	AB3100_LDO_E_SLEEP,
	AB3100_LDO_F,
	AB3100_LDO_G,
	AB3100_LDO_H,
	AB3100_LDO_K,
	AB3100_LDO_EXT,
	AB3100_BUCK,
	AB3100_BUCK_SLEEP,
	AB3100_LDO_D,
};

/* Preset (hardware defined) voltages for these regulators */
#define LDO_A_VOLTAGE 2750000
#define LDO_C_VOLTAGE 2650000
#define LDO_D_VOLTAGE 2650000

static const unsigned int ldo_e_buck_typ_voltages[] = {
	1800000,
	1400000,
	1300000,
	1200000,
	1100000,
	1050000,
	900000,
};

static const unsigned int ldo_f_typ_voltages[] = {
	1800000,
	1400000,
	1300000,
	1200000,
	1100000,
	1050000,
	2500000,
	2650000,
};

static const unsigned int ldo_g_typ_voltages[] = {
	2850000,
	2750000,
	1800000,
	1500000,
};

static const unsigned int ldo_h_typ_voltages[] = {
	2750000,
	1800000,
	1500000,
	1200000,
};

static const unsigned int ldo_k_typ_voltages[] = {
	2750000,
	1800000,
};

/* The regulator devices */
static struct ab3100_regulator
ab3100_regulators[AB3100_NUM_REGULATORS] = {
	{
		.regreg = AB3100_LDO_A,
	},
	{
		.regreg = AB3100_LDO_C,
	},
	{
		.regreg = AB3100_LDO_D,
	},
	{
		.regreg = AB3100_LDO_E,
	},
	{
		.regreg = AB3100_LDO_F,
	},
	{
		.regreg = AB3100_LDO_G,
	},
	{
		.regreg = AB3100_LDO_H,
	},
	{
		.regreg = AB3100_LDO_K,
	},
	{
		.regreg = AB3100_LDO_EXT,
		/* No voltages for the external regulator */
	},
	{
		.regreg = AB3100_BUCK,
	},
};

/*
 * General functions for enable, disable and is_enabled used for
 * LDO: A,C,E,F,G,H,K,EXT and BUCK
 */
static int ab3100_enable_regulator(struct regulator_dev *reg)
{
	struct ab3100_regulator *abreg = rdev_get_drvdata(reg);
	int err;
	u8 regval;

	err = abx500_get_register_interruptible(abreg->dev, 0, abreg->regreg,
						&regval);
	if (err) {
		dev_warn(&reg->dev, "failed to get regid %d value\n",
			 abreg->regreg);
		return err;
	}

	/* The regulator is already on, no reason to go further */
	if (regval & AB3100_REG_ON_MASK)
		return 0;

	regval |= AB3100_REG_ON_MASK;

	err = abx500_set_register_interruptible(abreg->dev, 0, abreg->regreg,
						regval);
	if (err) {
		dev_warn(&reg->dev, "failed to set regid %d value\n",
			 abreg->regreg);
		return err;
	}

	return 0;
}

static int ab3100_disable_regulator(struct regulator_dev *reg)
{
	struct ab3100_regulator *abreg = rdev_get_drvdata(reg);
	int err;
	u8 regval;

	/*
	 * LDO D is a special regulator. When it is disabled, the entire
	 * system is shut down. So this is handled specially.
	 */
	pr_info("Called ab3100_disable_regulator\n");
	if (abreg->regreg == AB3100_LDO_D) {
		dev_info(&reg->dev, "disabling LDO D - shut down system\n");
		/* Setting LDO D to 0x00 cuts the power to the SoC */
		return abx500_set_register_interruptible(abreg->dev, 0,
							 AB3100_LDO_D, 0x00U);
	}

	/*
	 * All other regulators are handled here
	 */
	err = abx500_get_register_interruptible(abreg->dev, 0, abreg->regreg,
						&regval);
	if (err) {
		dev_err(&reg->dev, "unable to get register 0x%x\n",
			abreg->regreg);
		return err;
	}
	regval &= ~AB3100_REG_ON_MASK;
	return abx500_set_register_interruptible(abreg->dev, 0, abreg->regreg,
						 regval);
}

static int ab3100_is_enabled_regulator(struct regulator_dev *reg)
{
	struct ab3100_regulator *abreg = rdev_get_drvdata(reg);
	u8 regval;
	int err;

	err = abx500_get_register_interruptible(abreg->dev, 0, abreg->regreg,
						&regval);
	if (err) {
		dev_err(&reg->dev, "unable to get register 0x%x\n",
			abreg->regreg);
		return err;
	}

	return regval & AB3100_REG_ON_MASK;
}

static int ab3100_get_voltage_regulator(struct regulator_dev *reg)
{
	struct ab3100_regulator *abreg = rdev_get_drvdata(reg);
	u8 regval;
	int err;

	/*
	 * For variable types, read out setting and index into
	 * supplied voltage list.
	 */
	err = abx500_get_register_interruptible(abreg->dev, 0,
						abreg->regreg, &regval);
	if (err) {
		dev_warn(&reg->dev,
			 "failed to get regulator value in register %02x\n",
			 abreg->regreg);
		return err;
	}

	/* The 3 highest bits index voltages */
	regval &= 0xE0;
	regval >>= 5;

	if (regval >= reg->desc->n_voltages) {
		dev_err(&reg->dev,
			"regulator register %02x contains an illegal voltage setting\n",
			abreg->regreg);
		return -EINVAL;
	}

	return reg->desc->volt_table[regval];
}

static int ab3100_set_voltage_regulator_sel(struct regulator_dev *reg,
					    unsigned selector)
{
	struct ab3100_regulator *abreg = rdev_get_drvdata(reg);
	u8 regval;
	int err;

	err = abx500_get_register_interruptible(abreg->dev, 0,
						abreg->regreg, &regval);
	if (err) {
		dev_warn(&reg->dev,
			 "failed to get regulator register %02x\n",
			 abreg->regreg);
		return err;
	}

	/* The highest three bits control the variable regulators */
	regval &= ~0xE0;
	regval |= (selector << 5);

	err = abx500_set_register_interruptible(abreg->dev, 0,
						abreg->regreg, regval);
	if (err)
		dev_warn(&reg->dev, "failed to set regulator register %02x\n",
			abreg->regreg);

	return err;
}

static int ab3100_set_suspend_voltage_regulator(struct regulator_dev *reg,
						int uV)
{
	struct ab3100_regulator *abreg = rdev_get_drvdata(reg);
	u8 regval;
	int err;
	int bestindex;
	u8 targetreg;

	if (abreg->regreg == AB3100_LDO_E)
		targetreg = AB3100_LDO_E_SLEEP;
	else if (abreg->regreg == AB3100_BUCK)
		targetreg = AB3100_BUCK_SLEEP;
	else
		return -EINVAL;

	/* LDO E and BUCK have special suspend voltages you can set */
	bestindex = regulator_map_voltage_iterate(reg, uV, uV);

	err = abx500_get_register_interruptible(abreg->dev, 0,
						targetreg, &regval);
	if (err) {
		dev_warn(&reg->dev,
			 "failed to get regulator register %02x\n",
			 targetreg);
		return err;
	}

	/* The highest three bits control the variable regulators */
	regval &= ~0xE0;
	regval |= (bestindex << 5);

	err = abx500_set_register_interruptible(abreg->dev, 0,
						targetreg, regval);
	if (err)
		dev_warn(&reg->dev, "failed to set regulator register %02x\n",
			abreg->regreg);

	return err;
}

/*
 * The external regulator can just define a fixed voltage.
 */
static int ab3100_get_voltage_regulator_external(struct regulator_dev *reg)
{
	struct ab3100_regulator *abreg = rdev_get_drvdata(reg);

	if (abreg->plfdata)
		return abreg->plfdata->external_voltage;
	else
		/* TODO: encode external voltage into device tree */
		return 0;
}

static const struct regulator_ops regulator_ops_fixed = {
	.enable      = ab3100_enable_regulator,
	.disable     = ab3100_disable_regulator,
	.is_enabled  = ab3100_is_enabled_regulator,
};

static const struct regulator_ops regulator_ops_variable = {
	.enable      = ab3100_enable_regulator,
	.disable     = ab3100_disable_regulator,
	.is_enabled  = ab3100_is_enabled_regulator,
	.get_voltage = ab3100_get_voltage_regulator,
	.set_voltage_sel = ab3100_set_voltage_regulator_sel,
	.list_voltage = regulator_list_voltage_table,
};

static const struct regulator_ops regulator_ops_variable_sleepable = {
	.enable      = ab3100_enable_regulator,
	.disable     = ab3100_disable_regulator,
	.is_enabled  = ab3100_is_enabled_regulator,
	.get_voltage = ab3100_get_voltage_regulator,
	.set_voltage_sel = ab3100_set_voltage_regulator_sel,
	.set_suspend_voltage = ab3100_set_suspend_voltage_regulator,
	.list_voltage = regulator_list_voltage_table,
};

/*
 * LDO EXT is an external regulator so it is really
 * not possible to set any voltage locally here, AB3100
 * is an on/off switch plain an simple. The external
 * voltage is defined in the board set-up if any.
 */
static const struct regulator_ops regulator_ops_external = {
	.enable      = ab3100_enable_regulator,
	.disable     = ab3100_disable_regulator,
	.is_enabled  = ab3100_is_enabled_regulator,
	.get_voltage = ab3100_get_voltage_regulator_external,
};

static const struct regulator_desc
ab3100_regulator_desc[AB3100_NUM_REGULATORS] = {
	{
		.name = "LDO_A",
		.id   = AB3100_LDO_A,
		.ops  = &regulator_ops_fixed,
		.n_voltages = 1,
		.type = REGULATOR_VOLTAGE,
		.owner = THIS_MODULE,
		.fixed_uV = LDO_A_VOLTAGE,
		.enable_time = 200,
	},
	{
		.name = "LDO_C",
		.id   = AB3100_LDO_C,
		.ops  = &regulator_ops_fixed,
		.n_voltages = 1,
		.type = REGULATOR_VOLTAGE,
		.owner = THIS_MODULE,
		.fixed_uV = LDO_C_VOLTAGE,
		.enable_time = 200,
	},
	{
		.name = "LDO_D",
		.id   = AB3100_LDO_D,
		.ops  = &regulator_ops_fixed,
		.n_voltages = 1,
		.type = REGULATOR_VOLTAGE,
		.owner = THIS_MODULE,
		.fixed_uV = LDO_D_VOLTAGE,
		.enable_time = 200,
	},
	{
		.name = "LDO_E",
		.id   = AB3100_LDO_E,
		.ops  = &regulator_ops_variable_sleepable,
		.n_voltages = ARRAY_SIZE(ldo_e_buck_typ_voltages),
		.volt_table = ldo_e_buck_typ_voltages,
		.type = REGULATOR_VOLTAGE,
		.owner = THIS_MODULE,
		.enable_time = 200,
	},
	{
		.name = "LDO_F",
		.id   = AB3100_LDO_F,
		.ops  = &regulator_ops_variable,
		.n_voltages = ARRAY_SIZE(ldo_f_typ_voltages),
		.volt_table = ldo_f_typ_voltages,
		.type = REGULATOR_VOLTAGE,
		.owner = THIS_MODULE,
		.enable_time = 600,
	},
	{
		.name = "LDO_G",
		.id   = AB3100_LDO_G,
		.ops  = &regulator_ops_variable,
		.n_voltages = ARRAY_SIZE(ldo_g_typ_voltages),
		.volt_table = ldo_g_typ_voltages,
		.type = REGULATOR_VOLTAGE,
		.owner = THIS_MODULE,
		.enable_time = 400,
	},
	{
		.name = "LDO_H",
		.id   = AB3100_LDO_H,
		.ops  = &regulator_ops_variable,
		.n_voltages = ARRAY_SIZE(ldo_h_typ_voltages),
		.volt_table = ldo_h_typ_voltages,
		.type = REGULATOR_VOLTAGE,
		.owner = THIS_MODULE,
		.enable_time = 200,
	},
	{
		.name = "LDO_K",
		.id   = AB3100_LDO_K,
		.ops  = &regulator_ops_variable,
		.n_voltages = ARRAY_SIZE(ldo_k_typ_voltages),
		.volt_table = ldo_k_typ_voltages,
		.type = REGULATOR_VOLTAGE,
		.owner = THIS_MODULE,
		.enable_time = 200,
	},
	{
		.name = "LDO_EXT",
		.id   = AB3100_LDO_EXT,
		.ops  = &regulator_ops_external,
		.type = REGULATOR_VOLTAGE,
		.owner = THIS_MODULE,
	},
	{
		.name = "BUCK",
		.id   = AB3100_BUCK,
		.ops  = &regulator_ops_variable_sleepable,
		.n_voltages = ARRAY_SIZE(ldo_e_buck_typ_voltages),
		.volt_table = ldo_e_buck_typ_voltages,
		.type = REGULATOR_VOLTAGE,
		.owner = THIS_MODULE,
		.enable_time = 1000,
	},
};

static int ab3100_regulator_register(struct platform_device *pdev,
				     struct ab3100_platform_data *plfdata,
				     struct regulator_init_data *init_data,
				     struct device_node *np,
				     unsigned long id)
{
	const struct regulator_desc *desc;
	struct ab3100_regulator *reg;
	struct regulator_dev *rdev;
	struct regulator_config config = { };
	int err, i;

	for (i = 0; i < AB3100_NUM_REGULATORS; i++) {
		desc = &ab3100_regulator_desc[i];
		if (desc->id == id)
			break;
	}
	if (desc->id != id)
		return -ENODEV;

	/* Same index used for this array */
	reg = &ab3100_regulators[i];

	/*
	 * Initialize per-regulator struct.
	 * Inherit platform data, this comes down from the
	 * i2c boarddata, from the machine. So if you want to
	 * see what it looks like for a certain machine, go
	 * into the machine I2C setup.
	 */
	reg->dev = &pdev->dev;
	if (plfdata) {
		reg->plfdata = plfdata;
		config.init_data = &plfdata->reg_constraints[i];
	} else if (np) {
		config.of_node = np;
		config.init_data = init_data;
	}
	config.dev = &pdev->dev;
	config.driver_data = reg;

	rdev = devm_regulator_register(&pdev->dev, desc, &config);
	if (IS_ERR(rdev)) {
		err = PTR_ERR(rdev);
		dev_err(&pdev->dev,
			"%s: failed to register regulator %s err %d\n",
			__func__, desc->name,
			err);
		return err;
	}

	return 0;
}

static struct of_regulator_match ab3100_regulator_matches[] = {
	{ .name = "ab3100_ldo_a", .driver_data = (void *) AB3100_LDO_A, },
	{ .name = "ab3100_ldo_c", .driver_data = (void *) AB3100_LDO_C, },
	{ .name = "ab3100_ldo_d", .driver_data = (void *) AB3100_LDO_D, },
	{ .name = "ab3100_ldo_e", .driver_data = (void *) AB3100_LDO_E, },
	{ .name = "ab3100_ldo_f", .driver_data = (void *) AB3100_LDO_F },
	{ .name = "ab3100_ldo_g", .driver_data = (void *) AB3100_LDO_G },
	{ .name = "ab3100_ldo_h", .driver_data = (void *) AB3100_LDO_H },
	{ .name = "ab3100_ldo_k", .driver_data = (void *) AB3100_LDO_K },
	{ .name = "ab3100_ext", .driver_data = (void *) AB3100_LDO_EXT },
	{ .name = "ab3100_buck", .driver_data = (void *) AB3100_BUCK },
};

/*
 * Initial settings of ab3100 registers.
 * Common for below LDO regulator settings are that
 * bit 7-5 controls voltage. Bit 4 turns regulator ON(1) or OFF(0).
 * Bit 3-2 controls sleep enable and bit 1-0 controls sleep mode.
 */
/* LDO_A 0x16: 2.75V, ON, SLEEP_A, SLEEP OFF GND */
#define LDO_A_SETTING		0x16
/* LDO_C 0x10: 2.65V, ON, SLEEP_A or B, SLEEP full power */
#define LDO_C_SETTING		0x10
/* LDO_D 0x10: 2.65V, ON, sleep mode not used */
#define LDO_D_SETTING		0x10
/* LDO_E 0x10: 1.8V, ON, SLEEP_A or B, SLEEP full power */
#define LDO_E_SETTING		0x10
/* LDO_E SLEEP 0x00: 1.8V, not used, SLEEP_A or B, not used */
#define LDO_E_SLEEP_SETTING	0x00
/* LDO_F 0xD0: 2.5V, ON, SLEEP_A or B, SLEEP full power */
#define LDO_F_SETTING		0xD0
/* LDO_G 0x00: 2.85V, OFF, SLEEP_A or B, SLEEP full power */
#define LDO_G_SETTING		0x00
/* LDO_H 0x18: 2.75V, ON, SLEEP_B, SLEEP full power */
#define LDO_H_SETTING		0x18
/* LDO_K 0x00: 2.75V, OFF, SLEEP_A or B, SLEEP full power */
#define LDO_K_SETTING		0x00
/* LDO_EXT 0x00: Voltage not set, OFF, not used, not used */
#define LDO_EXT_SETTING		0x00
/* BUCK 0x7D: 1.2V, ON, SLEEP_A and B, SLEEP low power */
#define BUCK_SETTING	0x7D
/* BUCK SLEEP 0xAC: 1.05V, Not used, SLEEP_A and B, Not used */
#define BUCK_SLEEP_SETTING	0xAC

static const u8 ab3100_reg_initvals[] = {
	LDO_A_SETTING,
	LDO_C_SETTING,
	LDO_E_SETTING,
	LDO_E_SLEEP_SETTING,
	LDO_F_SETTING,
	LDO_G_SETTING,
	LDO_H_SETTING,
	LDO_K_SETTING,
	LDO_EXT_SETTING,
	BUCK_SETTING,
	BUCK_SLEEP_SETTING,
	LDO_D_SETTING,
};

static int
ab3100_regulator_of_probe(struct platform_device *pdev, struct device_node *np)
{
	int err, i;

	/*
	 * Set up the regulator registers, as was previously done with
	 * platform data.
	 */
	/* Set up regulators */
	for (i = 0; i < ARRAY_SIZE(ab3100_reg_init_order); i++) {
		err = abx500_set_register_interruptible(&pdev->dev, 0,
					ab3100_reg_init_order[i],
					ab3100_reg_initvals[i]);
		if (err) {
			dev_err(&pdev->dev, "regulator initialization failed with error %d\n",
				err);
			return err;
		}
	}

	for (i = 0; i < ARRAY_SIZE(ab3100_regulator_matches); i++) {
		err = ab3100_regulator_register(
			pdev, NULL, ab3100_regulator_matches[i].init_data,
			ab3100_regulator_matches[i].of_node,
			(unsigned long)ab3100_regulator_matches[i].driver_data);
		if (err)
			return err;
	}

	return 0;
}

static int ab3100_regulators_probe(struct platform_device *pdev)
{
	struct ab3100_platform_data *plfdata = dev_get_platdata(&pdev->dev);
	struct device_node *np = pdev->dev.of_node;
	int err = 0;
	u8 data;
	int i;

	/* Check chip state */
	err = abx500_get_register_interruptible(&pdev->dev, 0,
						AB3100_LDO_D, &data);
	if (err) {
		dev_err(&pdev->dev, "could not read initial status of LDO_D\n");
		return err;
	}
	if (data & 0x10)
		dev_notice(&pdev->dev,
			   "chip is already in active mode (Warm start)\n");
	else
		dev_notice(&pdev->dev,
			   "chip is in inactive mode (Cold start)\n");

	if (np) {
		err = of_regulator_match(&pdev->dev, np,
					 ab3100_regulator_matches,
					 ARRAY_SIZE(ab3100_regulator_matches));
		if (err < 0) {
			dev_err(&pdev->dev,
				"Error parsing regulator init data: %d\n", err);
			return err;
		}
		return ab3100_regulator_of_probe(pdev, np);
	}

	/* Set up regulators */
	for (i = 0; i < ARRAY_SIZE(ab3100_reg_init_order); i++) {
		err = abx500_set_register_interruptible(&pdev->dev, 0,
					ab3100_reg_init_order[i],
					plfdata->reg_initvals[i]);
		if (err) {
			dev_err(&pdev->dev, "regulator initialization failed with error %d\n",
				err);
			return err;
		}
	}

	/* Register the regulators */
	for (i = 0; i < AB3100_NUM_REGULATORS; i++) {
		const struct regulator_desc *desc = &ab3100_regulator_desc[i];

		err = ab3100_regulator_register(pdev, plfdata, NULL, NULL,
						desc->id);
		if (err)
			return err;
	}

	return 0;
}

static struct platform_driver ab3100_regulators_driver = {
	.driver = {
		.name  = "ab3100-regulators",
	},
	.probe = ab3100_regulators_probe,
};

static __init int ab3100_regulators_init(void)
{
	return platform_driver_register(&ab3100_regulators_driver);
}

static __exit void ab3100_regulators_exit(void)
{
	platform_driver_unregister(&ab3100_regulators_driver);
}

subsys_initcall(ab3100_regulators_init);
module_exit(ab3100_regulators_exit);

MODULE_AUTHOR("Mattias Wallin <mattias.wallin@stericsson.com>");
MODULE_DESCRIPTION("AB3100 Regulator driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:ab3100-regulators");

{'repo_name': 'google/ktsan', 'stars': '551', 'repo_language': 'C', 'file_name': 'irqsrcs_thm_9_0.h', 'mime_type': 'text/x-c', 'hash': -3856709804314601098, 'source_dataset': 'data'}


require 'active_record/connection_adapters/abstract_adapter'

ActiveRecord::ConnectionAdapters::IndexDefinition.class_eval do
  attr_accessor :spatial

  alias_method :initialize_without_spatial, :initialize
  def initialize(table, name, unique, columns, spatial = false)
    initialize_without_spatial(table, name, unique, columns)
    @spatial = spatial
  end
end

{'repo_name': 'pdeffendol/spatial_adapter', 'stars': '201', 'repo_language': 'Ruby', 'file_name': 'init.rb', 'mime_type': 'text/plain', 'hash': -7716722894148074557, 'source_dataset': 'data'}


import { ADD_ERROR, REMOVE_ERROR } from '../../constants/actionTypes'
import { addError, removeError } from '../errors'

beforeEach(() => {
  jest.clearAllMocks()
})

describe('addError', () => {
  test('should create an action to update the authToken', () => {
    const payload = {
      id: 1,
      title: 'title',
      message: 'message'
    }

    const expectedAction = {
      type: ADD_ERROR,
      payload
    }

    expect(addError(payload)).toEqual(expectedAction)
  })
})

describe('removeError', () => {
  test('should create an action to update the authToken', () => {
    const payload = 1

    const expectedAction = {
      type: REMOVE_ERROR,
      payload
    }

    expect(removeError(payload)).toEqual(expectedAction)
  })
})

{'repo_name': 'nasa/earthdata-search', 'stars': '533', 'repo_language': 'JavaScript', 'file_name': '1559965681107_users.js', 'mime_type': 'text/plain', 'hash': 7592516172128754374, 'source_dataset': 'data'}


require_relative '../test_helper'
try_loading('test-unit')

if M::Frameworks.test_unit?
  class TestUnitExampleTest < Test::Unit::TestCase
    def setup
    end

    def test_apple
      assert_equal 1, 1
    end

    def test_banana
      assert_equal 1, 1
      assert_equal 2, 2
      assert_equal 3, 3
    end
  end
end

{'repo_name': 'qrush/m', 'stars': '329', 'repo_language': 'Ruby', 'file_name': 'e_test.rb', 'mime_type': 'text/x-ruby', 'hash': 6492489118497264448, 'source_dataset': 'data'}


<?php
/**
 * @package    Joomla.Component.Builder
 *
 * @created    30th April, 2015
 * @author     Llewellyn van der Merwe <http://www.joomlacomponentbuilder.com>
 * @github     Joomla Component Builder <https://github.com/vdm-io/Joomla-Component-Builder>
 * @copyright  Copyright (C) 2015 - 2020 Vast Development Method. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 */

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

// import the list field type
jimport('joomla.form.helper');
JFormHelper::loadFieldClass('list');

/**
 * Viewtabs Form Field class for the Componentbuilder component
 */
class JFormFieldViewtabs extends JFormFieldList
{
	/**
	 * The viewtabs field type.
	 *
	 * @var		string
	 */
	public $type = 'viewtabs';

	/**
	 * Method to get a list of options for a list input.
	 *
	 * @return	array    An array of JHtml options.
	 */
	protected function getOptions()
	{
		// get the input from url
		$jinput = JFactory::getApplication()->input;
		// get the view name & id
		$fieldsID = $jinput->getInt('id', 0);
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->select($db->quoteName(array('a.id','a.addtabs'),array('id','addtabs')));
		$query->from($db->quoteName('#__componentbuilder_admin_view', 'a'));
		if ($fieldsID > 0)
		{
			$viewName = $jinput->get('view', null, 'WORD');
			// only allow for fields and custom tabs
			if ('admin_fields' !== $viewName && 'admin_custom_tabs' !== $viewName)
			{
				return false;
			}
			$query->join('LEFT', $db->quoteName('#__componentbuilder_' . $viewName, 'b') . ' ON (' . $db->quoteName('a.id') . ' = ' . $db->quoteName('b.admin_view') . ')');
			$query->where($db->quoteName('b.id') . '  = ' . (int) $fieldsID);
		}
		else
		{
			// get the refs if found
			$ref = $jinput->get('ref', null, 'WORD');
			$refid = $jinput->getInt('refid', 0);
			if ('admin_view' === $ref && $refid > 0)
			{
				$query->where($db->quoteName('a.id') . ' = ' . (int) $refid);
			}
			else
			{
				// kry maar niks
				$query->where($db->quoteName('a.id') . ' = 0');
			}
		}
		$query->where($db->quoteName('a.published') . ' >= 1');
		$query->order('a.addtabs ASC');
		$db->setQuery((string)$query);
		$item = $db->loadObject();
		$options = array();
		if (isset($item->addtabs) && ComponentbuilderHelper::checkJson($item->addtabs))
		{
			$items = json_decode($item->addtabs, true);
			// check if the array has values
			if (ComponentbuilderHelper::checkArray($items))
			{
				$nr = 1;
				foreach($items as $itemName)
				{
					$options[] = JHtml::_('select.option', $nr, $itemName['name']);
					$nr++;
				}
			}
		}
		// check if any were loaded
		if (!ComponentbuilderHelper::checkArray($options))
		{
			$options[] = JHtml::_('select.option', 1, JText::_('COM_COMPONENTBUILDER_DETAILS'));
		}
		// add the default publish tab as an option
		$options[] = JHtml::_('select.option', 15, JText::_('COM_COMPONENTBUILDER_PUBLISHING'));
		return $options;
	}
}

{'repo_name': 'vdm-io/Joomla-Component-Builder', 'stars': '271', 'repo_language': 'PHP', 'file_name': 'library_files_folders_urls.php', 'mime_type': 'text/x-php', 'hash': 3813428337602133142, 'source_dataset': 'data'}


#ifndef OPENMW_COMPONENTS_MISC_MESSAGEFORMATPARSER_H
#define OPENMW_COMPONENTS_MISC_MESSAGEFORMATPARSER_H

#include <string>

namespace Misc
{
    class MessageFormatParser
    {
        protected:
            enum Placeholder
            {
                StringPlaceholder,
                IntegerPlaceholder,
                FloatPlaceholder
            };

            enum Notation
            {
                FixedNotation,
                ScientificNotation,
                ShortestNotation
            };

            virtual void visitedPlaceholder(Placeholder placeholder, char padding, int width, int precision, Notation notation) = 0;
            virtual void visitedCharacter(char c) = 0;

        public:
            virtual ~MessageFormatParser();

            virtual void process(const std::string& message);
    };
}

#endif

{'repo_name': 'OpenMW/openmw', 'stars': '3263', 'repo_language': 'C++', 'file_name': 'FindOSGPlugins.cmake', 'mime_type': 'text/plain', 'hash': -3466167248652601891, 'source_dataset': 'data'}


fileFormatVersion: 2
guid: f99f6bcc2fdb35a4bb8d0130d23974da
TextureImporter:
  internalIDToNameTable: []
  externalObjects: {}
  serializedVersion: 10
  mipmaps:
    mipMapMode: 0
    enableMipMap: 0
    sRGBTexture: 1
    linearTexture: 0
    fadeOut: 0
    borderMipMap: 0
    mipMapsPreserveCoverage: 0
    alphaTestReferenceValue: 0.5
    mipMapFadeDistanceStart: 1
    mipMapFadeDistanceEnd: 3
  bumpmap:
    convertToNormalMap: 0
    externalNormalMap: 0
    heightScale: 0.25
    normalMapFilter: 0
  isReadable: 1
  streamingMipmaps: 0
  streamingMipmapsPriority: 0
  grayScaleToAlpha: 0
  generateCubemap: 6
  cubemapConvolution: 0
  seamlessCubemap: 0
  textureFormat: 1
  maxTextureSize: 2048
  textureSettings:
    serializedVersion: 2
    filterMode: -1
    aniso: -1
    mipBias: -100
    wrapU: -1
    wrapV: -1
    wrapW: -1
  nPOTScale: 0
  lightmap: 0
  compressionQuality: 50
  spriteMode: 0
  spriteExtrude: 1
  spriteMeshType: 1
  alignment: 0
  spritePivot: {x: 0.5, y: 0.5}
  spritePixelsToUnits: 100
  spriteBorder: {x: 0, y: 0, z: 0, w: 0}
  spriteGenerateFallbackPhysicsShape: 1
  alphaUsage: 1
  alphaIsTransparency: 0
  spriteTessellationDetail: -1
  textureType: 0
  textureShape: 1
  singleChannelComponent: 0
  maxTextureSizeSet: 0
  compressionQualitySet: 0
  textureFormatSet: 0
  ignorePngGamma: 0
  platformSettings:
  - serializedVersion: 3
    buildTarget: DefaultTexturePlatform
    maxTextureSize: 2048
    resizeAlgorithm: 0
    textureFormat: -1
    textureCompression: 0
    compressionQuality: 50
    crunchedCompression: 0
    allowsAlphaSplitting: 0
    overridden: 0
    androidETC2FallbackOverride: 0
    forceMaximumCompressionQuality_BC6H_BC7: 0
  spriteSheet:
    serializedVersion: 2
    sprites: []
    outline: []
    physicsShape: []
    bones: []
    spriteID:
    internalID: 0
    vertices: []
    indices:
    edges: []
    weights: []
    secondaryTextures: []
  spritePackingTag:
  pSDRemoveMatte: 0
  pSDShowRemoveMatteOption: 0
  userData:
  assetBundleName:
  assetBundleVariant:

{'repo_name': 'Unity-Technologies/Graphics', 'stars': '309', 'repo_language': 'C#', 'file_name': 'Decal_All_SG.mat', 'mime_type': 'text/plain', 'hash': -7583836169908032133, 'source_dataset': 'data'}


/*
 * Copyright 2002-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.beans.factory.config;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.lang.Nullable;

/**
 * Strategy interface used by a {@link ConfigurableBeanFactory},
 * representing a target scope to hold bean instances in.
 * This allows for extending the BeanFactory's standard scopes
 * {@link ConfigurableBeanFactory#SCOPE_SINGLETON "singleton"} and
 * {@link ConfigurableBeanFactory#SCOPE_PROTOTYPE "prototype"}
 * with custom further scopes, registered for a
 * {@link ConfigurableBeanFactory#registerScope(String, Scope) specific key}.
 *
 *
{@link org.springframework.context.ApplicationContext} implementations
 * such as a {@link org.springframework.web.context.WebApplicationContext}
 * may register additional standard scopes specific to their environment,
 * e.g. {@link org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST "request"}
 * and {@link org.springframework.web.context.WebApplicationContext#SCOPE_SESSION "session"},
 * based on this Scope SPI.
 *
 *
Even if its primary use is for extended scopes in a web environment,
 * this SPI is completely generic: It provides the ability to get and put
 * objects from any underlying storage mechanism, such as an HTTP session
 * or a custom conversation mechanism. The name passed into this class's
 * {@code get} and {@code remove} methods will identify the
 * target object in the current scope.
 *
 *
{@code Scope} implementations are expected to be thread-safe.
 * One {@code Scope} instance can be used with multiple bean factories
 * at the same time, if desired (unless it explicitly wants to be aware of
 * the containing BeanFactory), with any number of threads accessing
 * the {@code Scope} concurrently from any number of factories.
 *
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @since 2.0
 * @see ConfigurableBeanFactory#registerScope
 * @see CustomScopeConfigurer
 * @see org.springframework.aop.scope.ScopedProxyFactoryBean
 * @see org.springframework.web.context.request.RequestScope
 * @see org.springframework.web.context.request.SessionScope
 */
public interface Scope {

	/**
	 * Return the object with the given name from the underlying scope,
	 * {@link org.springframework.beans.factory.ObjectFactory#getObject() creating it}
	 * if not found in the underlying storage mechanism.
	 *
This is the central operation of a Scope, and the only operation
	 * that is absolutely required.
	 * @param name the name of the object to retrieve
	 * @param objectFactory the {@link ObjectFactory} to use to create the scoped
	 * object if it is not present in the underlying storage mechanism
	 * @return the desired object (never {@code null})
	 * @throws IllegalStateException if the underlying scope is not currently active
	 */
	Object get(String name, ObjectFactory<?> objectFactory);

	/**
	 * Remove the object with the given {@code name} from the underlying scope.
	 *
Returns {@code null} if no object was found; otherwise
	 * returns the removed {@code Object}.
	 *
Note that an implementation should also remove a registered destruction
	 * callback for the specified object, if any. It does, however, not
	 * need to execute a registered destruction callback in this case,
	 * since the object will be destroyed by the caller (if appropriate).
	 *
Note: This is an optional operation. Implementations may throw
	 * {@link UnsupportedOperationException} if they do not support explicitly
	 * removing an object.
	 * @param name the name of the object to remove
	 * @return the removed object, or {@code null} if no object was present
	 * @throws IllegalStateException if the underlying scope is not currently active
	 * @see #registerDestructionCallback
	 */
	@Nullable
	Object remove(String name);

	/**
	 * Register a callback to be executed on destruction of the specified
	 * object in the scope (or at destruction of the entire scope, if the
	 * scope does not destroy individual objects but rather only terminates
	 * in its entirety).
	 *
Note: This is an optional operation. This method will only
	 * be called for scoped beans with actual destruction configuration
	 * (DisposableBean, destroy-method, DestructionAwareBeanPostProcessor).
	 * Implementations should do their best to execute a given callback
	 * at the appropriate time. If such a callback is not supported by the
	 * underlying runtime environment at all, the callback must be
	 * ignored and a corresponding warning should be logged.
	 *
Note that 'destruction' refers to automatic destruction of
	 * the object as part of the scope's own lifecycle, not to the individual
	 * scoped object having been explicitly removed by the application.
	 * If a scoped object gets removed via this facade's {@link #remove(String)}
	 * method, any registered destruction callback should be removed as well,
	 * assuming that the removed object will be reused or manually destroyed.
	 * @param name the name of the object to execute the destruction callback for
	 * @param callback the destruction callback to be executed.
	 * Note that the passed-in Runnable will never throw an exception,
	 * so it can safely be executed without an enclosing try-catch block.
	 * Furthermore, the Runnable will usually be serializable, provided
	 * that its target object is serializable as well.
	 * @throws IllegalStateException if the underlying scope is not currently active
	 * @see org.springframework.beans.factory.DisposableBean
	 * @see org.springframework.beans.factory.support.AbstractBeanDefinition#getDestroyMethodName()
	 * @see DestructionAwareBeanPostProcessor
	 */
	void registerDestructionCallback(String name, Runnable callback);

	/**
	 * Resolve the contextual object for the given key, if any.
	 * E.g. the HttpServletRequest object for key "request".
	 * @param key the contextual key
	 * @return the corresponding object, or {@code null} if none found
	 * @throws IllegalStateException if the underlying scope is not currently active
	 */
	@Nullable
	Object resolveContextualObject(String key);

	/**
	 * Return the conversation ID for the current underlying scope, if any.
	 *
The exact meaning of the conversation ID depends on the underlying
	 * storage mechanism. In the case of session-scoped objects, the
	 * conversation ID would typically be equal to (or derived from) the
	 * {@link javax.servlet.http.HttpSession#getId() session ID}; in the
	 * case of a custom conversation that sits within the overall session,
	 * the specific ID for the current conversation would be appropriate.
	 *
Note: This is an optional operation. It is perfectly valid to
	 * return {@code null} in an implementation of this method if the
	 * underlying storage mechanism has no obvious candidate for such an ID.
	 * @return the conversation ID, or {@code null} if there is no
	 * conversation ID for the current scope
	 * @throws IllegalStateException if the underlying scope is not currently active
	 */
	@Nullable
	String getConversationId();

}

{'repo_name': 'spring-projects/spring-framework', 'stars': '38287', 'repo_language': 'Java', 'file_name': 'Jaxb2UnmarshallerTests.java', 'mime_type': 'text/x-java', 'hash': -3541852325824189169, 'source_dataset': 'data'}


fileFormatVersion: 2
guid: 49b0c76b911a9d34bac07d4b3aa7f6de
MonoImporter:
  serializedVersion: 2
  defaultReferences: []
  executionOrder: 0
  icon: {instanceID: 0}
  userData:

{'repo_name': 'XINCGer/ColaFrameWork', 'stars': '246', 'repo_language': 'C#', 'file_name': 'init.lua', 'mime_type': 'text/plain', 'hash': -4400137733262904590, 'source_dataset': 'data'}


#### Table of Contents

1. [Introduction](index.html)
1. [Android Application Fundamentals](app_fundamentals.html)
1. [Getting Started with Reversing Android Apps](reversing_intro.html)
    * [Exercise 1](reversing_intro.html#exercise-1---beginning-re-with-jadx)
1. [Reverse Engineering Android Apps - DEX Bytecode](reversing_dex.html)
	* [Exercise 2](reversing_dex.html#exercise-2---reverse-engineer-the-dex)
	* [Exercise 3](reversing_dex.html#exercise-3---reverse-engineer-the-dex-to-identify-the-vuln)
	* [Exercise 4](reversing_dex.html#exercise-4---arbitrary-command-execution-take-2)
1. [Reverse Engineering Android Apps - Native Libraries](reversing_native_libs.html)
	* [Exercise 5](reversing_native_libs.html#exercise-5---find-the-address-of-the-native-function)
	* [Exercise 6](reversing_native_libs.html#exercise-6---find-and-reverse-the-native-function)
1. [Reverse Engineering Android Apps - Obfuscation](obfuscation.html)
	* [Exercise 7](obfuscation.html#exercise-7---string-deobfuscation)
1. [Conclusion](conclusion.html)

# 3. Getting Started with Reversing Android Apps
Now that we've reviewed the basics of Android applications, it's time to start reversing them!

## Starting Points for RE
One of the main keys of reverse engineering, regardless of platform, that all reverse engineers need to do, is figure out where to start their analysis. As a reverse engineer, when you've decided that your next step to solve your problem/answer your question is to use static analysis, then you need to know where you want to begin the static analysis.

Android applications can be very large and realistically, you likely won't be able to review every line of code. So where do you begin? My guidance when deciding where to begin doing static analysis is:

1. **What is your goal?** In *most* cases, you are doing RE/static analysis to answer a specific question. Remember what that is and go back to it often. It's very easy to go down a rabbit hole of code that is not related to the problem you're trying to solve.
1. **API Calls** Most interesting behaviors that you may want to identify in Android, ultimately come down to a single, or a set of API calls. For example, let's say you're evaluating an application to see if it's doing [Premium SMS Fraud](https://developers.google.com/android/play-protect/phacategories#billing-fraud). Premium SMS Fraud means that an app is sending a premium SMS message without user consent. Therefore, to do the fraud, the app must send an SMS message. There's a finite number of API calls that will allow an application to send an SMS message. For example, `sendTextMessage`, `sendMultipartMessage`,`smsto:`. Therefore one of the key places to begin analysis, is to find the API calls that are required for the behavior you're interested in, and then search for them in your application. You can then begin your reversing around those API calls.
1. **App Entry Points** In many cases, you're only interested in code that can be executed, not dead code, in the application. Therefore, starting at an application entry point (detailed in [this section](app_fundamentals.html#application-entry-points)) is a good choice if you're not sure where else to start.
1. **Decryption Methods** Java largely relies on strings to do many of its operations. For example, to send intents or call methods through reflection. If your application has no human readable strings, then it likely means its obfuscated or encrypted. A good starting point is to find if either "jumbled" strings or binary arrays are all passed to the same methods. If they are, those methods are likely the deobfuscation or decryption methods.

## Exercise #1 - Beginning RE with jadx

In Exercise #1, we're going to practice coming up with the classes where we would begin our RE analysis. Your goal is to come up with a class or classes that you think would be a good place to begin your analysis. The sample is the ThaiCamera.apk. You can find this sample in the VM at `~/samples/ThaiCamera.apk`. The SHA256 digest of this sample is 55da412157e93153e419c3385ebcd5335bd0d0c3f77a75e2d2413dd128270be2.

### Goal
The goal of this exercise is to:

1. Learn to use jadx for reverse engineering APKs
1. Practice identifying class(es) that would be good starting points to begin your revering

### Exercise Context
You are a malware analyst for Android applications. You are concerned that this sample maybe doing premium SMS fraud, meaning that it sends an SMS to a premium phone number without disclosure & user consent.

### Instructions

1. Start jadx by opening the terminal in the VM and running the `jadx-gui` command in the terminal.
1. Open ThaiCamera.apk in the jadx GUI. It's in the VM's path at `~/samples/ThaiCamera.apk`. When you open the application in jadx, you will see the following. Under the Source Code heading, the packages (namespaces for the Java classes) included in the application. ![Screenshot of jadx when first opening an APK](images/Ex1.OpenInJadx.png)
1. By clicking on the expansion tab of "Resources", you can see the contents of the APK. Some of the most interesting are the Manifest (`AndroidManifest.xml`), `classes.dex` (contains the DEX bytecode that is decompiled under the "Source Code" tab), and the `assets/` folder which contains any other files the APK may need to run.
1. Open AndroidManifest.xml and identify any of the application entry points described in the [Application Entry Points](app_fundamentals.html#application-entry-points) section.
1. Using the information gathered in the previous step and the [Starting Points for RE](#starting-points-for-re) section above. Decide on a class or classes, that you think would be classes that you'd begin analyzing when you start your reversing.

### Solution

[**NEXT** > 4. Reverse Engineering Android Apps - DEX Bytecode](reversing_dex.html)

{'repo_name': 'maddiestone/AndroidAppRE', 'stars': '795', 'repo_language': 'None', 'file_name': 'index.md', 'mime_type': 'text/plain', 'hash': -1722339144609883512, 'source_dataset': 'data'}


/* eslint no-useless-call: "off" */

// Taken from: https://github.com/mathiasbynens/String.prototype.codePointAt
//             /blob/master/tests/tests.js

"use strict";

module.exports = function (t, a) {
	a(t.length, 1, "Length");

	// String that starts with a BMP symbol
	a(t.call("abc\uD834\uDF06def", ""), 0x61);
	a(t.call("abc\uD834\uDF06def", "_"), 0x61);
	a(t.call("abc\uD834\uDF06def"), 0x61);
	a(t.call("abc\uD834\uDF06def", -Infinity), undefined);
	a(t.call("abc\uD834\uDF06def", -1), undefined);
	a(t.call("abc\uD834\uDF06def", -0), 0x61);
	a(t.call("abc\uD834\uDF06def", 0), 0x61);
	a(t.call("abc\uD834\uDF06def", 3), 0x1d306);
	a(t.call("abc\uD834\uDF06def", 4), 0xdf06);
	a(t.call("abc\uD834\uDF06def", 5), 0x64);
	a(t.call("abc\uD834\uDF06def", 42), undefined);
	a(t.call("abc\uD834\uDF06def", Infinity), undefined);
	a(t.call("abc\uD834\uDF06def", Infinity), undefined);
	a(t.call("abc\uD834\uDF06def", NaN), 0x61);
	a(t.call("abc\uD834\uDF06def", false), 0x61);
	a(t.call("abc\uD834\uDF06def", null), 0x61);
	a(t.call("abc\uD834\uDF06def", undefined), 0x61);

	// String that starts with an astral symbol
	a(t.call("\uD834\uDF06def", ""), 0x1d306);
	a(t.call("\uD834\uDF06def", "1"), 0xdf06);
	a(t.call("\uD834\uDF06def", "_"), 0x1d306);
	a(t.call("\uD834\uDF06def"), 0x1d306);
	a(t.call("\uD834\uDF06def", -1), undefined);
	a(t.call("\uD834\uDF06def", -0), 0x1d306);
	a(t.call("\uD834\uDF06def", 0), 0x1d306);
	a(t.call("\uD834\uDF06def", 1), 0xdf06);
	a(t.call("\uD834\uDF06def", 42), undefined);
	a(t.call("\uD834\uDF06def", false), 0x1d306);
	a(t.call("\uD834\uDF06def", null), 0x1d306);
	a(t.call("\uD834\uDF06def", undefined), 0x1d306);

	// Lone high surrogates
	a(t.call("\uD834abc", ""), 0xd834);
	a(t.call("\uD834abc", "_"), 0xd834);
	a(t.call("\uD834abc"), 0xd834);
	a(t.call("\uD834abc", -1), undefined);
	a(t.call("\uD834abc", -0), 0xd834);
	a(t.call("\uD834abc", 0), 0xd834);
	a(t.call("\uD834abc", false), 0xd834);
	a(t.call("\uD834abc", NaN), 0xd834);
	a(t.call("\uD834abc", null), 0xd834);
	a(t.call("\uD834abc", undefined), 0xd834);

	// Lone low surrogates
	a(t.call("\uDF06abc", ""), 0xdf06);
	a(t.call("\uDF06abc", "_"), 0xdf06);
	a(t.call("\uDF06abc"), 0xdf06);
	a(t.call("\uDF06abc", -1), undefined);
	a(t.call("\uDF06abc", -0), 0xdf06);
	a(t.call("\uDF06abc", 0), 0xdf06);
	a(t.call("\uDF06abc", false), 0xdf06);
	a(t.call("\uDF06abc", NaN), 0xdf06);
	a(t.call("\uDF06abc", null), 0xdf06);
	a(t.call("\uDF06abc", undefined), 0xdf06);

	a.throws(function () {
		t.call(undefined);
	}, TypeError);
	a.throws(function () {
		t.call(undefined, 4);
	}, TypeError);
	a.throws(function () {
		t.call(null);
	}, TypeError);
	a.throws(function () {
		t.call(null, 4);
	}, TypeError);
	a(t.call(42, 0), 0x34);
	a(t.call(42, 1), 0x32);
	a(
		t.call(
			{
				toString: function () {
					return "abc";
				}
			},
			2
		),
		0x63
	);

	a.throws(function () {
		t.apply(undefined);
	}, TypeError);
	a.throws(function () {
		t.apply(undefined, [4]);
	}, TypeError);
	a.throws(function () {
		t.apply(null);
	}, TypeError);
	a.throws(function () {
		t.apply(null, [4]);
	}, TypeError);
	a(t.apply(42, [0]), 0x34);
	a(t.apply(42, [1]), 0x32);
	a(
		t.apply(
			{
				toString: function () {
					return "abc";
				}
			},
			[2]
		),
		0x63
	);
};

{'repo_name': 'TriumphLLC/Blend4Web', 'stars': '643', 'repo_language': 'HTML', 'file_name': 'README.md', 'mime_type': 'text/plain', 'hash': 2949490696643545294, 'source_dataset': 'data'}


from __future__ import print_function
from __future__ import division

import tensorflow as tf
import numpy as np
from data_reader import load_data, DataReader
from read_param_init import EMBEDDING

EMBEDDING = np.array([
 [-0.04020876, -0.04589647,  0.00793677],
 [ 0.03760753,  0.03413731, -0.01067527],
 [ 0.00799222,  0.0039931 ,  0.01654441],
 [-0.03427302, -0.01310955,  0.02258706],
 [ 0.01835312, -0.03909086,  0.04725415],
 [ 0.0025036 , -0.02406038, -0.02044987],
 [ 0.04297833,  0.00279194,  0.03238043],
 [-0.02025876, -0.0179657 , -0.03936036],
 [-0.00074947,  0.00352414, -0.02381919],
 [ 0.03299351, -0.00162511,  0.01352856],
 [ 0.04310675,  0.00617707, -0.04662617],
 [-0.01005498,  0.00885675, -0.00254586],
 [ 0.03250795, -0.04367134, -0.0116791 ],
 [-0.04569028,  0.01104799,  0.01585159],
 [ 0.0268481 ,  0.00737945, -0.00946116],
 [-0.03124694,  0.02487025,  0.03971596],
 [ 0.03792145, -0.01725978, -0.02407817],
 [-0.02003244, -0.00951287, -0.00884187],
 [ 0.01316513,  0.04699151,  0.00852467],
 [ 0.03358141,  0.04829691,  0.0272072 ],
 [-0.00243091, -0.02307724, -0.03919974],
 [ 0.0480135 , -0.00144688, -0.02563277],
 [-0.02597598,  0.0180791 , -0.03409653],
 [ 0.0370702 ,  0.03115036,  0.04093158],
 [-0.03747274, -0.04877437,  0.01241867],
 [-0.00797913,  0.00889203,  0.03531776],
 [ 0.04417486,  0.02585512,  0.0442488 ],
 [ 0.02102883, -0.00723729,  0.01269014],
 [ 0.01498469, -0.03097989, -0.00921361],
 [ 0.04569569, -0.03314942, -0.02747623],
 [ 0.00670947,  0.0469846 ,  0.01506192],
 [-0.0130407 , -0.01612713,  0.01080076],
 [-0.03228744, -0.0118084 , -0.04491826],
 [ 0.04447197, -0.03722177,  0.01440583],
 [-0.03368512,  0.01650865,  0.04841593],
 [ 0.0474678 ,  0.04903487,  0.02930588],
 [ 0.02360311,  0.01920362,  0.04889371],
 [-0.03173489,  0.004164  ,  0.03575457],
 [ 0.03728818, -0.0265135 ,  0.0295449 ],
 [ 0.03745138, -0.0125595 , -0.02958026],
 [-0.0137555 , -0.04032354, -0.04303581],
 [ 0.02996253, -0.01153379,  0.03671537],
 [-0.011293  ,  0.00767836, -0.03518059],
 [ 0.03063016, -0.04559553,  0.03217774],
 [ 0.03193897, -0.03499981,  0.03303108],
 [ 0.02886082, -0.00475057, -0.04592496],
 [-0.04590289, -0.03963085,  0.00179808],
 [-0.03074999, -0.02197887,  0.02568519],
 [-0.00450748, -0.03790166,  0.02786475],
 [-0.02376388,  0.00572333, -0.01082846],
 [ 0.01590927,  0.00220331,  0.00233858]
])
EMBEDDING[0,:] = 0.0

X = np.array([
 [[ 1,  3,  4,  5,  2,  0,  0,  0,  0,  0,  0],
  [ 1,  6,  3,  7,  8,  7,  9, 10,  4,  2,  0],
  [ 1,  6,  4,  5, 11, 12, 10, 13,  2,  0,  0]],

 [[ 1, 11,  4, 10,  2,  0,  0,  0,  0,  0,  0],
  [ 1, 10, 22,  4,  2,  0,  0,  0,  0,  0,  0],
  [ 1, 23,  9, 11, 11,  3,  5,  2,  0,  0,  0]],

 [[ 1,  9,  5,  2,  0,  0,  0,  0,  0,  0,  0],
  [ 1, 11,  9,  3,  7,  2,  0,  0,  0,  0,  0],
  [ 1, 10,  9,  2,  0,  0,  0,  0,  0,  0,  0]],

 [[ 1, 30,  2,  0,  0,  0,  0,  0,  0,  0,  0],
  [ 1, 30,  2,  0,  0,  0,  0,  0,  0,  0,  0],
  [ 1,  3,  7, 23,  2,  0,  0,  0,  0,  0,  0]]
], dtype=np.int32)

IE3 = np.array([
  [[ 0.03760753,  0.03413731, -0.01067527],
   [-0.03427302, -0.01310955,  0.02258706],
   [ 0.01835312, -0.03909086,  0.04725415],
   [ 0.0025036 , -0.02406038, -0.02044987],
   [ 0.00799222,  0.0039931 ,  0.01654441],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ]],

  [[ 0.03760753,  0.03413731, -0.01067527],
   [-0.01005498,  0.00885675, -0.00254586],
   [ 0.01835312, -0.03909086,  0.04725415],
   [ 0.04310675,  0.00617707, -0.04662617],
   [ 0.00799222,  0.0039931 ,  0.01654441],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ]],

  [[ 0.03760753,  0.03413731, -0.01067527],
   [ 0.03299351, -0.00162511,  0.01352856],
   [ 0.0025036 , -0.02406038, -0.02044987],
   [ 0.00799222,  0.0039931 ,  0.01654441],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ]],

  [[ 0.03760753,  0.03413731, -0.01067527],
   [ 0.00670947,  0.0469846 ,  0.01506192],
   [ 0.00799222,  0.0039931 ,  0.01654441],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        ]]

])

Y = np.array([[   2,    3,    4],
       [  32,  429, 7408],
       [3078,   64,   35],
       [  27,   48,  395]], dtype=np.int32)

class TestEmbedding(tf.test.TestCase):

    def test(self):

        batch_size = 4
        num_unroll_steps = 3
        char_vocab_size = 51
        max_word_length = 11
        char_embed_size = 3

        _, _, word_data, char_data, _ = load_data('data/', max_word_length)
        dataset = char_data['train']
        self.assertEqual(dataset.shape, (929589, max_word_length))

        reader = DataReader(word_data['train'], char_data['train'], batch_size=batch_size, num_unroll_steps=num_unroll_steps)
        for x, y in reader.iter():
            assert x.shape == (batch_size, num_unroll_steps, max_word_length)
            break

        self.assertAllClose(X, x)
        self.assertAllClose(Y, y)

        with self.test_session() as session:
            input_ = tf.placeholder(tf.int32, shape=[batch_size, num_unroll_steps, max_word_length], name="input")

            ''' First, embed characters '''
            with tf.variable_scope('Embedding'):
                char_embedding = tf.get_variable('char_embedding', [char_vocab_size, char_embed_size])

                # [batch_size x max_word_length, num_unroll_steps, char_embed_size]
                input_embedded = tf.nn.embedding_lookup(char_embedding, input_)

                input_embedded = tf.reshape(input_embedded, [-1, max_word_length, char_embed_size])

            session.run(tf.assign(char_embedding, EMBEDDING))
            ie = session.run(input_embedded, {
                input_: x
            })

            #print(x.shape)
            #print(np.transpose(x, (1, 0, 2)))
            #print(ie.shape)
            ie = ie.reshape([batch_size, num_unroll_steps, max_word_length, char_embed_size])
            ie = np.transpose(ie, (1, 0, 2, 3))
            #print(ie[0,:,:,:])

            self.assertAllClose(IE3, ie[0,:,:,:])

{'repo_name': 'mkroutikov/tf-lstm-char-cnn', 'stars': '217', 'repo_language': 'Python', 'file_name': 'train.txt', 'mime_type': 'text/plain', 'hash': -3544150919524559958, 'source_dataset': 'data'}


************************************************************
* For the very latest on DRI development, please see:      *
*     http://dri.freedesktop.org/                          *
************************************************************

The Direct Rendering Manager (drm) is a device-independent kernel-level
device driver that provides support for the XFree86 Direct Rendering
Infrastructure (DRI).

The DRM supports the Direct Rendering Infrastructure (DRI) in four major
ways:

    1. The DRM provides synchronized access to the graphics hardware via
       the use of an optimized two-tiered lock.

    2. The DRM enforces the DRI security policy for access to the graphics
       hardware by only allowing authenticated X11 clients access to
       restricted regions of memory.

    3. The DRM provides a generic DMA engine, complete with multiple
       queues and the ability to detect the need for an OpenGL context
       switch.

    4. The DRM is extensible via the use of small device-specific modules
       that rely extensively on the API exported by the DRM module.

Documentation on the DRI is available from:
    http://dri.freedesktop.org/wiki/Documentation
    http://sourceforge.net/project/showfiles.php?group_id=387
    http://dri.sourceforge.net/doc/

For specific information about kernel-level support, see:

    The Direct Rendering Manager, Kernel Support for the Direct Rendering
    Infrastructure
    http://dri.sourceforge.net/doc/drm_low_level.html

    Hardware Locking for the Direct Rendering Infrastructure
    http://dri.sourceforge.net/doc/hardware_locking_low_level.html

    A Security Analysis of the Direct Rendering Infrastructure
    http://dri.sourceforge.net/doc/security_low_level.html

{'repo_name': 'RMerl/asuswrt-merlin.ng', 'stars': '2126', 'repo_language': 'None', 'file_name': 'cpu_vect.h', 'mime_type': 'text/x-c', 'hash': -4892509142160051543, 'source_dataset': 'data'}


{'repo_name': 'unity3d-jp/RaytracedHardShadow', 'stars': '150', 'repo_language': 'C++', 'file_name': 'AudioManager.asset', 'mime_type': 'text/plain', 'hash': -8130962696253707341, 'source_dataset': 'data'}


/* global document window */

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import update from 'immutability-helper';
import { isBefore, addHours } from 'date-fns';
import queryString from 'query-string';

import * as HttpStatus from 'http-status-codes';

import { Meteor } from 'meteor/meteor';
import oorjaClient from 'imports/modules/oorjaClient';

import { RoomStorage } from 'imports/modules/room/storage';

import { Intent } from '@blueprintjs/core';
import Room from 'imports/ui/components/Room';

import PasswordPrompt from 'imports/ui/components/PasswordPrompt';
import toaster from '../../components/Toaster';

import MinimalLogo from '../../components/MinimalLogo';
import GettingReady from '../../components/Room/GettingReady';

import './door.scss';

const GENERIC_ERROR_MESSAGE = 'Something went wrong 😕';

class Door extends Component {
  constructor(props) {
    super(props);
    this.roomStorage = null;
    const { params: { roomName } } = this.props.match;
    this.roomName = roomName;
    this.roomSecret = queryString.parse(props.location.search).secret;

    this.stages = {
      LOADING: 'LOADING',
      PASSWORD_PROMPT: 'PASSWORD_PROMPT',
      GETTING_READY: 'GETTING_READY',
      SHOW_TIME: 'SHOW_TIME',
    };

    this.state = {
      roomName,
      roomInfo: null,
      stage: this.stages.LOADING,
      initialized: false,
      cleanRun: false,
    };

    this.setupTrackerToRefreshIfWakingFromSleep();
    this.stateBuffer = this.state;

    this.kick = this.kick.bind(this);
    this.setup = this.setup.bind(this);
    this.initialize = this.initialize.bind(this);
    this.handleRoomLookup = this.handleRoomLookup.bind(this);
    this.fetchRoomInfo = this.fetchRoomInfo.bind(this);
    this.enterRoom = this.enterRoom.bind(this);
    this.passwordSuccess = this.passwordSuccess.bind(this);
    this.onUnexpectedServerError = this.onUnexpectedServerError.bind(this);
    this.handleRoomFetchFailure = this.handleRoomFetchFailure.bind(this);
  }

  kick(message = GENERIC_ERROR_MESSAGE, intent = Intent.WARNING) {
    this.props.history.push('/');
    toaster.show({
      message,
      intent,
      timeout: 6000,
    });
  }

  setupTrackerToRefreshIfWakingFromSleep() {
    this.lastActiveTime = (new Date()).getTime();
    this.SleepTracker = setInterval(() => {
      const currentTime = (new Date()).getTime();
      if (currentTime > (this.lastActiveTime + 7500)) {
        // resumed from sleep ?
        if (Meteor.settings.public.refreshOnWake) window.location.reload();
      }
      this.lastActiveTime = currentTime;
    }, 3000); // check every 3 seconds
  }

  updateState(changes, buffer = this.stateBuffer) {
    this.stateBuffer = update(buffer, changes);
    this.setState(this.stateBuffer);
  }

  passwordSuccess() {
    this.roomAccessToken = this.roomStorage.getAccessToken();
    this.initialize();
  }

  handleRoomLookup(response) {
    const { status } = response;
    if (status !== HttpStatus.OK) {
      const errorMessage = status === HttpStatus.NOT_FOUND ?
        (

            ( ⚆ _ ⚆ ) Room not found.

            Please check the link or create a new room.

        ) : GENERIC_ERROR_MESSAGE;
      this.kick(errorMessage);
      return Promise.reject();
    }
    return response.data;
  }

  handleRoomFetchFailure() {
    // possible reasons
    // - could be that room link is faulty (invalid secret)
    // - tokens are faulty
    // do a clean run once, if not fixed redirect to /.
    if (!this.stateBuffer.cleanRun) {
      this.roomStorage.deleteRoomAccessToken();
      this.updateState({
        cleanRun: { $set: true },
      });
      this.setup();
      return;
    }

    toaster.show({
      message: 'Could not connect to room. Please check your link or try later',
      intent: Intent.WARNING,
      timeout: 7000,
    });
    this.props.history.push('/');
  }

  setup() {
    oorjaClient.lookupRoom(this.roomName)
      .then(this.handleRoomLookup, () => { this.kick(); return Promise.reject(); })
      .then((minimalRoomInfo) => {
        this.roomId = minimalRoomInfo._id;
        this.roomStorage = new RoomStorage(this.roomId);
        this.roomStorage.saveRoomSecret(this.roomSecret);
        this.roomAccessToken = this.roomStorage.getAccessToken();

        if (!minimalRoomInfo.passwordEnabled && !this.roomSecret) {
          this.kick(`Could not access room.
            Try to obtain a new link OR make a new room and invite others`);
          return Promise.reject();
        }

        if (minimalRoomInfo.passwordEnabled && !this.roomAccessToken) {
          toaster.show({
            message: 'This room is password protected (°ロ°)☝',
            intent: Intent.PRIMARY,
            timeout: 3000,
          });
          this.gotoStage(this.stages.PASSWORD_PROMPT);
          return Promise.resolve();
        }
        this.initialize();
        return Promise.resolve();
      });
  }

  fetchRoomInfo() {
    return oorjaClient.fetchRoom(this.roomId)
      .then((response) => {
        const { status } = response;
        if (status !== HttpStatus.OK) {
          this.handleRoomSubscriptionFailure();
          return Promise.reject();
        }
        const roomInfo = response.data;
        if (!roomInfo) {
          this.onUnexpectedServerError();
          return Promise.reject();
        }
        this.updateState({
          roomInfo: { $set: roomInfo },
        });
        return Promise.resolve(roomInfo);
      }, () => { this.handleRoomFetchFailure(); return Promise.reject(); });
  }

  initialize() {
    this.gotoStage(this.stages.LOADING);
    this.fetchRoomInfo()
      .then(() => {
        this.updateState({
          initialized: { $set: true },
        });
        oorjaClient.checkIfExistingUser(this.roomId)
          .then(
            () => {
              if (this.isRoomReady()) {
                this.gotoStage(this.stages.LOADING);
                this.enterRoom();
                return;
              }
              this.gotoStage(this.stages.GETTING_READY);
            },
            () => {
              this.roomStorage.deleteSavedUser();
              this.gotoStage(this.stages.GETTING_READY);
            },
          );
      });
  }

  componentWillMount() {
    document.body.classList.add('room-container');
    this.setup();
  }

  enterRoom() {
    oorjaClient.joinRoom(this.roomId)
      .then(this.fetchRoomInfo)
      .then(() => this.gotoStage(this.stages.SHOW_TIME), this.onUnexpectedServerError);
  }

  onUnexpectedServerError(message, intent = Intent.WARNING) {
    setTimeout(() => {
      toaster.show({
        message: message || 'Internal Server Error 🤕',
        intent: intent || Intent.DANGER,
        timeout: 8000,
      });
    }, 300);
    this.props.history.push('/');
  }

  isRoomReady() {
    const lastReadyTime = this.roomStorage.getLastReadyTime();
    if (!lastReadyTime) return false;
    // If the user setup his webcam and all a few hours ago, use those settings.
    return isBefore(new Date(), addHours(new Date(lastReadyTime), 4));
  }

  gotoStage(stage) {
    const { SHOW_TIME } = this.stages;

    // const previousStage = this.stateBuffer.stage;
    // action before switching to stage
    switch (stage) {
      case SHOW_TIME:
        this.roomStorage.saveLastReadyTime(new Date().toISOString());
        this.roomUserId = this.roomStorage.getUserId();
        this.roomUserToken = this.roomStorage.getUserToken();
        break;
      default: break;
    }

    this.updateState({
      stage: { $set: stage },
    });

    // Action after switching to stage.
    switch (stage) {
      default: break;
    }
  }

  componentWillUnmount() {
    document.body.classList.remove('room-container');
    // cleanup
    clearInterval(this.SleepTracker);
  }

  render() {
    const {
      LOADING, PASSWORD_PROMPT, GETTING_READY, SHOW_TIME,
    } = this.stages;
    switch (this.state.stage) {
      case LOADING:
        return (

              <MinimalLogo />

        );
      case PASSWORD_PROMPT:
        return <PasswordPrompt
                  roomId={this.roomId}
                  oorjaClient={oorjaClient}
                  roomName={this.roomName}
                  onSuccess={this.passwordSuccess}
                  toaster={toaster}
                />;
      case GETTING_READY:
        return <GettingReady
                  roomInfo={this.state.roomInfo}
                  onReady={this.enterRoom}
                  oorjaClient={oorjaClient}
                  toaster={toaster}
                  onUnexpectedServerError = {this.onUnexpectedServerError}
                  roomUserId={this.roomUserId}/>;
      case SHOW_TIME:
        return <Room
                  roomId={this.roomId}
                  roomInfo={this.state.roomInfo}
                  updateRoomInfo={this.fetchRoomInfo}
                  roomStorage={this.roomStorage}
                  toaster={toaster}
                  oorjaClient={oorjaClient}
                  roomUserId={this.roomUserId} />;
      default: return null;
    }
  }
}

Door.propTypes = {
  match: PropTypes.object.isRequired,
  history: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
};

export default Door;

{'repo_name': 'akshaykmr/oorja', 'stars': '261', 'repo_language': 'JavaScript', 'file_name': 'settings.json', 'mime_type': 'text/plain', 'hash': 4691297323621714957, 'source_dataset': 'data'}


###### i18n file in UTF-8 character encoding  #######################
forgotten-password-confirmation.pageTitle=Anweisungen sind geschickt worden
forgotten-password-confirmation.h1=Anweisungen sind geschickt worden
forgotten-password-confirmation.message=Anweisungen worden an <strong>{0}</strong> geschickt
forgotten-password-confirmation.backToLogin=Zurück zu Seite anmelden

{'repo_name': 'Asqatasun/Asqatasun', 'stars': '202', 'repo_language': 'Java', 'file_name': 'main.yml', 'mime_type': 'text/plain', 'hash': -8793277260052825775, 'source_dataset': 'data'}


package flags

import (
	"flag"
	"fmt"
	"strings"
)

// Ensure implements
var _ flag.Value = (*FlagMapValue)(nil)

// FlagMapValue is a flag implementation used to provide key=value semantics
// multiple times.
type FlagMapValue map[string]string

func (h *FlagMapValue) String() string {
	return fmt.Sprintf("%v", *h)
}

func (h *FlagMapValue) Set(value string) error {
	idx := strings.Index(value, "=")
	if idx == -1 {
		return fmt.Errorf("Missing \"=\" value in argument: %s", value)
	}

	key, value := value[0:idx], value[idx+1:]

	if *h == nil {
		*h = make(map[string]string)
	}

	headers := *h
	headers[key] = value
	*h = headers

	return nil
}

{'repo_name': 'mhausenblas/burry.sh', 'stars': '249', 'repo_language': 'Go', 'file_name': 'deploy.sh', 'mime_type': 'text/x-shellscript', 'hash': 5240743923700313547, 'source_dataset': 'data'}


/*******************************************************************************
 * Copyright (c) 2012 Pursuer (http://pursuer.me).
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 *
 * Contributors:
 *     Pursuer - initial API and implementation
 ******************************************************************************/

package com.pursuer.reader.easyrss.network;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.fasterxml.jackson.core.JsonParseException;
import com.pursuer.reader.easyrss.R;
import com.pursuer.reader.easyrss.data.DataMgr;
import com.pursuer.reader.easyrss.data.GoogleAnalyticsMgr;
import com.pursuer.reader.easyrss.data.Setting;
import com.pursuer.reader.easyrss.data.Subscription;
import com.pursuer.reader.easyrss.data.parser.OnSubscriptionRetrievedListener;
import com.pursuer.reader.easyrss.data.parser.SubscriptionJSONParser;
import com.pursuer.reader.easyrss.data.readersetting.SettingSyncInterval;
import com.pursuer.reader.easyrss.data.readersetting.SettingSyncMethod;
import com.pursuer.reader.easyrss.network.url.SubscriptionIconUrl;
import com.pursuer.reader.easyrss.network.url.SubscriptionListURL;

public class SubscriptionDataSyncer extends AbsDataSyncer {
    private class SyncerSubscriptionListener implements OnSubscriptionRetrievedListener {
        final private List<Subscription> subscriptions;

        public SyncerSubscriptionListener() {
            this.subscriptions = new LinkedList<Subscription>();
        }

        public List<Subscription> getSubscriptions() {
            return subscriptions;
        }

        public void onSubscriptionRetrieved(final Subscription sub) {
            subscriptions.add(sub);
        }
    }

    private static SubscriptionDataSyncer instance;

    private static synchronized void clearInstance() {
        instance = null;
    }

    public static synchronized SubscriptionDataSyncer getInstance(final DataMgr dataMgr, final int networkConfig) {
        if (instance == null) {
            instance = new SubscriptionDataSyncer(dataMgr, networkConfig);
        }
        return instance;
    }

    public static synchronized boolean hasInstance() {
        return instance != null;
    }

    private SubscriptionDataSyncer(final DataMgr dataMgr, final int networkConfig) {
        super(dataMgr, networkConfig);
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        } else {
            return (obj instanceof SubscriptionDataSyncer);
        }
    }

    @Override
    protected void finishSyncing() {
        clearInstance();
    }

    @Override
    public void startSyncing() throws DataSyncerException {
        final String sExpTime = dataMgr.getSettingByName(Setting.SETTING_SUBSCRIPTION_LIST_EXPIRE_TIME);
        if (networkConfig != SettingSyncMethod.SYNC_METHOD_MANUAL
                && sExpTime != null
                && Long.valueOf(sExpTime) + new SettingSyncInterval(dataMgr).toSeconds() * 1000 - 10 * 60 * 1000 > System
                        .currentTimeMillis()) {
            return;
        }

        syncSubscriptions();
        syncSubscriptionIcons();

        dataMgr.updateSetting(new Setting(Setting.SETTING_SUBSCRIPTION_LIST_EXPIRE_TIME, System.currentTimeMillis()));
    }

    private void syncSubscriptionIcons() throws DataSyncerException {
        final Context context = dataMgr.getContext();
        if (!NetworkUtils.checkSyncingNetworkStatus(context, networkConfig)) {
            return;
        }
        final ContentResolver resolver = context.getContentResolver();
        final Cursor cur = resolver.query(Subscription.CONTENT_URI, new String[] { Subscription._UID,
                Subscription._ICON, Subscription._URL }, null, null, null);
        for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
            final String uid = cur.getString(0);
            final byte[] data = cur.getBlob(1);
            final String subUrl = cur.getString(2);
            if (subUrl != null && data == null) {
                final SubscriptionIconUrl fetchUrl = new SubscriptionIconUrl(isHttpsConnection, subUrl);
                try {
                    final byte[] iconData = httpGetQueryByte(fetchUrl);
                    final Bitmap icon = BitmapFactory.decodeByteArray(iconData, 0, iconData.length);
                    final int size = icon.getWidth() * icon.getHeight() * 2;
                    final ByteArrayOutputStream output = new ByteArrayOutputStream(size);
                    icon.compress(Bitmap.CompressFormat.PNG, 100, output);
                    output.flush();
                    output.close();
                    dataMgr.updateSubscriptionIconByUid(uid, output.toByteArray());
                } catch (final IOException exception) {
                    cur.close();
                    throw new DataSyncerException(exception);
                }
            }
        }
        cur.close();
    }

    private void syncSubscriptions() throws DataSyncerException {
        final Context context = dataMgr.getContext();
        if (!NetworkUtils.checkSyncingNetworkStatus(context, networkConfig)) {
            return;
        }
        notifyProgressChanged(context.getString(R.string.TxtSyncingSubscriptions), -1, -1);

        final InputStream stream = httpGetQueryStream(new SubscriptionListURL(isHttpsConnection));
        final SubscriptionJSONParser parser = new SubscriptionJSONParser(stream);
        final long curTime = System.currentTimeMillis();
        try {
            final SyncerSubscriptionListener listener = new SyncerSubscriptionListener();
            parser.parse(listener);
            dataMgr.addSubscriptions(listener.getSubscriptions());
            final int sAll = listener.getSubscriptions().size();
            final int sAllRange = sAll / 10 * 10;
            GoogleAnalyticsMgr.getInstance().trackEvent(GoogleAnalyticsMgr.CATEGORY_SYNCING,
                    GoogleAnalyticsMgr.ACTION_SYNCING_SUBSCRIPTIONS, sAllRange + "-" + (sAllRange + 9), sAll);
        } catch (final JsonParseException exception) {
            throw new DataSyncerException(exception);
        } catch (final IllegalStateException exception) {
            throw new DataSyncerException(exception);
        } catch (final IOException exception) {
            throw new DataSyncerException(exception);
        } finally {
            try {
                stream.close();
            } catch (final IOException exception) {
                exception.printStackTrace();
            }
        }
        dataMgr.removeOutdatedSubscriptions(curTime);
    }
}

{'repo_name': 'davidsun/EasyRSS', 'stars': '136', 'repo_language': 'Makefile', 'file_name': 'com.google.gwt.eclipse.core.prefs', 'mime_type': 'text/plain', 'hash': 8773507315194862178, 'source_dataset': 'data'}