text:
import ctypes
import struct
import unittest
import logging
import time
import mock

from subprocess import Popen
from os import path, kill
import snap7
from snap7.snap7exceptions import Snap7Exception
from snap7.snap7types import S7AreaDB, S7WLByte, S7DataItem
from snap7 import util

logging.basicConfig(level=logging.WARNING)

ip = '127.0.0.1'
tcpport = 1102
db_number = 1
rack = 1
slot = 1

class TestClient(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        server_path = path.join(path.dirname(path.realpath(snap7.__file__)),
                                "bin/snap7-server.py")
        cls.server_pid = Popen([server_path]).pid
        time.sleep(2)  # wait for server to start

    @classmethod
    def tearDownClass(cls):
        kill(cls.server_pid, 1)

    def setUp(self):
        self.client = snap7.client.Client()
        self.client.connect(ip, rack, slot, tcpport)

    def tearDown(self):
        self.client.disconnect()
        self.client.destroy()

    def test_db_read(self):
        size = 40
        start = 0
        db = 1
        data = bytearray(40)
        self.client.db_write(db_number=db, start=start, data=data)
        result = self.client.db_read(db_number=db, start=start, size=size)
        self.assertEqual(data, result)

    def test_db_write(self):
        size = 40
        data = bytearray(size)
        self.client.db_write(db_number=1, start=0, data=data)

    def test_db_get(self):
        self.client.db_get(db_number=db_number)

    def test_read_multi_vars(self):
        db = 1

        # build and write test values
        test_value_1 = 129.5
        test_bytes_1 = bytearray(struct.pack('>f', test_value_1))
        self.client.db_write(db, 0, test_bytes_1)

        test_value_2 = -129.5
        test_bytes_2 = bytearray(struct.pack('>f', test_value_2))
        self.client.db_write(db, 4, test_bytes_2)

        test_value_3 = 123
        test_bytes_3 = bytearray([0, 0])
        util.set_int(test_bytes_3, 0, test_value_3)
        self.client.db_write(db, 8, test_bytes_3)

        test_values = [test_value_1, test_value_2, test_value_3]

        # build up our requests
        data_items = (S7DataItem * 3)()

        data_items[0].Area = ctypes.c_int32(S7AreaDB)
        data_items[0].WordLen = ctypes.c_int32(S7WLByte)
        data_items[0].Result = ctypes.c_int32(0)
        data_items[0].DBNumber = ctypes.c_int32(db)
        data_items[0].Start = ctypes.c_int32(0)
        data_items[0].Amount = ctypes.c_int32(4)  # reading a REAL, 4 bytes

        data_items[1].Area = ctypes.c_int32(S7AreaDB)
        data_items[1].WordLen = ctypes.c_int32(S7WLByte)
        data_items[1].Result = ctypes.c_int32(0)
        data_items[1].DBNumber = ctypes.c_int32(db)
        data_items[1].Start = ctypes.c_int32(4)
        data_items[1].Amount = ctypes.c_int32(4)  # reading a REAL, 4 bytes

        data_items[2].Area = ctypes.c_int32(S7AreaDB)
        data_items[2].WordLen = ctypes.c_int32(S7WLByte)
        data_items[2].Result = ctypes.c_int32(0)
        data_items[2].DBNumber = ctypes.c_int32(db)
        data_items[2].Start = ctypes.c_int32(8)
        data_items[2].Amount = ctypes.c_int32(2)  # reading an INT, 2 bytes

        # create buffers to receive the data
        # use the Amount attribute on each item to size the buffer
        for di in data_items:
            # create the buffer
            dataBuffer = ctypes.create_string_buffer(di.Amount)
            # get a pointer to the buffer
            pBuffer = ctypes.cast(ctypes.pointer(dataBuffer),
                                  ctypes.POINTER(ctypes.c_uint8))
            di.pData = pBuffer

        result, data_items = self.client.read_multi_vars(data_items)

        result_values = []
        # function to cast bytes to match data_types[] above
        byte_to_value = [util.get_real, util.get_real, util.get_int]

        # unpack and test the result of each read
        for i in range(0, len(data_items)):
            btv = byte_to_value[i]
            di = data_items[i]
            value = btv(di.pData, 0)
            result_values.append(value)

        self.assertEqual(result_values[0], test_values[0])
        self.assertEqual(result_values[1], test_values[1])
        self.assertEqual(result_values[2], test_values[2])

    def test_upload(self):
        """
        this raises an exception due to missing authorization? maybe not
        implemented in server emulator
        """
        self.assertRaises(Snap7Exception, self.client.upload, db_number)

    @unittest.skip("TODO: invalid block size")
    def test_download(self):
        data = bytearray(1024)
        self.client.download(block_num=db_number, data=data)

    def test_read_area(self):
        area = snap7.snap7types.areas.DB
        dbnumber = 1
        amount = 1
        start = 1
        self.client.read_area(area, dbnumber, start, amount)

    def test_write_area(self):
        area = snap7.snap7types.areas.DB
        dbnumber = 1
        size = 1
        start = 1
        data = bytearray(size)
        self.client.write_area(area, dbnumber, start, data)

    def test_list_blocks(self):
        blockList = self.client.list_blocks()

    def test_list_blocks_of_type(self):
        self.client.list_blocks_of_type('DB', 10)

        self.assertRaises(Exception, self.client.list_blocks_of_type,
                          'NOblocktype', 10)

    def test_get_block_info(self):
        """test Cli_GetAgBlockInfo"""
        self.client.get_block_info('DB', 1)

        self.assertRaises(Exception, self.client.get_block_info,
                          'NOblocktype', 10)
        self.assertRaises(Exception, self.client.get_block_info, 'DB', 10)

    def test_get_cpu_state(self):
        """this tests the get_cpu_state function"""
        self.client.get_cpu_state()

    def test_set_session_password(self):
        password = 'abcdefgh'
        self.client.set_session_password(password)

    def test_clear_session_password(self):
        self.client.clear_session_password()

    def test_set_connection_params(self):
        self.client.set_connection_params("10.0.0.2", 10, 10)

    def test_set_connection_type(self):
        self.client.set_connection_type(1)
        self.client.set_connection_type(2)
        self.client.set_connection_type(3)
        self.client.set_connection_type(20)

    def test_get_connected(self):
        self.client.get_connected()

    def test_ab_read(self):
        start = 1
        size = 1
        data = bytearray(size)
        self.client.ab_write(start=start, data=data)
        self.client.ab_read(start=start, size=size)

    @unittest.skip("TODO: crash client: FATAL: exception not rethrown")
    def test_ab_write(self):
        start = 1
        size = 10
        data = bytearray(size)
        self.client.ab_write(start=start, data=data)

    @unittest.skip("TODO: crash client: FATAL: exception not rethrown")
    def test_as_ab_read(self):
        start = 1
        size = 1
        self.client.as_ab_read(start=start, size=size)

    @unittest.skip("TODO: not yet fully implemented")
    def test_as_ab_write(self):
        start = 1
        size = 10
        data = bytearray(size)
        self.client.as_ab_write(start=start, data=data)

    def test_compress(self):
        time = 1000
        self.client.compress(time)

    def test_as_compress(self):
        time = 1000
        self.client.as_compress(time)

    def test_set_param(self):
        values = (
            (snap7.snap7types.PingTimeout, 800),
            (snap7.snap7types.SendTimeout, 15),
            (snap7.snap7types.RecvTimeout, 3500),
            (snap7.snap7types.SrcRef, 128),
            (snap7.snap7types.DstRef, 128),
            (snap7.snap7types.SrcTSap, 128),
            (snap7.snap7types.PDURequest, 470),
        )
        for param, value in values:
            self.client.set_param(param, value)

        self.assertRaises(Exception, self.client.set_param,
                          snap7.snap7types.RemotePort, 1)

    def test_get_param(self):
        expected = (
            (snap7.snap7types.RemotePort, tcpport),
            (snap7.snap7types.PingTimeout, 750),
            (snap7.snap7types.SendTimeout, 10),
            (snap7.snap7types.RecvTimeout, 3000),
            (snap7.snap7types.SrcRef, 256),
            (snap7.snap7types.DstRef, 0),
            (snap7.snap7types.SrcTSap, 256),
            (snap7.snap7types.PDURequest, 480),
        )
        for param, value in expected:
            self.assertEqual(self.client.get_param(param), value)

        non_client = snap7.snap7types.LocalPort, snap7.snap7types.WorkInterval,\
            snap7.snap7types.MaxClients, snap7.snap7types.BSendTimeout,\
            snap7.snap7types.BRecvTimeout, snap7.snap7types.RecoveryTime,\
            snap7.snap7types.KeepAliveTime

        # invalid param for client
        for param in non_client:
            self.assertRaises(Exception, self.client.get_param,  non_client)

    @unittest.skip("TODO: not yet fully implemented")
    def test_as_copy_ram_to_rom(self):
        self.client.copy_ram_to_rom()

    @unittest.skip("TODO: not yet fully implemented")
    def test_as_ct_read(self):
        self.client.as_ct_read()

    @unittest.skip("TODO: not yet fully implemented")
    def test_as_ct_write(self):
        self.client.as_ct_write()

    @unittest.skip("TODO: not yet fully implemented")
    def test_as_db_fill(self):
        self.client.as_db_fill()

    def test_as_db_get(self):
        self.client.db_get(db_number=db_number)

    @unittest.skip("TODO: crash client: FATAL: exception not rethrown")
    def test_as_db_read(self):
        size = 40
        start = 0
        db = 1
        data = bytearray(40)
        self.client.db_write(db_number=db, start=start, data=data)
        result = self.client.as_db_read(db_number=db, start=start, size=size)
        self.assertEqual(data, result)

    @unittest.skip("TODO: crash client: FATAL: exception not rethrown")
    def test_as_db_write(self):
        size = 40
        data = bytearray(size)
        self.client.as_db_write(db_number=1, start=0, data=data)

    def test_as_download(self):
        data = bytearray(128)
        self.client.as_download(block_num=-1, data=data)

    def test_plc_stop(self):
        self.client.plc_stop()

    def test_plc_hot_start(self):
        self.client.plc_hot_start()

    def test_plc_cold_start(self):
        self.client.plc_cold_start()

    def test_get_pdu_length(self):
        pduRequested = self.client.get_param(10)
        pduSize = self.client.get_pdu_length()
        self.assertEqual(pduSize, pduRequested)

    def test_get_cpu_info(self):
        expected = (
            ('ModuleTypeName', 'CPU 315-2 PN/DP'),
            ('SerialNumber', 'S C-C2UR28922012'),
            ('ASName', 'SNAP7-SERVER'),
            ('Copyright', 'Original Siemens Equipment'),
            ('ModuleName', 'CPU 315-2 PN/DP')
        )
        cpuInfo = self.client.get_cpu_info()
        for param, value in expected:
            self.assertEqual(getattr(cpuInfo, param).decode('utf-8'), value)

class TestClientBeforeConnect(unittest.TestCase):
    """
    Test suite of items that should run without an open connection.
    """
    def setUp(self):
        self.client = snap7.client.Client()

    def test_set_param(self):
        values = (
            (snap7.snap7types.RemotePort, 1102),
            (snap7.snap7types.PingTimeout, 800),
            (snap7.snap7types.SendTimeout, 15),
            (snap7.snap7types.RecvTimeout, 3500),
            (snap7.snap7types.SrcRef, 128),
            (snap7.snap7types.DstRef, 128),
            (snap7.snap7types.SrcTSap, 128),
            (snap7.snap7types.PDURequest, 470),
        )
        for param, value in values:
            self.client.set_param(param, value)

class TestLibraryIntegration(unittest.TestCase):
    def setUp(self):
        # replace the function load_library with a mock
        self.loadlib_patch = mock.patch('snap7.client.load_library')
        self.loadlib_func = self.loadlib_patch.start()

        # have load_library return another mock
        self.mocklib = mock.MagicMock()
        self.loadlib_func.return_value = self.mocklib

        # have the Cli_Create of the mock return None
        self.mocklib.Cli_Create.return_value = None

    def tearDown(self):
        # restore load_library
        self.loadlib_patch.stop()

    def test_create(self):
        client = snap7.client.Client()
        self.mocklib.Cli_Create.assert_called_once()

    def test_gc(self):
        client = snap7.client.Client()
        del client
        self.mocklib.Cli_Destroy.assert_called_once()

if __name__ == '__main__':
    unittest.main()

# TODO: implement
"""
Cli_AsEBRead
Cli_AsEBWrite
Cli_AsFullUpload
Cli_AsListBlocksOfType
Cli_AsMBRead
Cli_AsMBWrite
Cli_AsReadArea
Cli_AsReadSZL
Cli_AsReadSZLList
Cli_AsTMRead
Cli_AsTMWrite
Cli_AsUpload
Cli_AsWriteArea
Cli_CheckAsCompletion
Cli_Connect
Cli_CopyRamToRom
Cli_CTRead
Cli_CTWrite
Cli_DBFill
Cli_Delete
Cli_EBRead
Cli_EBWrite
Cli_ErrorText
Cli_FullUpload
Cli_GetAgBlockInfo
Cli_GetCpInfo
Cli_GetExecTime
Cli_GetLastError
Cli_GetOrderCode
Cli_GetParam
Cli_GetPduLength
Cli_GetPgBlockInfo
Cli_GetPlcDateTime
Cli_GetPlcStatus
Cli_GetProtection
Cli_IsoExchangeBuffer
Cli_MBRead
Cli_MBWrite
Cli_ReadArea
Cli_ReadMultiVars
Cli_ReadSZL
Cli_ReadSZLList
Cli_SetAsCallback
Cli_SetParam
Cli_SetPlcDateTime
Cli_SetPlcSystemDateTime
Cli_SetSessionPassword
Cli_TMRead
Cli_TMWrite
Cli_WaitAsCompletion
Cli_WriteMultiVars
"""


text:
"""
Import API gateway definition

Usage:
  env init from <environment> <new-env>
  env render project <environment> [--tfstate=<file>] [<workdir>]
  env write project <environment> [--tfstate=<file>] [<workdir>]
  env link --environment=<string> [<workdir>]
  env render template [--tfstate=<file>] [--tfvars=<file>...] <template>...
  env write template --file=<file> [--tfstate=<file>] [--tfvars=<file>...] <template>...
  env import api [--tfstate=<file>] [--tfvars=<file>...] <template>...
  env render api [--tfstate=<file>] [--tfvars=<file>...] <template>...
  env add permissions <function> [<service>]
"""
import os, sys

script_dir = os.path.dirname( os.path.realpath(__file__) )
sys.path.insert(0, script_dir + os.sep + "lib")

import common as c
from docopt import docopt

import boto3, getpass, uuid

def read_first_existing(*files):
	for f in files:
		if os.path.exists(f):
			try:
				return c.read_json(f)
			except ValueError:
				pass
	raise IOError("Cannot find any of " + files)

def link(environment, target):
	dest = os.path.join(os.getcwd(), 'infrastructure', target)
	if not os.path.isdir(dest):
		source = os.path.join(os.getcwd(), 'infrastructure', environment)
		if os.path.islink(source):
			source = os.path.realpath(source)
		print "Creating symlink: " + dest
		os.symlink(source, dest)

def render_project_json(project, tfstate):
	if len( tfstate ):
		role = tfstate['apex_function_role']
		if role:
			project['role'] = role
		project = c.deep_merge(project, {"environment": tfstate})
	return c.to_json(project, False)

def read_tfvars(files, tfvars={}):
	for file in files:
		t = c.read_shlex(file)
		tfvars = c.deep_merge(tfvars, t)
	return tfvars

args = docopt(__doc__)
workdir = args.get('<workdir>') or os.getcwd()
environment = args.get('<environment>')
templates = args.get('<template>')

tfstate = {}
tfvars = read_tfvars( args.get('--tfvars') or [] )
if args.get('--tfstate'):
	tfstate = c.get_tfstate_f_outputs( args.get('--tfstate') )
params = c.deep_merge(tfstate, tfvars)

profile = os.getenv('AWS_PROFILE', 'default')
session = boto3.Session(profile_name=profile)

if args.get('init') and args.get('from'):
	target = args['<new-env>']
	link(environment, target)
	json =  read_first_existing(
		os.path.join(workdir, "project." + environment + ".json"),
		os.path.join(workdir, "project.json")
	)
	text = render_project_json(json, tfstate)
	c.write_file("project." + target + ".json", text)

if args.get('link'):
	link(environment, workdir)
	json = render_project_json(tfstate)

if args.get('project'):
	json =  read_first_existing(
		os.path.join(workdir, "project." + environment + ".json"),
		os.path.join(workdir, "project.json")
	)
	text = render_project_json(json, tfstate)
	if args.get('render'):
		print text
	if args.get('write'):
		c.write_file("project." + environment + ".json", text)

if args.get('template'):
	merge  = len(templates) > 1
	output = 'json' if len(templates) > 1 else 'text'
	text   = c.render_templates(templates,
								params=params,
								merge=merge,
								output=outt)
	if args.get('render'):
		print text
	if args.get('write'):
		c.write_file( args["--file"], text)

if args.get('api'):
	payload = c.render_templates(templates,
								 params=params,
								 merge=True,
								 output='json',
								 minify=False)
	if args.get('render'):
		print payload

	if args.get('import'):
		client  = session.client('apigateway')
		client.put_rest_api(
			failOnWarnings=False,
			restApiId=params['api_gateway_id'],
			mode='merge',
			body=str.encode(payload)
		)
		client.create_deployment(
			restApiId=params['api_gateway_id'],
			stageName=params['api_gateway_stage']
		)
		print 'done'

if args.get('add') and args.get('permissions'):
	function_name = 'serverless_{}_{}'.format(os.environ['ENV'], args['<function>'])
	service = args.get('<service>') or 'apigateway'
	lambda_client = session.client('lambda')
	print lambda_client.add_permission(
		FunctionName=function_name,
		StatementId=uuid.uuid4().hex,
		Action='lambda:InvokeFunction',
		Principal="{}.amazonaws.com".format(service)
			# SourceArn='string'
	)

if args.get('invalidate') and args.get('cache'):

  path = args['<path>'] if len(args['<path>']) else ['/*']

  client  = session.client('cloudfront')

  ref     = "evict " + str(path) + " by " + getpass.getuser()
  cloudfront = tfstate.get('cloudfront_id')
  print "Invalidate cache " + cloudfront + " with: " + ref

  print client.create_invalidation(
    DistributionId=cloudfront,
    InvalidationBatch={
        'Paths': {
            'Quantity': len(path),
            'Items': path
        },
        'CallerReference': ref
    }
)

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:core="http://www.milyn.org/xsd/smooks/smooks-core-1.4.xsd"
    xmlns:json="http://www.milyn.org/xsd/smooks/json-1.1.xsd"
    xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.2.xsd"
    xsi:schemaLocation="http://www.milyn.org/xsd/smooks-1.1.xsd http://www.milyn.org/xsd/smooks-1.1.xsd
        http://www.milyn.org/xsd/smooks/json-1.1.xsd http://www.milyn.org/xsd/smooks/json-1.1.xsd
        http://www.milyn.org/xsd/smooks/smooks-core-1.4.xsd http://www.milyn.org/xsd/smooks/smooks-core-1.4.xsd
        http://www.milyn.org/xsd/smooks/javabean-1.2.xsd http://www.milyn.org/xsd/smooks/javabean-1.2.xsd">

  <json:reader rootName="json" />

  <core:filterSettings type="SAX" readerPoolSize="5" />

  <jb:bean beanId="competencyLevelDescriptors" class="java.util.ArrayList" createOnElement="#document">
      <jb:wiring beanIdRef="competencyLevelDescriptor" />
  </jb:bean>

  <jb:bean beanId="competencyLevelDescriptor" class="org.slc.sli.ingestion.transformation.SimpleEntity" createOnElement="json">
    <jb:expression property="type">'competencyLevelDescriptor'</jb:expression>
    <jb:wiring property="body" beanIdRef="competencyLevelDescriptorBody" />
  </jb:bean>

  <jb:bean beanId="competencyLevelDescriptorBody" class="java.util.HashMap" createOnElement="attributes">
    <jb:value property="codeValue" data="attributes CodeValue _value" />
    <jb:value property="description" data="attributes Description _value"/>
    <jb:value property="performanceBaseConversion" data="attributes PerformanceBaseConversion _value" />
  </jb:bean>

</smooks-resource-list>


text:
import {Component} from '@angular/core';
import {DialogComponent, DialogService} from 'ng2-bootstrap-modal';
import {BlockParameter} from '../block-parameter';

export interface ParametersModal {
  parameters: Array<BlockParameter<any>>
}

@Component({
  selector: 'app-parameters-modal',
  templateUrl: './parameters-modal.component.html',
  styleUrls: ['./parameters-modal.component.scss']
})
export class ParametersModalComponent extends DialogComponent<ParametersModal, Array<BlockParameter<any>>> implements ParametersModal {

  parameters: Array<BlockParameter<any>>;

  constructor(dialogService: DialogService) {
    super(dialogService);
  }

  confirm() {
    this.result = this.parameters;
    this.close();
  }

  parameterValueChanged(event) {
    const p = event as BlockParameter<any>;
    this.deleteDependenciesIfNeeded(p);
    this.replaceOldParameterValue(p);
    this.addDependenciesIfNeeded(p);
  }

  private replaceOldParameterValue(newParameter: BlockParameter<any>) {
    this.parameters.filter(p => p.equals(newParameter)).forEach(p => p.value = newParameter.value);
  }

  private deleteDependenciesIfNeeded(p: BlockParameter<any>) {
    if (p.htmlType === 'select') {
      const oldParamValue = this.parameters.filter(p2 => p2.equals(p))[0].value;
      if (oldParamValue.dependencies !== undefined && oldParamValue.dependencies !== null) {
        oldParamValue.dependencies.forEach(d => {
          if (d.htmlType === 'option') {
            d.dependencies.forEach(dd => {
              this.parameters.splice(this.parameters.indexOf(dd), 1)
            });
          } else {
            this.parameters.splice(this.parameters.indexOf(d), 1)
          }
        });
      }
    }
  }

  private addDependenciesIfNeeded(p: BlockParameter<any>) {
    if (p.htmlType === 'select') {
      if (p.value.dependencies !== null && p.value.dependencies !== undefined) {
        p.value.dependencies.forEach(d => {
          if (d.htmlType === 'option') {
            d.dependencies.forEach(dd => this.parameters.push(dd));
          } else {
            this.parameters.push(d);
          }
        });
      }
    }
  }
}


text:
<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param array $data
     *
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        $data = $this->filterArray($data);

        return Validator::make($data, [
            'id'   => 'required|integer|max:9999999|min:1000000|unique:users|exists:user_registration_requests,id',
            'code' => [
                'required',
                'max:17',
                'min:17',
                'regex:/^[A-Z0-9]{5,5}-[A-Z0-9]{5,5}-[A-Z0-9]{5,5}$/',
                Rule::exists('user_registration_requests')
                    ->where('id', $data['id'])
                    ->where('code', $data['code']),
            ],
            'first_name'  => 'required|regex:/^\b[a-z\s-]+\b$/i|max:255',
            'middle_name' => 'regex:/^\b[a-z\s-]+\b$/i|max:255',
            'last_name'   => 'required|regex:/^\b[a-z\s-]+\b$/i|max:255',
            'email'       => 'required|email|max:255|unique:users',
            'password'    => 'required|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param array $data
     *
     * @return User
     */
    protected function create(array $data)
    {
        $data = $this->filterArray($data);

        return User::create([
            'id'        => $data['id'],
            'fname'     => $data['first_name'],
            'mname'     => $data['middle_name'],
            'lname'     => $data['last_name'],
            'email'     => $data['email'],
            'password'  => bcrypt($data['password']),
            'api_token' => str_random(60),
        ]);
    }

    private function filterArray(array $data)
    {
        $data['first_name']  = $this->formatData($data['first_name']);
        $data['middle_name'] = $this->formatData($data['middle_name']);
        $data['last_name']   = $this->formatData($data['last_name']);
        $data['code']        = strtoupper(trim($data['code']));

        return $data;
    }

    private function formatData($data)
    {
        $regexrep = [
            '/\s+/'     => ' ',
            '/-+/'      => '-',
            '/\s?-\s?/' => '-',
        ];

        return ucwords(strtolower(preg_replace(array_keys($regexrep), array_values($regexrep), trim($data))));
    }
}


text:
/* global describe, beforeEach, afterEach, context, it, expect, Erizo, sinon */

/* eslint-disable no-unused-expressions */

function promisify(func) {
  return new Promise((resolve) => {
    func((...args) => {
      resolve(...args);
    });
  });
}

describe('Room', () => {
  let room;
  let io;
  let connectionHelpers;
  let connectionManager;
  let socket;

  beforeEach(() => {
    Erizo.Logger.setLogLevel(Erizo.Logger.NONE);
    socket = {
      io: { engine: { transport: { ws: { onclose: sinon.stub() } } } },
      on: sinon.stub(),
      removeListener: sinon.stub(),
      emit: sinon.stub(),
      disconnect: sinon.stub(),
    };
    io = {
      connect: sinon.stub().returns(socket),
    };
    connectionHelpers = {
      getBrowser: sinon.stub(),
    };
    connectionManager = { ErizoConnectionManager: Erizo._.ErizoConnectionManager };
  });

  afterEach(() => {
  });

  it('should connect to ErizoController', async () => {
    const data = {
      tokenId: 'arbitraryId',
    };
    const spec = { token: Erizo._.Base64.encodeBase64(JSON.stringify(data)) };
    room = Erizo._.Room(io, connectionHelpers, connectionManager, spec);
    room.connect({});
    const promise = promisify(room.on.bind(null, 'room-connected'));
    const response = {
      id: 'arbitraryRoomId',
      clientId: 'arbitraryClientId',
      streams: [],
    };
    socket.on.withArgs('connected').callArgWith(1, response);

    const roomEvent = await promise;
    expect(roomEvent.type).to.equals('room-connected');
    expect(roomEvent.streams.length).to.equals(0);
  });

  context('Room connected', () => {
    const arbitraryStream = {
      id: 'arbitraryStreamId',
      audio: true,
      video: true,
      data: true,
      label: 'arbitraryStreamId',
      screen: false,
      attributes: [],
    };

    beforeEach(async () => {
      const data = {
        tokenId: 'arbitraryId',
      };
      const spec = { token: Erizo._.Base64.encodeBase64(JSON.stringify(data)) };
      room = Erizo._.Room(io, connectionHelpers, connectionManager, spec);
      room.connect({});
      const promise = promisify(room.on.bind(null, 'room-connected'));
      const response = {
        id: 'arbitraryRoomId',
        clientId: 'arbitraryClientId',
        streams: [],
      };
      socket.on.withArgs('connected').callArgWith(1, response);

      await promise;
    });

    it('should trigger new streams created', async () => {
      const promise = promisify(room.on.bind(null, 'stream-added'));
      socket.on.withArgs('onAddStream').callArgWith(1, arbitraryStream);
      const streamEvent = await promise;
      const stream = streamEvent.stream;
      expect(stream.getID()).to.equal(arbitraryStream.id);
    });

    it('should trigger new streams deleted', async () => {
      const promise = promisify(room.on.bind(null, 'stream-removed'));
      socket.on.withArgs('onAddStream').callArgWith(1, arbitraryStream);
      socket.on.withArgs('onRemoveStream').callArgWith(1, arbitraryStream);
      const streamEvent = await promise;
      const stream = streamEvent.stream;
      expect(stream.getID()).to.equal(arbitraryStream.id);
    });

    it('should subscribe to new streams', async () => {
      const promise = promisify(room.on.bind(null, 'stream-added'));
      socket.on.withArgs('onAddStream').callArgWith(1, arbitraryStream);
      const streamEvent = await promise;
      const stream = streamEvent.stream;

      room.subscribe(stream);

      const result = 'arbitraryResult';
      const erizoId = 'arbitraryErizoId';
      const connectionId = 'arbitraryConnectionId';
      const error = null;

      const data = socket.emit.withArgs('subscribe').args[0][1].msg;
      expect(data.options.streamId).to.equal(arbitraryStream.id);
      expect(stream.state).to.equal('subscribing');

      socket.emit.withArgs('subscribe').args[0][2](result, erizoId, connectionId, error);
      stream.dispatchEvent(Erizo.StreamEvent({ type: 'added', stream }));
      expect(stream.state).to.equal('subscribed');
    });

    it.skip('should resubscribe to new streams', async () => {
      const promise = promisify(room.on.bind(null, 'stream-added'));
      socket.on.withArgs('onAddStream').callArgWith(1, arbitraryStream);
      const streamEvent = await promise;
      const stream = streamEvent.stream;

      room.subscribe(stream);

      const result = 'arbitraryResult';
      const erizoId = 'arbitraryErizoId';
      const connectionId = 'arbitraryConnectionId';
      const error = null;

      const data = socket.emit.withArgs('subscribe').args[0][1].msg;
      expect(data.options.streamId).to.equal(arbitraryStream.id);
      expect(stream.state).to.equal('subscribing');

      socket.emit.withArgs('subscribe').args[0][2](result, erizoId, connectionId, error);

      room.unsubscribe(stream);

      expect(stream.state).to.equal('unsubscribing');
      stream.dispatchEvent(Erizo.StreamEvent({ type: 'added', stream }));
      expect(stream.state).to.equal('subscribed');
      const connection = room.erizoConnectionManager.getErizoConnection('arbitraryConnectionId');
      connection.streamRemovedListener(stream.getID());
      socket.emit.withArgs('unsubscribe').args[0][2](result, error);
      expect(stream.state).to.equal('unsubscribed');
    });
  });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SampleWebApp.Baseline.Support;
using Microsoft.EntityFrameworkCore;
using Swashbuckle.AspNetCore.Swagger;
using SampleWebApp.Baseline.Models;
using System.Data.SqlClient;
using SampleWebAppBaseline.DAta;

namespace SampleWebAppBaseline
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            // Add data store
            var connBuilder = new SqlConnectionStringBuilder();
            connBuilder.DataSource = Environment.GetEnvironmentVariable("SQL_DATASOURCE");
            connBuilder.PersistSecurityInfo = false;
            connBuilder.UserID = Environment.GetEnvironmentVariable("SQL_USER");
            connBuilder.Password = Environment.GetEnvironmentVariable("SQL_PASSWORD");
            connBuilder.MultipleActiveResultSets = false;
            connBuilder.Encrypt = true;
            connBuilder.TrustServerCertificate = true;
            connBuilder.ConnectTimeout = 30;
            Console.WriteLine("Building sql connection for data source {0}, with user {1}",
                connBuilder.DataSource, connBuilder.UserID);

            services.AddEntityFrameworkSqlServer()
                .AddDbContext<RaffleContext>(options =>
                    options.UseSqlServer(connBuilder.ToString()));

            // Add repositories
            services.AddScoped<IRaffleRepository, RaffleRepository>();
            services.AddScoped<IUserRepository, UserRepository>();

            // Register the Swagger generator, defining one or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
            ILoggerFactory loggerFactory, RaffleContext raffleContext)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc();

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });
        }
    }
}


text:
package com.nec.strudel.workload.job;

/**
 * an encapsulation of additional information on job (suite) which does not
 * appear in the XML document itself (such as its file name)
 *
 * @author tatemura
 *
 */
public class JobInfo {
    private String outDir;
    private String path;
    private String id;
    private int jobId;

    public JobInfo() {
    }

    public JobInfo(String path) {
        this.path = path;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getOutDir() {
        return outDir;
    }

    public void setOutDir(String outDir) {
        this.outDir = outDir;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setJobId(int jobId) {
        this.jobId = jobId;
    }

    public int getJobId() {
        return jobId;
    }

    public JobInfo copy(int jobId) {
        JobInfo info = new JobInfo(path);
        info.setJobId(jobId);
        info.setOutDir(getOutDir());
        info.setId(getId());
        return info;
    }

}


text:
import { Component, Input }  from '@angular/core';

import { AdComponent }       from './ad.component';

@Component({
  template: `

Featured Hero Profile

{{data.name}}

{{data.bio}}

      Hire this hero today!

  `
})
export class HeroProfileComponent implements AdComponent {
  @Input() data: any;
}


text:
from basic import *
import re

class checker(property):
    """
    Item restrictions

    @ilen   length of one item, 0 for unlimited
    @nr     number of items, 0 for unlimited
    @tlen   total length of a fields, 0 for unlimited
    """
    _value = None
    __ilen = 0
    __nr   = 0
    __tlen = __ilen * __nr

    @property
    def ilen(self): return self.__ilen

    @ilen.setter
    def ilen(self, entry):
        self.__ilen = entry
        self.tlen = self.ilen * self.nr

    @property
    def nr(self): return self.__nr

    @nr.setter
    def nr(self, entry):
        self.__nr = entry
        self.tlen = self.ilen * self.nr

    @property
    def tlen(self): return self.__tlen

    @tlen.setter
    def tlen(self, entry):
        self.__tlen = entry

    def __init__(self, func):

        self.ilen = 0
        self.tlen = 0

    def __get__(self, obj, cls):
        return self._value

    def __set__(self, obj, entry):

        self._value = entry

#    def __setattr__(self, name, entry):
#
#        property.__setattr__(self, name, entry)
#
#        if name in ['ilen', 'nr']:
#            self.tlen = self.ilen * self.nr

class list_chk(checker):

    _value = []

    def __set__(self, obj, entry):

        if not isinstance(entry, list) and entry is not None:
            raise TypeError('list type required')

        if self.nr > 0 and len(entry) > self.nr:
            raise ValueError('too much items')

        if entry is not None:
            self._value = entry

class string_chk(checker):

    _value = str()

    def __set__(self, obj, entry):

        if entry is None or entry == '':
            self._value = ''
            return

        if not isinstance(entry, str):
            raise TypeError('string type required')

        if self.tlen > 0 and len(entry) > self.tlen:
            raise ValueError('value length exceeded')

        self._value = entry

class integer_chk(checker):

    _value = int()

    def __set__(self, obj, entry):

        if entry is None: return

        if not isinstance(entry, int):
            raise TypeError('integer type required')

        self._value = entry

class boolean_chk(checker):

    _value = bool()

    def __set__(self, obj, entry):

        if entry is None: return

        if not isinstance(entry, bool):
            raise TypeError('boolean value required')

        self._value = entry

class map_chk(checker):

    _value = {}

    def __set__(self, obj, entry):

        if entry is None: return

        if not isinstance(entry, dict):
            raise TypeError('list required')

        self._value = entry

class list_of_string_chk(list_chk):

    def __set__(self, obj, entry):

        super(list_of_string_chk, self).__set__(obj, entry)

        for e in entry:
            if not isinstance(e, str):
                raise TypeError('list of string required')

        if entry is not None:
            self._value = entry

class dotted_ip_chk(string_chk):

    def __init__(self, func):

        super(dotted_ip_chk, self).__init__(obj, entry)

        self.reobj = re.compile('^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$')

        self.ilen = 15
        self.nr   = 1

    def __set__(self, obj, entry):

        super(dotted_ip_chk, self).__set__(obj, entry)

        if len(entry) and not self.reobj.match(entry):
            raise ValueError('Dotted string required')

        self._value = entry

class mac_chk(string_chk):

    def __init__(self, func):

        super(mac_chk, self).__init__(obj, entry)

        self.reobj = re.compile('^([0-9A-Fa-f]{2}[.:-]{0,1}){6}$')
        self.ilen  = 17
        self.nr    = 1

    def __set__(self, obj, entry):

        if entry is None or len(entry) == 0:

            self._value = ''
            return

        super(mac_chk, self).__set__(obj, entry)

        if len(entry) and not self.reobj.match(entry):
            raise ValueError('Colon delimited string required')

        self._value = entry

class dummy_chk(list_chk):
    """
    type('usersettings_chk', (list_chk,), {'ilen':1, 'nr':2})
    """
    def __init__(self, func):

        self.ilen = 1
        self.nr = 5
"""
from cipher_helper import CiHelper

class passwd_chk(string_chk):

    __ci = CiHelper

    def __init__(self, func):

        self._value = ''

    def __set__(self, obj, entry):

        string_chk(None).__set__(obj, entry)

        try:
            b64.b64decode(entry, validate=True)
            self._value = entry
        except b64.binascii.Error:
            self._value = self.__ci.enc(entry)[0]

    def __get__(self, obj, cls):

        return self.__ci.dec(self._value)[0]

"""


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

class Search extends MX_Controller {
	public function __construct(){
		parent::__construct();
		$helper = $this->load->helper(array('url','uin_helper'));
	}

	public function index()
	{
		$this->load->view('vSearch');
	}
}


text:
curl http://localhost:3000/products.json > products.json
curl http://localhost:3000/vendors.json > vendors.json

curl http://localhost:3000/products/[1-250].json -o "products/#1.json"
curl http://localhost:3000/vendors/[1-25].json -o "vendors/#1.json"


text:
export function newApi() {
  const target = () => {};

  const handler = {
    apply: function (target, that, args) {
      return Promise.resolve();
    },
    get: function (target, prop, receiver) {
      const original = target[prop];
      if (prop === 'toString') {
        return () => '[fakeApi]';
      } else if (typeof original === 'function') {
        return target[prop].bind(target);
      } else if (original) {
        return target[prop];
      }
      return newApi();
    }
  };

  return new Proxy(target, handler) as any;
}


text:
<?php

namespace OS\CommonBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Comment
 *
 * @ORM\Table(name="comment")
 * @ORM\Entity
 */
class Comment
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var integer
     *
     * @ORM\Column(name="score", type="integer", nullable=true)
     */
    private $score;

    /**
     * @var string
     *
     * @ORM\Column(name="comment", type="text", nullable=true)
     */
    private $comment;

    /**
     * @var string
     *
     * @ORM\Column(name="displayed_username", type="string", length=64, nullable=true)
     */
    private $displayedUsername;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=true)
     */
    private $createdAt;

    /**
     * @var \Post
     *
     * @ORM\ManyToOne(targetEntity="Post")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="post_id", referencedColumnName="id")
     * })
     */
    private $post;

    /**
     * @var \User
     *
     * @ORM\ManyToOne(targetEntity="User")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     * })
     */
    private $user;

    /**
     *
     */
    public function __construct()
    {
        $this->score = 0;
        $this->createdAt = new \DateTime();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set score
     *
     * @param integer $score
     * @return Comment
     */
    public function setScore($score)
    {
        $this->score = $score;

        return $this;
    }

    /**
     * Get score
     *
     * @return integer
     */
    public function getScore()
    {
        return $this->score;
    }

    /**
     * Set comment
     *
     * @param string $comment
     * @return Comment
     */
    public function setComment($comment)
    {
        $this->comment = $comment;

        return $this;
    }

    /**
     * Get comment
     *
     * @return string
     */
    public function getComment()
    {
        return $this->comment;
    }

    /**
     * Set displayedUsername
     *
     * @param string $displayedUsername
     * @return Comment
     */
    public function setDisplayedUsername($displayedUsername)
    {
        $this->displayedUsername = $displayedUsername;

        return $this;
    }

    /**
     * Get displayedUsername
     *
     * @return string
     */
    public function getDisplayedUsername()
    {
        return $this->displayedUsername;
    }

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     * @return Comment
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set post
     *
     * @param \OS\CommonBundle\Entity\Post $post
     * @return Comment
     */
    public function setPost(\OS\CommonBundle\Entity\Post $post = null)
    {
        $this->post = $post;

        return $this;
    }

    /**
     * Get post
     *
     * @return \OS\CommonBundle\Entity\Post
     */
    public function getPost()
    {
        return $this->post;
    }

    /**
     * Set user
     *
     * @param \OS\CommonBundle\Entity\User $user
     * @return Comment
     */
    public function setUser(\OS\CommonBundle\Entity\User $user = null)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \OS\CommonBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
}


text:
<?php

class Clientes_model extends CI_Model {

    public function __construct() {
        $this->load->database();
    }

    public function buscar_persona_natural($data = array()) {
        $arrayParametros = array();
        $arrayParametros['primerNombre'] = $data['primerNombre'] != '' ? '%' . $data['primerNombre'] . '%' : NULL;
        $arrayParametros['segundoNombre'] = $data['segundoNombre'] != '' ? '%' . $data['segundoNombre'] . '%' : NULL;
        $arrayParametros['apellidoPaterno'] = $data['apellidoPaterno'] != '' ? '%' . $data['apellidoPaterno'] . '%' : NULL;
        $arrayParametros['apellidoMaterno'] = $data['apellidoMaterno'] != '' ? '%' . $data['apellidoMaterno'] . '%' : NULL;
        $arrayParametros['nroDocumento'] = $data['nroDocumento'] != '' ? '%' . $data['nroDocumento'] . '%' : NULL;

        $this->db->select('*');
        $this->db->from('tab_personas');
        $this->db->join('tab_clientes_naturales', 'tab_clientes_naturales.ID_PERSONA = tab_personas.ID_PERSONA');
        $this->db->join('tab_clientes', 'tab_clientes_naturales.ID_CLIENTE = tab_clientes.ID_CLIENTE');

        if ($arrayParametros['primerNombre'] != NULL) {
            $this->db->where('tab_personas.PRIMER_NOMBRE like', $arrayParametros['primerNombre']);
        }
        if ($arrayParametros['segundoNombre'] != NULL) {
            $this->db->where('tab_personas.SEGUNDO_NOMBRE like', $arrayParametros['segundoNombre']);
        }
        if ($arrayParametros['apellidoPaterno'] != NULL) {
            $this->db->where('tab_personas.APELLIDO_PATERNO like', $arrayParametros['apellidoPaterno']);
        }
        if ($arrayParametros['apellidoMaterno'] != NULL) {
            $this->db->where('tab_personas.APELLIDO_MATERNO like', $arrayParametros['apellidoMaterno']);
        }
        if ($arrayParametros['nroDocumento'] != NULL) {
            $this->db->where('tab_clientes.NRO_DOCUMENTO like', $arrayParametros['nroDocumento']);
        }
        $consulta = $this->db->get();
        $resultado = $consulta->result_array();
        return $resultado;
    }

    public function buscar_persona_juridica($data = array()) {
        $arrayParametros = array();
        $arrayParametros['nombreComercial'] = $data['nombreComercial'] != '' ? '%' . $data['nombreComercial'] . '%' : NULL;
        $arrayParametros['nroDocumento'] = $data['nroDocumento'] != '' ? '%' . $data['nroDocumento'] . '%' : NULL;
        $this->db->select('*');
        $this->db->from('tab_clientes_juridicos');
        $this->db->join('tab_clientes', 'tab_clientes.ID_CLIENTE=tab_clientes_juridicos.ID_CLIENTE');

        if ($arrayParametros['nombreComercial'] != NULL) {
            $this->db->where('tab_clientes_juridicos.NOMBRE_COMERCIAL like', $arrayParametros['nombreComercial']);
        }
        if ($arrayParametros['nroDocumento'] != NULL) {
            $this->db->where('tab_clientes.NRO_DOCUMENTO like', $arrayParametros['nroDocumento']);
        }
        $consulta = $this->db->get();
        $resultado = $consulta->result_array();
        return $resultado;
    }

    public function obtener_datos_cliente_natural($idCliente = null)
    {
        $this->db->select('tab_personas.*, '
                . 'tab_contactos.ID_PAIS ID_CONTACTO_LABORAL,'
                . 'tab_contactos.ID_PAIS ID_PAIS_CONTACTO_LABORAL,'
                . 'tab_contactos.CORREO_ELECTRONICO CORREO_ELECTRONICO_CONTACTO_LABORAL,'
                . 'tab_contactos.ID_PROVINCIA ID_PROVINCIA_CONTACTO_LABORAL,'
                . 'tab_contactos.ID_CANTON ID_CANTON_CONTACTO_LABORAL,'
                . 'tab_contactos.ID_PARROQUIA ID_PARROQUIA_CONTACTO_LABORAL,'
                . 'tab_contactos.DIRECCION_CALLE_PRINCIPAL DIRECCION_CALLE_PRINCIPAL_CONTACTO_LABORAL,'
                . 'tab_contactos.DIRECCION_NUMERO DIRECCION_NUMERO_CONTACTO_LABORAL,'
                . 'tab_contactos.DIRECCION_CALLE_SECUNDARIA1 DIRECCION_CALLE_SECUNDARIA1_CONTACTO_LABORAL,'
                . 'tab_contactos.DIRECCION_CALLE_SECUNDARIA2 DIRECCION_CALLE_SECUNDARIA2_CONTACTO_LABORAL,'
                . 'tab_contactos.DIRECCION_REFERENCIA DIRECCION_REFERENCIA_CONTACTO_LABORAL,'
                . 'tab_contactos.TELEFONO TELEFONO_CONTACTO_LABORAL,'
                . 'tab_contactos.CELULAR CELULAR_CONTACTO_LABORAL,'
                . 'tab_contactos.ID_OPERADOR_TELEFONICO ID_OPERADOR_TELEFONICO_CONTACTO_LABORAL,'
                . 'tab_contactos.DESCRIPCION DESCRIPCION_CONTACTO_LABORAL,'

                . 'tab_contacto_domicilio.ID_CONTACTO AS ID_CONTACTO_DOMICILIO,'
                . 'tab_contacto_domicilio.ID_PAIS ID_PAIS_DOMICILIO,'
                . 'tab_contacto_domicilio.CORREO_ELECTRONICO CORREO_ELECTRONICO_DOMICILIO,'
                . 'tab_contacto_domicilio.ID_PROVINCIA ID_PROVINCIA_DOMICILIO,'
                . 'tab_contacto_domicilio.ID_CANTON ID_CANTON_DOMICILIO,'
                . 'tab_contacto_domicilio.ID_PARROQUIA ID_PARROQUIA_DOMICILIO,'
                . 'tab_contacto_domicilio.DIRECCION_CALLE_PRINCIPAL DIRECCION_CALLE_PRINCIPAL_DOMICILIO,'
                . 'tab_contacto_domicilio.DIRECCION_NUMERO DIRECCION_NUMERO_DOMICILIO,'
                . 'tab_contacto_domicilio.DIRECCION_CALLE_SECUNDARIA1 DIRECCION_CALLE_SECUNDARIA1_DOMICILIO,'
                . 'tab_contacto_domicilio.DIRECCION_CALLE_SECUNDARIA2 DIRECCION_CALLE_SECUNDARIA2_DOMICILIO,'
                . 'tab_contacto_domicilio.DIRECCION_REFERENCIA DIRECCION_REFERENCIA_DOMICILIO,'
                . 'tab_contacto_domicilio.TELEFONO TELEFONO_DOMICILIO,'
                . 'tab_contacto_domicilio.CELULAR CELULAR_DOMICILIO,'
                . 'tab_contacto_domicilio.ID_OPERADOR_TELEFONICO ID_OPERADOR_TELEFONICO_DOMICILIO,'
                . 'tab_contacto_domicilio.DESCRIPCION DESCRIPCION_DOMICILIO,'

                . 'tab_clientes.ID_CLIENTE,'
                . 'tab_clientes.TIPO_DOCUMENTO,'
                . 'tab_clientes.NRO_DOCUMENTO,'
                . 'tab_clientes.ID_NATURALEZA_PERSONA,'
                . 'tab_clientes.ID_TIPO_CONTRIBUYENTE,'
                . 'tab_clientes.ES_CONTRIBUYENTE_ESPECIAL'
        );
        $this->db->from('tab_clientes_naturales');
        $this->db->join('tab_clientes', 'tab_clientes_naturales.ID_CLIENTE = tab_clientes.ID_CLIENTE ');
        $this->db->join('tab_personas', 'tab_personas.ID_PERSONA = tab_clientes_naturales.ID_PERSONA ');
        $this->db->join('tab_contactos as tab_contacto_domicilio', 'tab_clientes.ID_CLIENTE = tab_contacto_domicilio.ID_CLIENTE AND tab_contacto_domicilio.ID_TIPO_CONTACTO=2 AND tab_contacto_domicilio.ESTADO=1', 'left');
        $this->db->join('tab_contactos', 'tab_clientes_naturales.ID_CLIENTE = tab_contactos.ID_CLIENTE AND tab_contactos.ID_TIPO_CONTACTO=1 AND tab_contactos.ESTADO=1', 'left');
        $this->db->where('tab_clientes.ID_CLIENTE', $idCliente);
        $query = $this->db->get();
        return $query->row_array();
    }

    public function obtener_detalles_cliente_natural($idCliente = null) {
        $this->db->select('tab_personas.*, '

                . 'tab_contactos.ID_CONTACTO ID_CONTACTO_LABORAL,'
                . 'tab_contactos.ID_PAIS ID_PAIS_CONTACTO_LABORAL,'
                . 'tab_contactos.CORREO_ELECTRONICO CORREO_ELECTRONICO_CONTACTO_LABORAL,'
                . 'tab_contactos.ID_PROVINCIA ID_PROVINCIA_CONTACTO_LABORAL,'
                . 'tab_contactos.ID_CANTON ID_CANTON_CONTACTO_LABORAL,'
                . 'tab_contactos.ID_PARROQUIA ID_PARROQUIA_CONTACTO_LABORAL,'
                . 'tab_contactos.DIRECCION_CALLE_PRINCIPAL DIRECCION_CALLE_PRINCIPAL_CONTACTO_LABORAL,'
                . 'tab_contactos.DIRECCION_NUMERO DIRECCION_NUMERO_CONTACTO_LABORAL,'
                . 'tab_contactos.DIRECCION_CALLE_SECUNDARIA1 DIRECCION_CALLE_SECUNDARIA1_CONTACTO_LABORAL,'
                . 'tab_contactos.DIRECCION_CALLE_SECUNDARIA2 DIRECCION_CALLE_SECUNDARIA2_CONTACTO_LABORAL,'
                . 'tab_contactos.DIRECCION_REFERENCIA DIRECCION_REFERENCIA_CONTACTO_LABORAL,'
                . 'tab_contactos.TELEFONO TELEFONO_CONTACTO_LABORAL,'
                . 'tab_contactos.CELULAR CELULAR_CONTACTO_LABORAL,'
                . 'tab_contactos.ID_OPERADOR_TELEFONICO ID_OPERADOR_TELEFONICO_CONTACTO_LABORAL,'
                . 'tab_contactos.DESCRIPCION DESCRIPCION_CONTACTO_LABORAL,'

                . 'pais_contacto_laboral.PAIS AS PAIS_CONTACTO_LABORAL,'
                . 'provincias_contacto_laboral.PROVINCIA AS PROVINCIA_CONTACTO_LABORAL,'
                . 'cantones_contacto_laboral.CANTON AS CANTON_CONTACTO_LABORAL,'
                . 'parroquias_contacto_laboral.PARROQUIA AS PARROQUIA_CONTACTO_LABORAL,'
                . 'operadoras_telefonicas_contacto_laboral.NOMBRE_OPERADOR AS NOMBRE_OPERADOR_CONTACTO_LABORAL,'

                . 'tab_contacto_domicilio.ID_CONTACTO AS ID_CONTACTO_DOMICILIO,'
                . 'tab_contacto_domicilio.ID_PAIS ID_PAIS_DOMICILIO,'
                . 'tab_contacto_domicilio.CORREO_ELECTRONICO CORREO_ELECTRONICO_DOMICILIO,'
                . 'tab_contacto_domicilio.ID_PROVINCIA ID_PROVINCIA_DOMICILIO,'
                . 'tab_contacto_domicilio.ID_CANTON ID_CANTON_DOMICILIO,'
                . 'tab_contacto_domicilio.ID_PARROQUIA ID_PARROQUIA_DOMICILIO,'
                . 'tab_contacto_domicilio.DIRECCION_CALLE_PRINCIPAL DIRECCION_CALLE_PRINCIPAL_DOMICILIO,'
                . 'tab_contacto_domicilio.DIRECCION_NUMERO DIRECCION_NUMERO_DOMICILIO,'
                . 'tab_contacto_domicilio.DIRECCION_CALLE_SECUNDARIA1 DIRECCION_CALLE_SECUNDARIA1_DOMICILIO,'
                . 'tab_contacto_domicilio.DIRECCION_CALLE_SECUNDARIA2 DIRECCION_CALLE_SECUNDARIA2_DOMICILIO,'
                . 'tab_contacto_domicilio.DIRECCION_REFERENCIA DIRECCION_REFERENCIA_DOMICILIO,'
                . 'tab_contacto_domicilio.TELEFONO TELEFONO_DOMICILIO,'
                . 'tab_contacto_domicilio.CELULAR CELULAR_DOMICILIO,'
                . 'tab_contacto_domicilio.ID_OPERADOR_TELEFONICO ID_OPERADOR_TELEFONICO_DOMICILIO,'
                . 'tab_contacto_domicilio.DESCRIPCION DESCRIPCION_DOMICILIO,'

                . 'pais_domicilio.PAIS AS PAIS_DOMICILIO,'
                . 'provincias_domicilio.PROVINCIA AS PROVINCIA_DOMICILIO,'
                . 'cantones_domicilio.CANTON AS CANTON_DOMICILIO,'
                . 'parroquias_domicilio.PARROQUIA AS PARROQUIA_DOMICILIO,'
                . 'operadoras_telefonicas_domicilio.NOMBRE_OPERADOR AS NOMBRE_OPERADOR_DOMICILIO,'

                . 'tab_clientes.ID_CLIENTE,'
                . 'tab_clientes.TIPO_DOCUMENTO,'
                . 'tab_clientes.NRO_DOCUMENTO,'
                . 'tab_clientes.ID_NATURALEZA_PERSONA,'
                . 'tab_clientes.ID_TIPO_CONTRIBUYENTE,'
                . 'tab_clientes.ES_CONTRIBUYENTE_ESPECIAL,'

                . 'tab_tipos_documentos.NOMBRE_TIPO_DOCUMENTO,'
                . 'tab_tipos_contribuyentes.TIPO_CONTRIBUYENTE,'
                . 'tab_tipos_becas.TIPO_BECA,'
                . 'tab_nacionalidades.NACIONALIDAD,'
                . 'pais_nacimiento.PAIS PAIS_NACIMIENTO,'
                . 'provincia_nacimiento.PROVINCIA PROVINCIA_NACIMIENTO,'
                . 'tab_estados_civiles.ESTADO_CIVIL,'
                . 'tab_grupos_culturales.GRUPO_CULTURAL,'
                . 'tab_profesiones.PROFESION,'
                . 'tab_generos.GENERO DENOMINACION_GENERO,'
        );
        $this->db->from('tab_clientes_naturales');
        $this->db->join('tab_clientes', 'tab_clientes_naturales.ID_CLIENTE = tab_clientes.ID_CLIENTE ');
        $this->db->join('tab_tipos_documentos', 'tab_clientes.TIPO_DOCUMENTO = tab_tipos_documentos.TIPO_DOCUMENTO ');
        $this->db->join('tab_tipos_contribuyentes', 'tab_clientes.ID_TIPO_CONTRIBUYENTE = tab_tipos_contribuyentes.ID_TIPO_CONTRIBUYENTE ');
        $this->db->join('tab_personas', 'tab_personas.ID_PERSONA = tab_clientes_naturales.ID_PERSONA ');
        $this->db->join('tab_tipos_becas', 'tab_personas.ID_TIPO_BECA = tab_tipos_becas.ID_TIPO_BECA ','left');
        $this->db->join('tab_nacionalidades', 'tab_personas.ID_NACIONALIDAD = tab_nacionalidades.ID_NACIONALIDAD ');
        $this->db->join('tab_paises as pais_nacimiento', 'tab_personas.ID_PAIS_NACIMIENTO = pais_nacimiento.ID_PAIS','left');
        $this->db->join('tab_provincias as provincia_nacimiento', 'tab_personas.ID_PROVINCIA_NACIMIENTO = provincia_nacimiento.ID_PROVINCIA','left');
        $this->db->join('tab_estados_civiles', 'tab_personas.ID_ESTADO_CIVIL = tab_estados_civiles.ID_ESTADO_CIVIL','left');
        $this->db->join('tab_grupos_culturales', 'tab_personas.ID_GRUPO_CULTURAL = tab_grupos_culturales.ID_GRUPO_CULTURAL','left');
        $this->db->join('tab_profesiones', 'tab_personas.ID_PROFESION = tab_profesiones.ID_PROFESION','left');
        $this->db->join('tab_generos', 'tab_generos.ABREVIATURA_GENERO = tab_personas.GENERO','left');
        $this->db->join('tab_contactos as tab_contacto_domicilio', 'tab_clientes.ID_CLIENTE = tab_contacto_domicilio.ID_CLIENTE AND tab_contacto_domicilio.ID_TIPO_CONTACTO=2 AND tab_contacto_domicilio.ESTADO=1', 'left');
        $this->db->join('tab_contactos', 'tab_clientes_naturales.ID_CLIENTE = tab_contactos.ID_CLIENTE AND tab_contactos.ID_TIPO_CONTACTO=1 AND tab_contactos.ESTADO=1', 'left');

        $this->db->join('tab_paises as pais_domicilio', 'tab_contacto_domicilio.ID_PAIS = pais_domicilio.ID_PAIS', 'left');
        $this->db->join('tab_provincias as provincias_domicilio', 'tab_contacto_domicilio.ID_PROVINCIA = provincias_domicilio.ID_PROVINCIA', 'left');
        $this->db->join('tab_cantones as cantones_domicilio', 'tab_contacto_domicilio.ID_CANTON = cantones_domicilio.ID_CANTON', 'left');
        $this->db->join('tab_parroquias as parroquias_domicilio', 'tab_contacto_domicilio.ID_PARROQUIA = parroquias_domicilio.ID_PARROQUIA', 'left');
        $this->db->join('tab_operadoras_telefonicas as operadoras_telefonicas_domicilio', 'tab_contacto_domicilio.ID_OPERADOR_TELEFONICO = operadoras_telefonicas_domicilio.ID_OPERADOR_TELEFONICO', 'left');

        $this->db->join('tab_paises as pais_contacto_laboral', 'tab_contactos.ID_PAIS = pais_contacto_laboral.ID_PAIS', 'left');
        $this->db->join('tab_provincias as provincias_contacto_laboral', 'tab_contactos.ID_PROVINCIA = provincias_contacto_laboral.ID_PROVINCIA', 'left');
        $this->db->join('tab_cantones as cantones_contacto_laboral', 'tab_contactos.ID_CANTON = cantones_contacto_laboral.ID_CANTON', 'left');
        $this->db->join('tab_parroquias as parroquias_contacto_laboral', 'tab_contactos.ID_PARROQUIA = parroquias_contacto_laboral.ID_PARROQUIA', 'left');
        $this->db->join('tab_operadoras_telefonicas as operadoras_telefonicas_contacto_laboral', 'tab_contactos.ID_OPERADOR_TELEFONICO = operadoras_telefonicas_contacto_laboral.ID_OPERADOR_TELEFONICO', 'left');

        $this->db->where('tab_clientes.ID_CLIENTE', $idCliente);
        $query = $this->db->get();
        return $query->row_array();
    }

    public function obtener_datos_clientes_juridicos($idCliente = null) {
        $this->db->select('tab_clientes.ID_CLIENTE,'
                . 'tab_clientes.TIPO_DOCUMENTO, '
                . 'tab_clientes.NRO_DOCUMENTO, '
                . 'tab_clientes.ID_NATURALEZA_PERSONA, '
                . 'tab_clientes.ID_TIPO_CONTRIBUYENTE, '
                . 'tab_clientes.ES_CONTRIBUYENTE_ESPECIAL, '

                . 'tab_clientes_juridicos.NOMBRE_COMERCIAL,'
                . 'tab_clientes_juridicos.RAZON_SOCIAL,'
                . 'tab_clientes_juridicos.ID_REPRESENTANTE, '
                . 'tab_clientes_juridicos.ES_PUBLICO, '
                . 'tab_clientes_juridicos.ES_SIN_FINES_DE_LUCRO, '

                . 'tab_contactos.CORREO_ELECTRONICO ,'
                . 'tab_contactos.ID_PAIS ,'
                . 'tab_contactos.ID_PROVINCIA ,'
                . 'tab_contactos.ID_CANTON ,'
                . 'tab_contactos.ID_PARROQUIA ,'
                . 'tab_contactos.DIRECCION_CALLE_PRINCIPAL ,'
                . 'tab_contactos.DIRECCION_NUMERO ,'
                . 'tab_contactos.DIRECCION_CALLE_SECUNDARIA1 ,'
                . 'tab_contactos.DIRECCION_CALLE_SECUNDARIA2 ,'
                . 'tab_contactos.DIRECCION_REFERENCIA ,'
                . 'tab_contactos.TELEFONO ,'
                . 'tab_contactos.CELULAR ,'
                . 'tab_contactos.ID_OPERADOR_TELEFONICO ,'
                . 'tab_contactos.ID_TIPO_CONTACTO ,'
                . 'tab_contactos.DESCRIPCION ,'
                . 'tab_contactos.ESTADO ,'

                . 'tab_representantes.PRIMER_NOMBRE,'
                . 'tab_representantes.SEGUNDO_NOMBRE,'
                . 'tab_representantes.APELLIDO_PATERNO,'
                . 'tab_representantes.APELLIDO_MATERNO');
        $this->db->from('tab_clientes');
        $this->db->join('tab_clientes_juridicos', 'tab_clientes.ID_CLIENTE = tab_clientes_juridicos.ID_CLIENTE');
        $this->db->join('tab_contactos', 'tab_clientes.ID_CLIENTE = tab_contactos.ID_CLIENTE  AND tab_contactos.ID_TIPO_CONTACTO=2 AND tab_contactos.ESTADO=1', 'left');
        $this->db->join('tab_representantes', 'tab_representantes.ID_REPRESENTANTE = tab_clientes_juridicos.ID_REPRESENTANTE','left');
        $this->db->where('tab_clientes.ID_CLIENTE', $idCliente);
        $consulta = $this->db->get();
        $resultado = $consulta->row_array();
        return $resultado;
    }

     public function obtener_detalles_clientes_juridicos($idCliente = null) {
        $this->db->select('tab_clientes.ID_CLIENTE,'
                . 'tab_clientes.TIPO_DOCUMENTO, '
                . 'tab_clientes.NRO_DOCUMENTO, '
                . 'tab_clientes.ID_NATURALEZA_PERSONA, '
                . 'tab_clientes.ID_TIPO_CONTRIBUYENTE, '
                . 'tab_clientes.ES_CONTRIBUYENTE_ESPECIAL, '

                . 'tab_clientes_juridicos.NOMBRE_COMERCIAL,'
                . 'tab_clientes_juridicos.RAZON_SOCIAL,'
                . 'tab_clientes_juridicos.ID_REPRESENTANTE, '
                . 'tab_clientes_juridicos.ES_PUBLICO, '
                . 'tab_clientes_juridicos.ES_SIN_FINES_DE_LUCRO, '
                . 'tab_tipos_documentos.NOMBRE_TIPO_DOCUMENTO,'
                . 'tab_tipos_contribuyentes.TIPO_CONTRIBUYENTE,'

                . 'tab_contacto_domicilio.ID_CONTACTO AS ID_CONTACTO_DOMICILIO,'
                . 'tab_contacto_domicilio.ID_PAIS ID_PAIS_DOMICILIO,'
                . 'tab_contacto_domicilio.CORREO_ELECTRONICO CORREO_ELECTRONICO_DOMICILIO,'
                . 'tab_contacto_domicilio.ID_PROVINCIA ID_PROVINCIA_DOMICILIO,'
                . 'tab_contacto_domicilio.ID_CANTON ID_CANTON_DOMICILIO,'
                . 'tab_contacto_domicilio.ID_PARROQUIA ID_PARROQUIA_DOMICILIO,'
                . 'tab_contacto_domicilio.DIRECCION_CALLE_PRINCIPAL DIRECCION_CALLE_PRINCIPAL_DOMICILIO,'
                . 'tab_contacto_domicilio.DIRECCION_NUMERO DIRECCION_NUMERO_DOMICILIO,'
                . 'tab_contacto_domicilio.DIRECCION_CALLE_SECUNDARIA1 DIRECCION_CALLE_SECUNDARIA1_DOMICILIO,'
                . 'tab_contacto_domicilio.DIRECCION_CALLE_SECUNDARIA2 DIRECCION_CALLE_SECUNDARIA2_DOMICILIO,'
                . 'tab_contacto_domicilio.DIRECCION_REFERENCIA DIRECCION_REFERENCIA_DOMICILIO,'
                . 'tab_contacto_domicilio.TELEFONO TELEFONO_DOMICILIO,'
                . 'tab_contacto_domicilio.CELULAR CELULAR_DOMICILIO,'
                . 'tab_contacto_domicilio.ID_OPERADOR_TELEFONICO ID_OPERADOR_TELEFONICO_DOMICILIO,'
                . 'tab_contacto_domicilio.DESCRIPCION DESCRIPCION_DOMICILIO,'

                . 'pais_domicilio.PAIS AS PAIS_DOMICILIO,'
                . 'provincias_domicilio.PROVINCIA AS PROVINCIA_DOMICILIO,'
                . 'cantones_domicilio.CANTON AS CANTON_DOMICILIO,'
                . 'parroquias_domicilio.PARROQUIA AS PARROQUIA_DOMICILIO,'
                . 'operadoras_telefonicas_domicilio.NOMBRE_OPERADOR AS NOMBRE_OPERADOR_DOMICILIO,'

                . 'representante.PRIMER_NOMBRE,'
                . 'representante.SEGUNDO_NOMBRE,'
                . 'representante.APELLIDO_PATERNO,'
                . 'representante.APELLIDO_MATERNO');

        $this->db->from('tab_clientes');
        $this->db->join('tab_clientes_juridicos', 'tab_clientes.ID_CLIENTE = tab_clientes_juridicos.ID_CLIENTE');
        $this->db->join('tab_tipos_documentos', 'tab_clientes.TIPO_DOCUMENTO = tab_tipos_documentos.TIPO_DOCUMENTO ');
        $this->db->join('tab_tipos_contribuyentes', 'tab_clientes.ID_TIPO_CONTRIBUYENTE = tab_tipos_contribuyentes.ID_TIPO_CONTRIBUYENTE ');

        $this->db->join('tab_contactos tab_contacto_domicilio', 'tab_clientes.ID_CLIENTE = tab_contacto_domicilio.ID_CLIENTE  AND tab_contacto_domicilio.ID_TIPO_CONTACTO=2 AND tab_contacto_domicilio.ESTADO=1', 'left');
        $this->db->join('tab_paises as pais_domicilio', 'tab_contacto_domicilio.ID_PAIS = pais_domicilio.ID_PAIS', 'left');
        $this->db->join('tab_provincias as provincias_domicilio', 'tab_contacto_domicilio.ID_PROVINCIA = provincias_domicilio.ID_PROVINCIA', 'left');
        $this->db->join('tab_cantones as cantones_domicilio', 'tab_contacto_domicilio.ID_CANTON = cantones_domicilio.ID_CANTON', 'left');
        $this->db->join('tab_parroquias as parroquias_domicilio', 'tab_contacto_domicilio.ID_PARROQUIA = parroquias_domicilio.ID_PARROQUIA', 'left');
        $this->db->join('tab_operadoras_telefonicas as operadoras_telefonicas_domicilio', 'tab_contacto_domicilio.ID_OPERADOR_TELEFONICO = operadoras_telefonicas_domicilio.ID_OPERADOR_TELEFONICO', 'left');

        $this->db->join('tab_representantes as representante', 'representante.ID_REPRESENTANTE = tab_clientes_juridicos.ID_REPRESENTANTE','left');
        $this->db->where('tab_clientes.ID_CLIENTE', $idCliente);
        $consulta = $this->db->get();
        $resultado = $consulta->row_array();
        return $resultado;
    }

    /*Este método se usa para buscar un cliente por su Nro de documento registrado*/
    public function obtener_cliente_por_nro_documento($nroDocumento = null) {
        if ($nroDocumento === null) {
            return array();
        } else {
            $this->db->select('tab_personas.*,tab_clientes.ID_CLIENTE');
            $this->db->from('tab_personas');
            $this->db->join('tab_clientes_naturales', 'tab_clientes_naturales.ID_PERSONA = tab_personas.ID_PERSONA');
            $this->db->join('tab_clientes', 'tab_clientes.ID_CLIENTE = tab_clientes_naturales.ID_CLIENTE');
            $this->db->where('tab_clientes.NRO_DOCUMENTO', $nroDocumento);
            $query = $this->db->get();
            return $query->row_array();
        }
    }

    /*Este método se usa para buscar un cliente juridico por su Nro de documento registrado*/
    public function obtener_cliente_juridico_por_nro_documento($nroDocumento = null) {
        if ($nroDocumento === null) {
            return array();
        } else {
            $this->db->select('tab_clientes.ID_CLIENTE');
            $this->db->from('tab_clientes');
            $this->db->join('tab_clientes_juridicos', 'tab_clientes.ID_CLIENTE = tab_clientes_juridicos.ID_CLIENTE');
            $this->db->where('tab_clientes.NRO_DOCUMENTO', $nroDocumento);
            $query = $this->db->get();
            return $query->row_array();
        }
    }

    /*este método se utiliza para verificar si u Nro de documento ya esta registrado.*/
    public function buscar_cliente_por_nro_documento($nroDocumento = null, $idCliente = NULL) {
        if ($nroDocumento === null) {
            return null;
        } else {
            $this->db->select('tab_clientes.ID_CLIENTE');
            $this->db->from('tab_clientes');
            $this->db->join('tab_clientes_naturales', 'tab_clientes_naturales.ID_CLIENTE=tab_clientes.ID_CLIENTE','left');
            $this->db->join('tab_personas', 'tab_personas.ID_PERSONA = tab_clientes_naturales.ID_PERSONA ','left');
            $this->db->where('tab_clientes.NRO_DOCUMENTO', $nroDocumento);
            if ($idCliente) {
                $this->db->where('tab_clientes.ID_CLIENTE <>', $idCliente);
            }
//            $this->db->or_where('tab_personas.NUMERO_RUC', $nroDocumento);
            $query = $this->db->get();
            return $query->row_array();
        }
    }

    public function crearPersona($data) {
        $this->db->insert('tab_personas', $data);
        return $this->db->insert_id();
    }

    public function actualizarPersona($data, $idPersona) {
        $this->db->where('tab_personas.ID_PERSONA', $idPersona);
        $this->db->update('tab_personas', $data);
    }

    public function crearCliente($data) {
        $this->db->insert('tab_clientes', $data);
        return $this->db->insert_id();
    }

    public function actualizarCliente($data, $idCliente) {
        $this->db->where('tab_clientes.ID_CLIENTE', $idCliente);
        $this->db->update('tab_clientes', $data);
    }

    public function crearClienteNatural($data) {
        $this->db->insert('tab_clientes_naturales', $data);
        return $this->db->insert_id();
    }

    public function crearClienteJuridico($data) {
        $this->db->insert('tab_clientes_juridicos', $data);
        return $this->db->insert_id();
    }

    public function actualizarClienteJuridico($data) {
        $this->db->where('tab_clientes_juridicos.ID_CLIENTE', $data['ID_CLIENTE']);
        $this->db->update('tab_clientes_juridicos', $data);
    }

    public function crearPersonaAContactar($data) {
        $this->db->insert('tab_personas_a_contactar', $data);
        return $this->db->insert_id();
    }

    public function actualizarPersonaAContactar($data) {
        $this->db->where('tab_personas_a_contactar.ID_PERSONA_CONTACTAR', $data['ID_PERSONA_CONTACTAR']);
        $this->db->update('tab_personas_a_contactar', $data);
    }

    public function obtenerDatosClientesParaFactura($idCliente=NULL) {
        $this->db->select('tab_clientes.*,'
                . 'tab_clientes_juridicos.RAZON_SOCIAL,'
                . 'tab_personas.*,'
                . 'tab_tipos_becas.PORCENTAJE,'
                . 'tab_contactos.DIRECCION_CALLE_PRINCIPAL,'
                . 'tab_contactos.DIRECCION_NUMERO,'
                . 'tab_contactos.DIRECCION_CALLE_SECUNDARIA1,'
                . 'tab_contactos.TELEFONO,'
                . 'tab_contactos.CELULAR,'
                . 'tab_provincias.PROVINCIA,'
                . 'tab_paises.PAIS'
                );
        $this->db->from('tab_clientes');
        $this->db->join('tab_contactos','tab_clientes.ID_CLIENTE = tab_contactos.ID_CLIENTE AND tab_contactos.ID_TIPO_CONTACTO = 2 AND tab_contactos.ESTADO = 1','left');
        $this->db->join('tab_provincias','tab_provincias.ID_PROVINCIA = tab_contactos.ID_PROVINCIA','left');
        $this->db->join('tab_paises','tab_contactos.ID_PAIS = tab_paises.ID_PAIS','left');
        $this->db->join('tab_clientes_juridicos','tab_clientes.ID_CLIENTE = tab_clientes_juridicos.ID_CLIENTE', 'left');
        $this->db->join('tab_clientes_naturales','tab_clientes.ID_CLIENTE = tab_clientes_naturales.ID_CLIENTE', 'left');
        $this->db->join('tab_personas','tab_clientes_naturales.ID_PERSONA = tab_personas.ID_PERSONA', 'left');
        $this->db->join('tab_tipos_becas','tab_personas.ID_TIPO_BECA = tab_tipos_becas.ID_TIPO_BECA', 'left');
        $this->db->where('tab_clientes.ID_CLIENTE',$idCliente);

        $query = $this->db->get();
        $result = $query->row_array();

        if($result['RAZON_SOCIAL'])
        {
            $result['CLIENTE_DENOMINACION'] = $result['RAZON_SOCIAL'];
        }
        else
        {
            $result['CLIENTE_DENOMINACION'] = $result['PRIMER_NOMBRE'].' '.
                                              $result['SEGUNDO_NOMBRE'].' ' .
                                              $result['APELLIDO_PATERNO'].' '.
                                              $result['APELLIDO_MATERNO'] ;

        }

        $result['DIRECCION'] = $result['DIRECCION_CALLE_PRINCIPAL'];

        if($result['DIRECCION_NUMERO']){
           $result['DIRECCION'] .= ' '.$result['DIRECCION_NUMERO'];
        }
        if($result['DIRECCION_CALLE_SECUNDARIA1']){
           $result['DIRECCION'] .= 'Y '.$result['DIRECCION_CALLE_SECUNDARIA1'];
        }
          //$result['DIRECCION'] .= '. '.$result['PAIS'].', '.$result['PROVINCIA'].'. ' ;
        return $result;
    }

    public function obtenerDatosClientesParaAsociacionRubros($idCliente=NULL) {
        $this->db->select('tab_clientes.*,'
                . 'tab_clientes_juridicos.RAZON_SOCIAL,'
                . 'tab_personas.*'
                );
        $this->db->from('tab_clientes');
         $this->db->join('tab_clientes_juridicos','tab_clientes.ID_CLIENTE = tab_clientes_juridicos.ID_CLIENTE', 'left');
        $this->db->join('tab_clientes_naturales','tab_clientes.ID_CLIENTE = tab_clientes_naturales.ID_CLIENTE', 'left');
        $this->db->join('tab_personas','tab_clientes_naturales.ID_PERSONA = tab_personas.ID_PERSONA', 'left');
        $this->db->where('tab_clientes.ID_CLIENTE',$idCliente);

        $query = $this->db->get();
        $result = $query->row_array();

        $result['NOMBRE_CLIENTE'] = '';
        if( $result['RAZON_SOCIAL'] != NULL)
        {
            $result['NOMBRE_CLIENTE'] = $result['RAZON_SOCIAL'];
        }
        else
        {
             $result['NOMBRE_CLIENTE'] = $result['PRIMER_NOMBRE'].' '.$result['APELLIDO_PATERNO'].' '.$result['APELLIDO_MATERNO'];
        }

        if($result['ID_TIPO_CONTRIBUYENTE'] == '2')
        {
            $result['OBLIGADO_A_LLEVAR_CONTABILIDAD'] = TRUE;
        }
        else
        {
            $result['OBLIGADO_A_LLEVAR_CONTABILIDAD'] = FALSE;
        }

        if($result['ES_CONTRIBUYENTE_ESPECIAL'] == '1')
        {
            $result['ES_CONTRIBUYENTE_ESPECIAL'] = TRUE;
        }
        else
        {
            $result['ES_CONTRIBUYENTE_ESPECIAL'] = FALSE;
        }

//        esContribuyenteEspecial'=> $datosCliente[],
//        'estaObligadoLlevarcontabilidad
        return $result;
    }
    /*--------------------- METODOS RELACIONADOS CON LOS CONTACTOS -----------------------*/

    public function buscarContacto($datos_contacto) {
        $this->db->select('tab_contactos.ID_CONTACTO');
        $this->db->from('tab_contactos');
        $this->db->where($datos_contacto);

        $query = $this->db->get();
        return $query->row_array();
    }

    public function desactivarContactosLaborales($id_cliente) {
        $data = array();
        $data['ESTADO'] = 0;
        $this->db->where('tab_contactos.ID_CLIENTE', $id_cliente);
        $this->db->where('tab_contactos.ID_TIPO_CONTACTO', 1);
        $this->db->update('tab_contactos', $data);
    }

    public function desactivarContactosDeDomicilio($id_cliente) {
        $data = array();
        $data['ESTADO'] = 0;
        $this->db->where('tab_contactos.ID_CLIENTE', $id_cliente);
        $this->db->where('tab_contactos.ID_TIPO_CONTACTO', 2);
        $this->db->update('tab_contactos', $data);
    }

    public function crearContacto($data) {
        $this->db->insert('tab_contactos', $data);
        return $this->db->insert_id();
    }
    /*--------------------------------------------------------------------*/

    public function crearActualizarClienteNaturalTransaccional($persona, $dataPersona, $dataCliente, $contactoLaboral, $contactoDomiciliar)
    {
        $this->db->trans_start();
        $idPersona = null;
        $idCliente = null;
        if (isset($persona['ID_PERSONA']) && $persona['ID_PERSONA'] != NULL)
        {
            $idPersona = $persona['ID_PERSONA'];

            $this->actualizarPersona($dataPersona, $persona['ID_PERSONA']); //actualizo la persona
        }
        else
        {
            /* SETEAR LA NATURALEZA DE LA PERSONA */
            $idPersona = $this->crearPersona($dataPersona);
        }

        /* SE INSERTAN O MODIFICAN LOS DATOS DEL CLIENTE */
        if (isset($persona['ID_CLIENTE']) && $persona['ID_CLIENTE'] != NULL) {
            $idCliente = $persona['ID_CLIENTE'];
            $this->actualizarCliente($dataCliente, $persona['ID_CLIENTE']);
        } else {
            /* SETEAR LA NATURALEZA DE LA PERSONA */
            $dataCliente['ID_NATURALEZA_PERSONA'] = 1;

            /* INSERTAR CLIENTE */
            $idCliente = $this->crearCliente($dataCliente);

            /* INSERTAR CLIENTE NATURAL */
            $clienteNatural = array();
            $clienteNatural['ID_CLIENTE'] = $idCliente;
            $clienteNatural['ID_PERSONA'] = $idPersona;
            $this->crearClienteNatural($clienteNatural);
        }

        /* INSERCION O ACTUALIZACION DE LOS CONTACTOS LABORALES O DE DOMICILIO DE LAS PERSONAS */

        /* DETERMINAR SI EXISTE UN CONTACTO CON ESOS DATOS PARA ESA PERSONA */
        $estaVacioContactoLaboral = true;
        foreach ($contactoLaboral as $value) {
            if ($value !== NULL) {
                $estaVacioContactoLaboral = false;
            }
        }

        $contactoLaboral['ID_CLIENTE'] = $idCliente;
        $contactoLaboral['ID_TIPO_CONTACTO'] = 1;
        $contactoLaboral['ESTADO'] = 1;

        $contactoDomiciliar['ID_CLIENTE'] = $idCliente;
        $contactoDomiciliar['ID_TIPO_CONTACTO'] = 2;
        $contactoDomiciliar['ESTADO'] = 1;

        if (!$estaVacioContactoLaboral) {

            $contactosLaborales = $this->buscarContacto($contactoLaboral);
            /* SI NO EXISTE SE PROCEDERA A INSERTAR ESTE CONTACTO NUEVO Y SE CAMBIARA EL ESTADO DEL RESTO DE  LOS CONTACTOS EXISTENTES */
            if (!$contactosLaborales) {
                $this->desactivarContactosLaborales($idCliente);
                $this->crearContacto($contactoLaboral);
            }
        } else {
            $this->desactivarContactosLaborales($idCliente);
        }

        $contactosDomiciliares = $this->buscarContacto($contactoDomiciliar);
        if (!$contactosDomiciliares) {
            $this->desactivarContactosDeDomicilio($idCliente);
            $this->crearContacto($contactoDomiciliar);
        }
        $this->db->trans_complete();
    }

    public function crearActualizarClienteNaturalBasicoTransaccional($persona,$dataPersona, $dataCliente, $contactoDomiciliar)
    {
        $this->db->trans_start();
        $idPersona = null;
        $idCliente = null;

        if (isset($persona['ID_PERSONA']) && $persona['ID_PERSONA'] != NULL)
        {
            $idPersona = $persona['ID_PERSONA'];

            $this->actualizarPersona($dataPersona, $persona['ID_PERSONA']);
        }
        else
        {
            /* SETEAR LA NATURALEZA DE LA PERSONA */
            $dataPersona['OCUPACION']=3;
            $idPersona = $this->crearPersona($dataPersona);
        }

        /* SE INSERTAN O MODIFICAN LOS DATOS DEL CLIENTE */
        if (isset($persona['ID_CLIENTE']) && $persona['ID_CLIENTE'] != NULL)
        {
            $idCliente = $persona['ID_CLIENTE'];
            $this->actualizarCliente($dataCliente, $persona['ID_CLIENTE']);
        }
        else
        {
            /* SETEAR LA NATURALEZA DE LA PERSONA */
            $dataCliente['ID_NATURALEZA_PERSONA'] = 1;

            /* INSERTAR CLIENTE */
            $idCliente = $this->crearCliente($dataCliente);

            /* INSERTAR CLIENTE NATURAL */
            $clienteNatural = array();
            $clienteNatural['ID_CLIENTE'] = $idCliente;
            $clienteNatural['ID_PERSONA'] = $idPersona;
            $this->crearClienteNatural($clienteNatural);
        }

        /* INSERCION O ACTUALIZACION DEL CONTACTO DE DOMICILIO DE LAS PERSONAS */

        $contactoDomiciliar['ID_CLIENTE'] = $idCliente;
        $contactoDomiciliar['ID_TIPO_CONTACTO'] = 2;
        $contactoDomiciliar['ESTADO'] = 1;

        $contactosDomiciliares = $this->buscarContacto($contactoDomiciliar);
        if (!$contactosDomiciliares) {
            $this->desactivarContactosDeDomicilio($idCliente);
            $this->crearContacto($contactoDomiciliar);
        }
        $this->db->trans_complete();
    }

    public function crearActualizarRepresentante($idRepresentante, $representanteData) {
        if($idRepresentante == NULL)
        {
            $this->db->insert('tab_representantes', $representanteData);
            return $this->db->insert_id();
        }
        else
        {
            $this->db->where('tab_representantes.ID_REPRESENTANTE', $idRepresentante);
            $this->db->update('tab_representantes', $representanteData);
            return $idRepresentante;
        }
    }

    public function crearActualizarClienteJuridicoTransaccional($data, $persona) {
        $this->db->trans_start();

        /* SE INSERTAN O MODIFICAN LOS DATOS DEL REPRESENTANTE */
        $representanteData = $data['REPRESENTANTE'];
        if($representanteData['PRIMER_NOMBRE'] != "" || $representanteData['APELLIDO_PATERNO']  != "" || $representanteData['SEGUNDO_NOMBRE']  != ""  || $representanteData['APELLIDO_MATERNO']  != "" )
        {
            $idRepresentante = $this->crearActualizarRepresentante($data['ID_REPRESENTANTE'], $representanteData);
            $data['ID_REPRESENTANTE'] = $idRepresentante;
        }
        if($representanteData['PRIMER_NOMBRE'] == "" && $representanteData['APELLIDO_PATERNO']  == "" && $representanteData['SEGUNDO_NOMBRE']  == ""  && $representanteData['APELLIDO_MATERNO']  == "" && $data['ID_REPRESENTANTE'] != "" )
        {
            $data['ID_REPRESENTANTE'] = NULL;
        }

        /* SE INSERTAN O MODIFICAN LOS DATOS DEL CLIENTE */
        $idCliente = NULL;
        $cliente = array();
        $cliente['TIPO_DOCUMENTO'] = 'RUC';
        $cliente['NRO_DOCUMENTO'] = $data['NRO_DOCUMENTO'];
        $cliente['ES_CONTRIBUYENTE_ESPECIAL'] = isset($data['ES_CONTRIBUYENTE_ESPECIAL'])?$data['ES_CONTRIBUYENTE_ESPECIAL']:0;
        $cliente['ID_TIPO_CONTRIBUYENTE'] = 2;

        if (isset($persona['ID_CLIENTE']) && $persona['ID_CLIENTE'] != NULL) {
            $idCliente = $persona['ID_CLIENTE'];
            $this->actualizarCliente($cliente, $persona['ID_CLIENTE']);

            $clienteJuridico = array();
            $clienteJuridico['ID_CLIENTE'] = $idCliente;
            $clienteJuridico['NOMBRE_COMERCIAL'] = $data['NOMBRE_COMERCIAL'];
            $clienteJuridico['RAZON_SOCIAL'] = $data['RAZON_SOCIAL'];
            $clienteJuridico['ES_PUBLICO'] = isset($data['ES_PUBLICO'])?$data['ES_PUBLICO']:0;
            $clienteJuridico['ES_SIN_FINES_DE_LUCRO'] = isset($data['ES_SIN_FINES_DE_LUCRO'])?$data['ES_SIN_FINES_DE_LUCRO']:0;
            $clienteJuridico['ID_REPRESENTANTE'] = $data['ID_REPRESENTANTE'];

            $this->actualizarClienteJuridico($clienteJuridico);

        } else {
            /* SETEAR LA NATURALEZA DE LA PERSONA */
            $cliente['ID_NATURALEZA_PERSONA'] = 1;

            /* INSERTAR CLIENTE */
            $idCliente = $this->crearCliente($cliente);

            /* INSERTAR CLIENTE juridico */
            $clienteJuridico = array();
            $clienteJuridico['ID_CLIENTE'] = $idCliente;
            $clienteJuridico['NOMBRE_COMERCIAL'] = $data['NOMBRE_COMERCIAL'];
            $clienteJuridico['RAZON_SOCIAL'] = $data['RAZON_SOCIAL'];
            $clienteJuridico['ES_PUBLICO'] = isset($data['ES_PUBLICO'])?$data['ES_PUBLICO']:0;
            $clienteJuridico['ES_SIN_FINES_DE_LUCRO'] = isset($data['ES_SIN_FINES_DE_LUCRO'])?$data['ES_SIN_FINES_DE_LUCRO']:0;
            $clienteJuridico['ID_REPRESENTANTE'] = $data['ID_REPRESENTANTE'];
            $this->crearClienteJuridico($clienteJuridico);
        }

        /*INSERTAR PERSONAS A CONTACTAR*/

        $personas_a_contactar = $data['PERSONA_CONTACTAR'];
        foreach ($personas_a_contactar as $personas_a_contactar) {
            $personas_a_contactar['ID_CLIENTE_JURIDICO'] = $idCliente;
            if($personas_a_contactar['ID_PERSONA_CONTACTAR'] != "") //Ya esta registrado
            {
                if($personas_a_contactar['NOMBRE_COMPLETO'] == "" )
                {
                    $this->actualizarPersonaAContactar(array('ID_CLIENTE_JURIDICO'=>$idCliente, 'ESTADO'=>0,'ID_PERSONA_CONTACTAR'=>$personas_a_contactar['ID_PERSONA_CONTACTAR']));
                }
                else {
                    $this->actualizarPersonaAContactar($personas_a_contactar);

                }
            }
            else {
                 if($personas_a_contactar['NOMBRE_COMPLETO'] != "") // crear nuevo
                 {
                     $this->crearPersonaAContactar($personas_a_contactar);
                 }
            }

        }

        /* INSERTAR DATOS DE CONTACTO */
        $contactoDomiciliar = $data['CONTACTO_DOMICILIO'];
        foreach ($contactoDomiciliar as $key => $value) {
            if ($value === '') {
                $contactoDomiciliar[$key] = NULL;
            }
        }
        $contactoDomiciliar['ID_CLIENTE'] = $idCliente;
        $contactoDomiciliar['ID_TIPO_CONTACTO'] = 2;
        $contactoDomiciliar['ESTADO'] = 1;

        $contactosDomiciliares = $this->buscarContacto($contactoDomiciliar);
        if (!$contactosDomiciliares) {
            $this->desactivarContactosDeDomicilio($idCliente);
            $this->crearContacto($contactoDomiciliar);
        }

        $this->db->trans_complete();
    }

    public function crearActualizarClienteJuridicoBasicoTransaccional($data) {
        $this->db->trans_start();
        /* SE INSERTAN O MODIFICAN LOS DATOS DEL CLIENTE */
        $cliente = array();
        $cliente['TIPO_DOCUMENTO'] = 'RUC';
        $cliente['NRO_DOCUMENTO'] = $data['NRO_DOCUMENTO'];
        $cliente['ID_TIPO_CONTRIBUYENTE'] = 2;

            /* SETEAR LA NATURALEZA DE LA PERSONA */
            $cliente['ID_NATURALEZA_PERSONA'] = 1;

            /* INSERTAR CLIENTE */
            $idCliente = $this->crearCliente($cliente);

            /* INSERTAR CLIENTE NATURAL */
            $clienteJuridico = array();
            $clienteJuridico['ID_CLIENTE'] = $idCliente;
            $clienteJuridico['NOMBRE_COMERCIAL'] = $data['NOMBRE_COMERCIAL'];
            $clienteJuridico['RAZON_SOCIAL'] = $data['NOMBRE_COMERCIAL'];
            $clienteJuridico['ID_REPRESENTANTE'] = $data['ID_REPRESENTANTE'];
            $this->crearClienteJuridico($clienteJuridico);

        /* INSERTAR DATOS DE CONTACTO */
        $contactoDomiciliar = $data['CONTACTO_DOMICILIO'];
        foreach ($contactoDomiciliar as $key => $value) {
            if ($value === '') {
                $contactoDomiciliar[$key] = NULL;
            }
        }
        $contactoDomiciliar['ID_CLIENTE'] = $idCliente;
        $contactoDomiciliar['ID_TIPO_CONTACTO'] = 2;
        $contactoDomiciliar['ESTADO'] = 1;

        $contactosDomiciliares = $this->buscarContacto($contactoDomiciliar);
        if (!$contactosDomiciliares) {
            $this->desactivarContactosDeDomicilio($idCliente);
            $this->crearContacto($contactoDomiciliar);
        }

        $this->db->trans_complete();
    }

    public function crearUsuario($p_nombre,$s_nombre,$p_apellido,$s_apellido)
    {
        $usuario=substr($p_nombre,0,1).$p_apellido; //wbaro
        if($this->existeUsuario($this->sustituir_caracteres_no_permitidos(strtolower($usuario))))
        {
             $usuario=$p_nombre.substr($p_apellido,0,1); //wilderb
             if($this->existeUsuario($this->sustituir_caracteres_no_permitidos(strtolower($usuario))))
             {
                 if($s_apellido!="" && $s_apellido!=NULL)
                 {
                    $usuario=substr($p_nombre,0,1).substr($p_apellido,0,1).$s_apellido; //wbfernandez
                    if($this->existeUsuario($this->sustituir_caracteres_no_permitidos(strtolower($usuario))))
                    {
                        while ($this->existeUsuario($this->sustituir_caracteres_no_permitidos(strtolower($usuario)))) //wbaro##
                        {
                            $usuario=substr($p_nombre,0,1).$p_apellido.$this->generateRandomString();
                        }
                    }
                 }
                 else
                 {
                    while ($this->existeUsuario($this->sustituir_caracteres_no_permitidos(strtolower($usuario)))) //wbaro##
                    {
                        $usuario=substr($p_nombre,0,1).$p_apellido.$this->generateRandomString();
                    }
                 }
             }
        }

        return $this->sustituir_caracteres_no_permitidos(strtolower($usuario));
    }

    public function existeUsuario($usuario)
    {
        $this->db->select('*');
        $this->db->from('tab_personas');
        $this->db->where('tab_personas.USUARIO', $usuario);
        $query = $this->db->get();
        $ds = $query->row_array();

        if (count($ds)>0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public function generateRandomString()
    {
        $length = 2;
        return substr(str_shuffle("0123456789"), 0, $length); //str_shuffle baraja la cadena, o sea cambia los numeros de posicion
    }

    public function sustituir_caracteres_no_permitidos($cadena)
    {
    $no_permitidas= array ("á","é","í","ó","ú","Á","É","Í","Ó","Ú","ñ","À","Ã","Ì","Ò","Ù","Ù","à ","è","ì","ò","ù","ç","Ç","â","ê","î","ô","û","Â","Ê","ÃŽ","Ô","Û","ü","ö","Ö","ï","ä","«","Ò","Ï","Ä","Ë");
    $permitidas= array ("a","e","i","o","u","A","E","I","O","U","n","N","A","E","I","O","U","a","e","i","o","u","c","C","a","e","i","o","u","A","E","I","O","U","u","o","O","i","a","e","U","I","A","E");
    $texto = str_replace($no_permitidas, $permitidas ,$cadena);
    return $texto;
    }

}


text:
import logging
# noinspection PyUnresolvedReferences
from .error import *
# noinspection PyUnresolvedReferences
from .models import (Show, ShowDetails, Season, Episode,
                     EpisodeDetails, EpisodeContainer)
from .funimationlater import FunimationLater
# noinspection PyUnresolvedReferences
from .constants import ShowTypes
# noinspection PyUnresolvedReferences
from .httpclient import HTTPClientBase
# noinspection PyUnresolvedReferences
from .response_handler import ResponseHandler

logging.getLogger(__name__).addHandler(logging.NullHandler())

__author__ = 'Aaron Frase'
__email__ = 'afrase91@gmail.com'
__version__ = '0.0.1'


text:
package com.alexandreroman.nrelay;

import static com.alexandreroman.nrelay.Constants.PREF_FILE;
import static com.alexandreroman.nrelay.Constants.SP_HOST_ADDRESS;
import static com.alexandreroman.nrelay.Constants.TAG;

import java.io.IOException;

import android.app.Fragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Fragment displaying information about NMEA relay.
 *
 * @author Alexandre Roman <alexandre.roman@gmail.com>
 */
public class InfoFragment extends Fragment implements NmeaRelayListener {
    private final ServiceConnection serviceConn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            nmeaRelayService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            final NmeaRelayService.Binder binder = (NmeaRelayService.Binder) service;
            nmeaRelayService = binder.getService();
            nmeaRelayService.addListener(InfoFragment.this);
            update(nmeaRelayService.getNmeaRelayContext());
        }
    };
    private static final SparseIntArray STATE_STRINGS = new SparseIntArray(7);
    private static final SparseIntArray STATE_ICONS = new SparseIntArray(7);
    static {
        STATE_STRINGS.put(NmeaRelayContext.State.GPS_DISABLED.ordinal(),
                R.string.state_gps_disabled);
        STATE_STRINGS.put(NmeaRelayContext.State.NETWORK_UNAVAILABLE.ordinal(),
                R.string.state_network_unavailable);
        STATE_STRINGS.put(NmeaRelayContext.State.RELAYING_NMEA.ordinal(), R.string.state_relaying);
        STATE_STRINGS.put(NmeaRelayContext.State.SERVER_UNREACHABLE.ordinal(),
                R.string.state_server_unreachable);
        STATE_STRINGS.put(NmeaRelayContext.State.STARTING.ordinal(), R.string.state_starting);
        STATE_STRINGS.put(NmeaRelayContext.State.STOPPED.ordinal(), R.string.state_stopped);
        STATE_STRINGS.put(NmeaRelayContext.State.WAITING_FOR_GPS_FIX.ordinal(),
                R.string.state_waiting_for_gps_fix);

        STATE_ICONS.put(NmeaRelayContext.State.GPS_DISABLED.ordinal(), R.drawable.state_red);
        STATE_ICONS.put(NmeaRelayContext.State.NETWORK_UNAVAILABLE.ordinal(), R.drawable.state_red);
        STATE_ICONS.put(NmeaRelayContext.State.RELAYING_NMEA.ordinal(), R.drawable.state_green);
        STATE_ICONS.put(NmeaRelayContext.State.SERVER_UNREACHABLE.ordinal(), R.drawable.state_red);
        STATE_ICONS.put(NmeaRelayContext.State.STARTING.ordinal(), R.drawable.state_orange);
        STATE_ICONS.put(NmeaRelayContext.State.STOPPED.ordinal(), R.drawable.state_red);
        STATE_ICONS.put(NmeaRelayContext.State.WAITING_FOR_GPS_FIX.ordinal(),
                R.drawable.state_orange);
    }
    private NmeaRelayService nmeaRelayService;
    private TextView stateTV;
    private TextView satellitesTV;
    private TextView accuracyTV;
    private MenuItem startStopAction;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.fragment_info, container);
        stateTV = (TextView) v.findViewById(R.id.info_state);
        satellitesTV = (TextView) v.findViewById(R.id.info_satellites);
        accuracyTV = (TextView) v.findViewById(R.id.info_accuracy);
        return v;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        stateTV = satellitesTV = accuracyTV = null;
        startStopAction = null;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().bindService(new Intent(getActivity(), NmeaRelayService.class), serviceConn,
                Context.BIND_IMPORTANT | Context.BIND_AUTO_CREATE);
        setHasOptionsMenu(true);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        startStopAction = menu.findItem(R.id.start_stop_action);
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.start_stop_action:
            onMenuStartStopAction();
            break;
        case R.id.settings_action:
            startActivity(new Intent(getActivity(), PreferencesActivity.class));
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void onMenuStartStopAction() {
        if (nmeaRelayService != null) {
            if (nmeaRelayService.getNmeaRelayContext().state == NmeaRelayContext.State.STOPPED) {
                final SharedPreferences prefs = getActivity().getSharedPreferences(PREF_FILE,
                        Context.MODE_PRIVATE);
                if (prefs.getString(SP_HOST_ADDRESS, null) == null) {
                    final Fragment f = ErrorDialog.newInstance(R.string.dialog_error,
                            R.string.error_no_host_address_set);
                    getFragmentManager().beginTransaction().add(f, "error").commit();
                    return;
                }

                try {
                    getActivity().startService(new Intent(getActivity(), NmeaRelayService.class));
                    nmeaRelayService.startNmeaRelay();
                } catch (IOException e) {
                    Log.w(TAG, "Failed to start NMEA relay", e);
                }
            } else {
                nmeaRelayService.stopNmeaRelay();
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (nmeaRelayService != null) {
            nmeaRelayService.addListener(this);
            update(nmeaRelayService.getNmeaRelayContext());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (nmeaRelayService != null) {
            nmeaRelayService.removeListener(this);
        }
        getActivity().unbindService(serviceConn);
    }

    @Override
    public void onNmeaRelayContextChanged(NmeaRelayContext context) {
        update(context);
    }

    private void update(NmeaRelayContext context) {
        final int accuracy = context.location == null ? 0 : (int) context.location.getAccuracy();
        final String accuracyStr = String.format(getString(R.string.accuracy), accuracy);
        accuracyTV.setText(accuracyStr);

        final String satellitesStr = String.format(getString(R.string.seen_satellites),
                context.satellitesInUse, context.satellitesInView);
        satellitesTV.setText(satellitesStr);

        stateTV.setText(STATE_STRINGS.get(context.state.ordinal()));

        final int stateDrawable;
        if (context.state == NmeaRelayContext.State.RELAYING_NMEA && context.location == null) {
            stateDrawable = R.drawable.state_orange;
        } else {
            stateDrawable = STATE_ICONS.get(context.state.ordinal());
        }
        stateTV.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(stateDrawable),
                null, null, null);

        if (startStopAction != null) {
            if (context.state == NmeaRelayContext.State.STOPPED) {
                startStopAction.setTitle(R.string.menu_start);
                startStopAction.setIcon(R.drawable.ic_action_play);
            } else {
                startStopAction.setTitle(R.string.menu_stop);
                startStopAction.setIcon(R.drawable.ic_action_stop);
            }
        }
    }
}


text: My template to start off a Django web project