text:
module VersionOne
class TableTodo < VersionOneRecord
  belongs_to :project, :inverse_of => :table_todos
  has_many :finished_table_todos, :inverse_of => :table_todo, :dependent => :destroy

  validates :name, :presence => true

  def done_for_table?(table)
    finished_table_todos.find_by_table_id(table.id) != nil
  end

  def done_by_for_table(table)
    return nil unless done_for_table?(table)
    finished_table_todos.find_by_table_id(table.id).account_name
  end

  def progress
    return 100 if project.table_count == 0
    100 * finished_table_todos.count / project.table_count
  end
end
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace 屏幕保护
{
    public partial class FormDoor : Form
    {
        private FormScreenSaver formScreenSaver;
        private FormPasswordCheck formPasswordCheck;
        private List<string> filePathList = new List<string>();
        private ListAllFile listAllFile;
        private Random random = new Random();
        private List<Image> imageList = new List<Image>();
        public FormDoor(FormScreenSaver formScreenSaver)
        {
            InitializeComponent();
            this.formScreenSaver = formScreenSaver;
            this.MouseWheel += new MouseEventHandler(FormDoor_MouseWheel);

            List<string> suffixList=new List<string>();
            suffixList.AddRange(new string[] { ".jpg", ".bmp", "jpeg", ".gif", ".png", ".ico" });
            listAllFile = new ListAllFile(filePathList, suffixList);
            Thread myThread = new Thread(ListAllNeedFile);
            myThread.IsBackground = true;
            myThread.Start();
        }
        private void ListAllNeedFile()
        {
            foreach (string drive in listAllFile.GetAllDrive())
            {
                listAllFile.StartFind(drive);
            }
            //MessageBox.Show("Over" + filePathList.Count);
        }
        private void FormDoor_MouseWheel(object sender, MouseEventArgs e)
        {
            double speed = ((double)e.Delta) / 120 / 50;
            if (speed > 0 && this.Opacity < 1)
            {
                this.Opacity += speed;
            }
            if (speed < 0 && this.Opacity > 0.1)
            {
                this.Opacity += speed;
            }
        }

        private void FormDoor_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (formScreenSaver.Password == String.Empty)
            {
                formScreenSaver.MyScreenKeyHook.KeyBoardHookStop();
                this.Close();
                formScreenSaver.Close();
            }
            else
            {
                if (formPasswordCheck == null)
                {
                    formPasswordCheck = new FormPasswordCheck(formScreenSaver, this);
                    formPasswordCheck.Show();
                }
                else
                {
                    formPasswordCheck.Visible = true;
                }
            }
        }

        private void FormDoor_MouseClick(object sender, MouseEventArgs e)
        {
            if (formPasswordCheck != null)
                formPasswordCheck.Visible = false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            int countFile = filePathList.Count;
            if (countFile != 0)
            {
                string selectedFilePath = filePathList[random.Next(countFile)];
                try
                {
                    using (Image image = Image.FromFile(selectedFilePath))
                    {
                        int x = random.Next(this.Width - 100);
                        int y = random.Next(this.Height - 100);
                        Graphics g = this.CreateGraphics();
                        g.TranslateTransform(x, y);
                        g.RotateTransform(random.Next(360));
                        g.DrawImage(image, 0, 0, image.Width, image.Height);
                    }
                }
                catch { }
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            timer2.Interval = random.Next(1000, 60000);
            Graphics g = this.CreateGraphics();
            g.Clear(this.BackColor);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
How to test redis+ELK

```
sudo fig build
sudo fig up -d
sudo fig logs
```

kibana http://host:9280/

elasticsearch http://host:9200/

plugin head http://host:9200/_plugin/head/

plugin HQ http://host:9200/_plugin/HQ/


text:
layout: post
date: 2009-06-23
time: "09:00:00"
author: "Greg Wilson"
title: Another New Version of the Slides
category: ["Content"]
---

A new(er) version of the slides has been posted at http://software-carpentry.org that includes styling changes courtesy of Ryan Feeley. There are still many minor formatting glitches; we'll fix them in the coming week, and post a schedule showing which lectures are going to be given when.

We've also updated the Guest Speakers page with bios and abstracts for the people who'll be talking at the MaRS Centre in Toronto on July 29.  Talks will run 1-6 pm, and will be followed by a wine and cheese.  The event is free, but will require advance registration—we'll post details here as soon as we have them.

Note: the guest speakers page has been retired.


text: mono /Users/Hugo/Dev/ContentSyncTool.exe stgop -c newglobalwww --putlive


text:
layout: post
title:  "5 Things I Learned in My First Month at a Startup"
date:   2015-08-11 17:48:00
categories: engineering
author: Josh Beam
comments: true
---

In a departure from the normal content of this blog, I wanted to talk briefly about some of (what I think) are some important things I've learned so far in my first month working for a Bay Area tech startup.

In no particular order (and at a very high level of abstraction and with as little fluff as possible)...

# 5) Don't come with a problem. Come with a working prototype.

A working prototype says much more about a proposed solution, than does talking about the proposed solution.

# 4) Be both purist and pragmatic

This is a careful balance of business goals vs. coding nirvana, ruthless pragmatism vs. lofty purism. In other words, it's both good to know exactly what the perfect solution *should* look like, and to know what compromises you have to make to have a working solution based on business timeline constraints.

# 3) Conflict breeds results (but always listen)

As our patient, level-headed CTO says, "One person scores, but the whole team gets them there." By "conflict" I don't mean the *bad* type of conflict. I mean the conflict that arises from a group of passionate people all trying to arrive at the best solution.

The opposite side of the coin is: communication. "Today, I will learn nothing by speaking, but much by listening." Beme engineer Matt Hackett (previously VP of Engineering at Tumblr) says: "Most important engineering skill: Humility."

# 2) The pieces eventually come together

When working on teams of engineers (perhaps in an Agile environment), all the pieces of the product seem scattered, but eventually, everything will begin to cleanly merge back into the product that everyone has been imagining it would be.

# 1) Work hard

You're it. You directly influence the success or failure of your company. Dwayne Johnson says, "always be the hardest worker in the room." This is a tough goal when everyone else is already working harder than everyone else in the room.

> Great companies don't hire skilled people and motivate them, they hire already motivated people and inspire them. People are either motivated or they are not. Unless you give motivated people something to believe in, something bigger than their job to work toward, they will motivate themselves to find a new job and you'll be stuck with whoever's left.

— Simon Sinek, Start with Why: How Great Leaders Inspire Everyone to Take Action


text:
var BT = require('../lib/bt');
require('chai').should();

describe('matching', function() {
    var bt;
    beforeEach(function() {
        bt = new BT();
    });
    it('should accept array replacement', function () {
        bt.match('page', function(ctx) {
            ctx.setTag('html');
            ctx.disableCssClassGeneration();
            ctx.disableDataAttrGeneration();
            return [
                {raw: '<!DOCTYPE>'},
                ctx.getJson()
            ];
        });
        bt.apply({ block: 'page' }).should.equal(
            '<!DOCTYPE>'
        );
    });
    it('should accept string replacement', function () {
        bt.match('page', function() {
            return 'Hello';
        });
        bt.apply({ block: 'page' }).should.equal('Hello');
    });
    it('should accept numeric replacement', function () {
        bt.match('page', function() {
            return 0;
        });
        bt.apply({ block: 'page' }).should.equal('0');
    });
    it('should match block and child', function () {
        bt.match('button', function(ctx) {
            ctx.setTag('span');
            ctx.disableDataAttrGeneration();
            ctx.setContent({ elem: 'text' });
        });
        bt.match('button__text', function(ctx) {
            ctx.setTag('i');
        });
        bt.apply({ block: 'button' }).should.equal('');
    });
    it('should multiple match block and child', function () {
        bt.match('button', function(ctx) {
            ctx.setTag('span');
            ctx.disableDataAttrGeneration();
            ctx.setContent([{ elem: 'icon' }, { elem: 'text' }]);
        });
        bt.match(['button__text', 'button__icon'], function(ctx) {
            ctx.setTag('i');
        });
        bt.apply({ block: 'button' }).should.equal(
            ''
        );
    });
    it('should match block and child using view', function () {
        bt.match('button_def', function(ctx) {
            ctx.setTag('span');
            ctx.disableDataAttrGeneration();
            ctx.setContent({ elem: 'text' });
        });
        bt.match('button_def__text', function(ctx) {
            ctx.setTag('i');
        });
        bt.apply({ block: 'button', view: 'def' }).should.equal(
            ''
        );
    });
    it('should match block and child using view ns', function () {
        bt.match('button_def*', function(ctx) {
            ctx.setTag('span');
            ctx.disableDataAttrGeneration();
            ctx.setContent({ elem: 'text' });
        });
        bt.match('button_def*__text', function(ctx) {
            ctx.setTag('i');
        });
        bt.apply({ block: 'button', view: 'def' }).should.equal(
            ''
        );
    });
    it('should match block and child using view ns', function () {
        bt.match('button_def*', function(ctx) {
            ctx.setTag('span');
            ctx.disableDataAttrGeneration();
            ctx.setContent({ elem: 'text' });
        });
        bt.match('button_def*__text', function(ctx) {
            ctx.setTag('i');
        });
        bt.apply({ block: 'button', view: 'def-xxx' }).should.equal(
            ''
        );
    });

    describe('block*', function () {
        beforeEach(function () {
            bt.match('button*', function (ctx) {
                ctx.setTag('span');
                ctx.disableDataAttrGeneration();
                ctx.setContent({elem: 'text'});
            });

            bt.match('button*__text', function (ctx) {
                ctx.setTag('i');
            });
        });

        it('should match block and element without view', function () {
            bt.apply({block: 'button'}).should.eq(
                ''
            );
        });

        it('should match block and element with view', function () {
            bt.apply({block: 'button', view: 'foo'}).should.eq(
                ''
            );

            bt.apply({block: 'button', view: 'foo-bar'}).should.eq(
                ''
            );
        });

        it('should match on most relevant matcher', function () {
            bt.match('button_foo*', function (ctx) {
                ctx.setTag('button');
                ctx.disableDataAttrGeneration();
                ctx.setContent({elem: 'text'});
            });
            bt.apply({block: 'button', view: 'foo-bar'}).should.eq(
                '<button class="button_foo-bar"></button>'
            );
        });

        it('should match on most relevant matcher using strict match', function () {
            bt.match('button_foo*', function (ctx) {
                ctx.setTag('button');
                ctx.disableDataAttrGeneration();
                ctx.setContent({elem: 'text'});
            });
            bt.match('button_foo-bar', function (ctx) {
                ctx.setTag('div');
                ctx.disableDataAttrGeneration();
                ctx.setContent({elem: 'text'});
            });
            bt.apply({block: 'button', view: 'foo-bar'}).should.eq(
                '

'
            );
        });

        it('should apply returned content', function () {
            bt.match('button', function (ctx) {
                ctx.setTag('button');
                ctx.disableDataAttrGeneration();
                ctx.setContent({elem: 'text'});
            });

            bt.match('button__text', function () {
                return 'Hello';
            });

            bt.apply({block: 'button'}).should.eq(
                '<button class="button">Hello</button>'
            );
        });
    });
});


text:
<Order OrderID="10848">
	<CustomerID>CONSH</CustomerID>
	<EmployeeID>7</EmployeeID>
	<OrderDate>1998-01-23T19:15:02</OrderDate>
	<RequiredDate>1998-02-20T02:50:01</RequiredDate>
	<ShippedDate>1998-01-29T22:44:39</ShippedDate>
	<ShipVia>2</ShipVia>
	<Freight>38.2400</Freight>
	<ShipName>Consolidated Holdings</ShipName>
	<ShipAddress>Berkeley Gardens 12  Brewery</ShipAddress>
	<ShipCity>London</ShipCity>
	<ShipRegion/>
	<ShipPostalCode>WX1 6LT</ShipPostalCode>
	<ShipCountry>UK</ShipCountry>
	<OrderDetails>
		<OrderDetail>
			<ProductID>5</ProductID>
			<UnitPrice>21.3500</UnitPrice>
			<Quantity>30</Quantity>
			<Discount>0</Discount>
		</OrderDetail>
		<OrderDetail>
			<ProductID>9</ProductID>
			<UnitPrice>97.0000</UnitPrice>
			<Quantity>3</Quantity>
			<Discount>0</Discount>
		</OrderDetail>
	</OrderDetails>
</Order>


text:
package bio.terra.service.rawls;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import bio.terra.app.configuration.SamConfiguration;
import bio.terra.app.model.rawls.WorkspaceDetails;
import bio.terra.app.model.rawls.WorkspaceResponse;
import bio.terra.common.category.Unit;
import bio.terra.common.exception.UnauthorizedException;
import bio.terra.common.iam.AuthenticatedUserRequest;
import bio.terra.model.ErrorModel;
import bio.terra.model.InaccessibleWorkspacePolicyModel;
import bio.terra.model.PolicyModel;
import bio.terra.model.ResourcePolicyModel;
import bio.terra.model.SamPolicyModel;
import bio.terra.model.WorkspacePolicyModel;
import bio.terra.service.auth.iam.IamResourceType;
import bio.terra.service.auth.iam.IamRole;
import bio.terra.service.auth.iam.sam.SamIam;
import bio.terra.service.configuration.ConfigEnum;
import bio.terra.service.configuration.ConfigurationService;
import java.util.List;
import java.util.UUID;
import org.broadinstitute.dsde.workbench.client.sam.ApiClient;
import org.broadinstitute.dsde.workbench.client.sam.api.GoogleApi;
import org.broadinstitute.dsde.workbench.client.sam.api.ResourcesApi;
import org.broadinstitute.dsde.workbench.client.sam.api.StatusApi;
import org.broadinstitute.dsde.workbench.client.sam.api.UsersApi;
import org.broadinstitute.dsde.workbench.client.sam.model.AccessPolicyMembershipV2;
import org.broadinstitute.dsde.workbench.client.sam.model.AccessPolicyResponseEntryV2;
import org.broadinstitute.dsde.workbench.client.sam.model.PolicyIdentifiers;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(properties = {"datarepo.testWithEmbeddedDatabase=false"})
@AutoConfigureMockMvc
@ActiveProfiles({"google", "unittest"})
@Category(Unit.class)
public class RawlsServiceTest {

  @Mock private SamConfiguration samConfig;
  @Mock private ConfigurationService configurationService;
  @Mock private ApiClient apiClient;
  @Mock private ResourcesApi samResourceApi;
  @Mock private StatusApi samStatusApi;
  @Mock private GoogleApi samGoogleApi;
  @Mock private UsersApi samUsersApi;

  @Mock private AuthenticatedUserRequest userReq;

  @MockBean private RawlsClient rawlsClient;
  @Autowired private RawlsService rawlsService;
  private SamIam samIam;
  private static final String OWNER_NAME = "owner";
  private static final String OWNER_EMAIL = "policy-email@firecloud.org";
  private static final String WORKSPACE_NAME = "testWorkspace";
  private static final String WORKSPACE_NAMEPACE = "testNamespace";
  private final UUID accessibleWorkspaceId = UUID.randomUUID();
  private final UUID inaccessibleWorkspaceId = UUID.randomUUID();
  private final UnauthorizedException inaccessibleWorkspaceException =
      new UnauthorizedException("Workspace inaccessible");

  @Before
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    samIam = spy(new SamIam(samConfig, configurationService));
    final String userToken = "some_token";
    when(userReq.getToken()).thenReturn(userToken);
    when(configurationService.getParameterValue(ConfigEnum.SAM_RETRY_MAXIMUM_WAIT_SECONDS))
        .thenReturn(0);
    when(configurationService.getParameterValue(ConfigEnum.SAM_RETRY_INITIAL_WAIT_SECONDS))
        .thenReturn(0);
    when(configurationService.getParameterValue(ConfigEnum.SAM_OPERATION_TIMEOUT_SECONDS))
        .thenReturn(0);
    // Mock out samApi, samStatusApi, samGoogleApi, and samUsersApi in individual tests as needed
    doAnswer(a -> samResourceApi).when(samIam).samResourcesApi(userToken);
    // Mock out the lower level client in individual as needed
    when(samResourceApi.getApiClient()).thenAnswer(a -> apiClient);

    when(rawlsClient.getWorkspace(accessibleWorkspaceId, userReq))
        .thenReturn(
            new WorkspaceResponse()
                .workspace(
                    new WorkspaceDetails()
                        .workspaceId(accessibleWorkspaceId.toString())
                        .name(WORKSPACE_NAME)
                        .namespace(WORKSPACE_NAMEPACE)));

    when(rawlsClient.getWorkspace(inaccessibleWorkspaceId, userReq))
        .thenThrow(inaccessibleWorkspaceException);
  }

  private PolicyIdentifiers createPolicyIdentifiers(IamResourceType resourceType, UUID resourceId) {
    return new PolicyIdentifiers()
        .policyName(OWNER_NAME)
        .policyEmail(OWNER_EMAIL)
        .resourceTypeName(resourceType.toString())
        .resourceId(resourceId.toString());
  }

  private ResourcePolicyModel createResourcePolicyModel(
      IamResourceType resourceType, UUID resourceId) {
    return new ResourcePolicyModel()
        .policyName(OWNER_NAME)
        .policyEmail(OWNER_EMAIL)
        .resourceTypeName(resourceType.toString())
        .resourceId(resourceId);
  }

  @Test
  public void testRetrievePoliciesAndEmailsWorkspace() throws Exception {
    final UUID snapshotId = UUID.randomUUID();
    final UUID nonWorkspaceResourceId = UUID.randomUUID();
    final String policyEmail = "policygroup@firecloud.org";
    final String memberEmail = "a@a.com";

    var policyIdentifiers =
        List.of(
            createPolicyIdentifiers(IamResourceType.WORKSPACE, accessibleWorkspaceId),
            createPolicyIdentifiers(IamResourceType.WORKSPACE, inaccessibleWorkspaceId),
            createPolicyIdentifiers(IamResourceType.DATASNAPSHOT, nonWorkspaceResourceId));
    var workspacePolicy =
        new AccessPolicyResponseEntryV2()
            .policyName(IamRole.READER.toString())
            .email(policyEmail)
            .policy(
                new AccessPolicyMembershipV2()
                    .addMemberEmailsItem(memberEmail)
                    .memberPolicies(policyIdentifiers));
    when(samResourceApi.listResourcePoliciesV2(
            IamResourceType.DATASNAPSHOT.toString(), snapshotId.toString()))
        .thenReturn(List.of(workspacePolicy));

    var resourcePolicyModels =
        List.of(
            createResourcePolicyModel(IamResourceType.WORKSPACE, accessibleWorkspaceId),
            createResourcePolicyModel(IamResourceType.WORKSPACE, inaccessibleWorkspaceId),
            createResourcePolicyModel(IamResourceType.DATASNAPSHOT, nonWorkspaceResourceId));
    List<SamPolicyModel> samPolicyModels =
        samIam.retrievePolicies(userReq, IamResourceType.DATASNAPSHOT, snapshotId);
    assertThat(
        "Snapshot resource policies for all resource types are returned by SAM",
        samPolicyModels,
        is(
            List.of(
                new SamPolicyModel()
                    .name(IamRole.READER.toString())
                    .addMembersItem(memberEmail)
                    .memberPolicies(resourcePolicyModels))));

    var workspacePolicyModels = rawlsService.resolvePolicyEmails(samPolicyModels.get(0), userReq);
    verify(rawlsClient, times(1)).getWorkspace(accessibleWorkspaceId, userReq);
    verify(rawlsClient, times(1)).getWorkspace(inaccessibleWorkspaceId, userReq);

    assertThat(
        "Workspace accessible to the user is included in returned policy models",
        workspacePolicyModels.accessible(),
        is(
            List.of(
                new WorkspacePolicyModel()
                    .workspaceName(WORKSPACE_NAME)
                    .workspaceNamespace(WORKSPACE_NAMEPACE)
                    .workspaceId(accessibleWorkspaceId)
                    .workspaceLink(
                        "https://bvdp-saturn-dev.appspot.com/#workspaces/testNamespace/testWorkspace")
                    .addWorkspacePoliciesItem(
                        new PolicyModel().name(OWNER_NAME).addMembersItem(OWNER_EMAIL)))));

    assertThat(
        "Workspace inaccessible to the user is included in returned policy models",
        workspacePolicyModels.inaccessible(),
        is(
            List.of(
                new InaccessibleWorkspacePolicyModel()
                    .workspaceId(inaccessibleWorkspaceId)
                    .addWorkspacePoliciesItem(
                        new PolicyModel().name(OWNER_NAME).addMembersItem(OWNER_EMAIL))
                    .error(
                        new ErrorModel().message(inaccessibleWorkspaceException.getMessage())))));
  }
}


text:
package org.semispace.comet.jsonschema.schemabean;

import java.util.Map;

/**
 *
 */
public class SchemaRoot {
    private String name;
    private Map<String, SchemaItem> properties;

    public Map<String, SchemaItem> getProperties() {
        return properties;
    }

    public void setProperties(Map<String, SchemaItem> properties) {
        this.properties = properties;
    }

    public String getName() {

        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


text:
package gov.nih.nci.restgen.mapping.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "Method")
@XmlRootElement(name="Method")
public class Method {

	public static final String GET = "GET";
	public static final String PUT = "PUT";
	public static final String POST = "POST";
	public static final String DELETE = "DELETE";

	@XmlAttribute
	private String name;

	@XmlAttribute
	private String pathName;

	@XmlElementRef()
	private Implementation implementation;

	public String getPathName() {
		return pathName;
	}

	public void setPathName(String pathName) {
		this.pathName = pathName;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Implementation getImplementation() {
		return implementation;
	}

	public void setImplementation(Implementation implementation) {
		this.implementation = implementation;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((implementation == null) ? 0 : implementation.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Method other = (Method) obj;
		if (implementation == null) {
			if (other.implementation != null)
				return false;
		} else if (!implementation.equals(other.implementation))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

}


text:
<?php

namespace ilabpro01\BackFotogBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use ilabpro01\GeneralBundle\Form\EventListener\AddCityFieldSubscriber;
use ilabpro01\GeneralBundle\Form\EventListener\AddProvinceFieldSubscriber;
use ilabpro01\GeneralBundle\Form\EventListener\AddCountryFieldSubscriber;

/*
 * Cuando el fotógrafo tiene un plan vigente
 * No se muestra combo para entidad Plan, se agrega en modifFotografo como cuadro de texto readonly
 */

class FotografoType2 extends AbstractType
{

    public function buildForm(FormBuilderInterface $generador, array $opciones){

        $propertyPathToCity = 'ciudad';

        $generador->add('id','hidden', array(
        ));
        $generador->add('nombre','text', array(
            'label' =>'Nombre ',
            'max_length' =>50,
        ));
        $generador->add('apellido','text', array(
            'label' =>'Apellido ',
            'max_length' =>50,
        ));
        $generador->add('email','text', array(
            'label' =>'Email ',
            'max_length' =>50,
        ));
        $generador->add('usuario','text', array(
            'label' =>'Usuario ',
            'max_length' =>30,
        ));
        $generador->add('contrasenia','text', array(
            'label' =>'Contraseña ',
            'max_length' =>30,
        ));
        $generador->add('telefono','text', array(
            'label' =>'Teléfono ',
            'max_length' =>20,
        ));
        $generador->add('estudio','text', array(
            'label' =>'Estudio ',
            'max_length' =>50,
        ));
        $generador->add('calleEstudio','text', array(
            'label' =>'Calle Estudio',
            'max_length' =>50,
        ));
        $generador->add('numeroEstudio','text', array(
            'label' =>'Número Estudio',
            'max_length' =>50,
            'required' =>false,
        ));
        $generador->add('telefonoEstudio','text', array(
            'label' =>'Teléfono Estudio',
            'max_length' =>50,
            'required' =>false,
        ));
        $generador
                ->addEventSubscriber(new AddCountryFieldSubscriber($propertyPathToCity))
                ->addEventSubscriber(new AddProvinceFieldSubscriber($propertyPathToCity))
                ->addEventSubscriber(new AddCityFieldSubscriber($propertyPathToCity))
        ;

    }

    public function getDefaultOptions(array $options) {
        return array('data_class' => 'ilabpro01\GeneralBundle\Entity\fotografo',);
    }

    public function getName() {
        return 'nombre';
    }

}


text:
##
# Import Modules
#
from __future__ import absolute_import
import re
import Common.EdkLogger as EdkLogger
from Common.BuildToolError import *
from .UniClassObject import *
from io import BytesIO
from struct import pack, unpack
from Common.LongFilePathSupport import OpenLongFilePath as open

##
# Static definitions
#
EFI_HII_SIBT_END = '0x00'
EFI_HII_SIBT_STRING_SCSU = '0x10'
EFI_HII_SIBT_STRING_SCSU_FONT = '0x11'
EFI_HII_SIBT_STRINGS_SCSU = '0x12'
EFI_HII_SIBT_STRINGS_SCSU_FONT = '0x13'
EFI_HII_SIBT_STRING_UCS2 = '0x14'
EFI_HII_SIBT_STRING_UCS2_FONT = '0x15'
EFI_HII_SIBT_STRINGS_UCS2 = '0x16'
EFI_HII_SIBT_STRINGS_UCS2_FONT = '0x17'
EFI_HII_SIBT_DUPLICATE = '0x20'
EFI_HII_SIBT_SKIP2 = '0x21'
EFI_HII_SIBT_SKIP1 = '0x22'
EFI_HII_SIBT_EXT1 = '0x30'
EFI_HII_SIBT_EXT2 = '0x31'
EFI_HII_SIBT_EXT4 = '0x32'
EFI_HII_SIBT_FONT = '0x40'

EFI_HII_PACKAGE_STRINGS = '0x04'
EFI_HII_PACKAGE_FORM = '0x02'

StringPackageType = EFI_HII_PACKAGE_STRINGS
StringPackageForm = EFI_HII_PACKAGE_FORM
StringBlockType = EFI_HII_SIBT_STRING_UCS2
StringSkipType = EFI_HII_SIBT_SKIP2

HexHeader = '0x'

COMMENT = '// '
DEFINE_STR = '#define'
COMMENT_DEFINE_STR = COMMENT + DEFINE_STR
NOT_REFERENCED = 'not referenced'
COMMENT_NOT_REFERENCED = ' ' + COMMENT + NOT_REFERENCED
CHAR_ARRAY_DEFIN = 'unsigned char'
COMMON_FILE_NAME = 'Strings'
STRING_TOKEN = re.compile('STRING_TOKEN *\(([A-Z0-9_]+) *\)', re.MULTILINE | re.UNICODE)

EFI_HII_ARRAY_SIZE_LENGTH = 4
EFI_HII_PACKAGE_HEADER_LENGTH = 4
EFI_HII_HDR_SIZE_LENGTH = 4
EFI_HII_STRING_OFFSET_LENGTH = 4
EFI_STRING_ID = 1
EFI_STRING_ID_LENGTH = 2
EFI_HII_LANGUAGE_WINDOW = 0
EFI_HII_LANGUAGE_WINDOW_LENGTH = 2
EFI_HII_LANGUAGE_WINDOW_NUMBER = 16
EFI_HII_STRING_PACKAGE_HDR_LENGTH = EFI_HII_PACKAGE_HEADER_LENGTH + EFI_HII_HDR_SIZE_LENGTH + EFI_HII_STRING_OFFSET_LENGTH + EFI_HII_LANGUAGE_WINDOW_LENGTH * EFI_HII_LANGUAGE_WINDOW_NUMBER + EFI_STRING_ID_LENGTH

H_C_FILE_HEADER = ['//', \
                   '//  DO NOT EDIT -- auto-generated file', \
                   '//', \
                   '//  This file is generated by the StrGather utility', \
                   '//']
LANGUAGE_NAME_STRING_NAME = '$LANGUAGE_NAME'
PRINTABLE_LANGUAGE_NAME_STRING_NAME = '$PRINTABLE_LANGUAGE_NAME'

## Convert a dec number to a hex string
#
# Convert a dec number to a formatted hex string in length digit
# The digit is set to default 8
# The hex string starts with "0x"
# DecToHexStr(1000) is '0x000003E8'
# DecToHexStr(1000, 6) is '0x0003E8'
#
# @param Dec:    The number in dec format
# @param Digit:  The needed digit of hex string
#
# @retval:       The formatted hex string
#
def DecToHexStr(Dec, Digit = 8):
    return '0x{0:0{1}X}'.format(Dec, Digit)

## Convert a dec number to a hex list
#
# Convert a dec number to a formatted hex list in size digit
# The digit is set to default 8
# DecToHexList(1000) is ['0xE8', '0x03', '0x00', '0x00']
# DecToHexList(1000, 6) is ['0xE8', '0x03', '0x00']
#
# @param Dec:    The number in dec format
# @param Digit:  The needed digit of hex list
#
# @retval:       A list for formatted hex string
#
def DecToHexList(Dec, Digit = 8):
    Hex = '{0:0{1}X}'.format(Dec, Digit)
    return ["0x" + Hex[Bit:Bit + 2] for Bit in range(Digit - 2, -1, -2)]

## Convert a acsii string to a hex list
#
# Convert a acsii string to a formatted hex list
# AscToHexList('en-US') is ['0x65', '0x6E', '0x2D', '0x55', '0x53']
#
# @param Ascii:  The acsii string
#
# @retval:       A list for formatted hex string
#
def AscToHexList(Ascii):
    return ['0x{0:02X}'.format(ord(Item)) for Item in Ascii]

## Create content of .h file
#
# Create content of .h file
#
# @param BaseName:        The basename of strings
# @param UniObjectClass   A UniObjectClass instance
# @param IsCompatibleMode Compatible mode
# @param UniGenCFlag      UniString is generated into AutoGen C file when it is set to True
#
# @retval Str:           A string of .h file content
#
def CreateHFileContent(BaseName, UniObjectClass, IsCompatibleMode, UniGenCFlag):
    Str = []
    ValueStartPtr = 60
    Line = COMMENT_DEFINE_STR + ' ' + LANGUAGE_NAME_STRING_NAME + ' ' * (ValueStartPtr - len(DEFINE_STR + LANGUAGE_NAME_STRING_NAME)) + DecToHexStr(0, 4) + COMMENT_NOT_REFERENCED
    Str = WriteLine(Str, Line)
    Line = COMMENT_DEFINE_STR + ' ' + PRINTABLE_LANGUAGE_NAME_STRING_NAME + ' ' * (ValueStartPtr - len(DEFINE_STR + PRINTABLE_LANGUAGE_NAME_STRING_NAME)) + DecToHexStr(1, 4) + COMMENT_NOT_REFERENCED
    Str = WriteLine(Str, Line)
    UnusedStr = ''

    #Group the referred/Unused STRING token together.
    for Index in range(2, len(UniObjectClass.OrderedStringList[UniObjectClass.LanguageDef[0][0]])):
        StringItem = UniObjectClass.OrderedStringList[UniObjectClass.LanguageDef[0][0]][Index]
        Name = StringItem.StringName
        Token = StringItem.Token
        Referenced = StringItem.Referenced
        if Name is not None:
            Line = ''
            if Referenced == True:
                if (ValueStartPtr - len(DEFINE_STR + Name)) <= 0:
                    Line = DEFINE_STR + ' ' + Name + ' ' + DecToHexStr(Token, 4)
                else:
                    Line = DEFINE_STR + ' ' + Name + ' ' * (ValueStartPtr - len(DEFINE_STR + Name)) + DecToHexStr(Token, 4)
                Str = WriteLine(Str, Line)
            else:
                if (ValueStartPtr - len(DEFINE_STR + Name)) <= 0:
                    Line = COMMENT_DEFINE_STR + ' ' + Name + ' ' + DecToHexStr(Token, 4) + COMMENT_NOT_REFERENCED
                else:
                    Line = COMMENT_DEFINE_STR + ' ' + Name + ' ' * (ValueStartPtr - len(DEFINE_STR + Name)) + DecToHexStr(Token, 4) + COMMENT_NOT_REFERENCED
                UnusedStr = WriteLine(UnusedStr, Line)

    Str.extend( UnusedStr)

    Str = WriteLine(Str, '')
    if IsCompatibleMode or UniGenCFlag:
        Str = WriteLine(Str, 'extern unsigned char ' + BaseName + 'Strings[];')
    return "".join(Str)

## Create a complete .h file
#
# Create a complet .h file with file header and file content
#
# @param BaseName:        The basename of strings
# @param UniObjectClass   A UniObjectClass instance
# @param IsCompatibleMode Compatible mode
# @param UniGenCFlag      UniString is generated into AutoGen C file when it is set to True
#
# @retval Str:           A string of complete .h file
#
def CreateHFile(BaseName, UniObjectClass, IsCompatibleMode, UniGenCFlag):
    HFile = WriteLine('', CreateHFileContent(BaseName, UniObjectClass, IsCompatibleMode, UniGenCFlag))

    return "".join(HFile)

## Create a buffer to store all items in an array
#
# @param BinBuffer   Buffer to contain Binary data.
# @param Array:      The array need to be formatted
#
def CreateBinBuffer(BinBuffer, Array):
    for Item in Array:
        BinBuffer.write(pack("B", int(Item, 16)))

## Create a formatted string all items in an array
#
# Use ',' to join each item in an array, and break an new line when reaching the width (default is 16)
#
# @param Array:      The array need to be formatted
# @param Width:      The line length, the default value is set to 16
#
# @retval ArrayItem: A string for all formatted array items
#
def CreateArrayItem(Array, Width = 16):
    MaxLength = Width
    Index = 0
    Line = '  '
    ArrayItem = []

    for Item in Array:
        if Index < MaxLength:
            Line = Line + Item + ',  '
            Index = Index + 1
        else:
            ArrayItem = WriteLine(ArrayItem, Line)
            Line = '  ' + Item + ',  '
            Index = 1
    ArrayItem = Write(ArrayItem, Line.rstrip())

    return "".join(ArrayItem)

## CreateCFileStringValue
#
# Create a line with string value
#
# @param Value:  Value of the string
#
# @retval Str:   A formatted string with string value
#

def CreateCFileStringValue(Value):
    Value = [StringBlockType] + Value
    Str = WriteLine('', CreateArrayItem(Value))

    return "".join(Str)

## GetFilteredLanguage
#
# apply get best language rules to the UNI language code list
#
# @param UniLanguageList:  language code definition list in *.UNI file
# @param LanguageFilterList:  language code filter list of RFC4646 format in DSC file
#
# @retval UniLanguageListFiltered:   the filtered language code
#
def GetFilteredLanguage(UniLanguageList, LanguageFilterList):
    UniLanguageListFiltered = []
    # if filter list is empty, then consider there is no filter
    if LanguageFilterList == []:
        UniLanguageListFiltered = UniLanguageList
        return UniLanguageListFiltered
    for Language in LanguageFilterList:
        # first check for exact match
        if Language in UniLanguageList:
            if Language not in UniLanguageListFiltered:
                UniLanguageListFiltered.append(Language)
        # find the first one with the same/equivalent primary tag
        else:
            if Language.find('-') != -1:
                PrimaryTag = Language[0:Language.find('-')].lower()
            else:
                PrimaryTag = Language

            if len(PrimaryTag) == 3:
                PrimaryTag = LangConvTable.get(PrimaryTag)

            for UniLanguage in UniLanguageList:
                if UniLanguage.find('-') != -1:
                    UniLanguagePrimaryTag = UniLanguage[0:UniLanguage.find('-')].lower()
                else:
                    UniLanguagePrimaryTag = UniLanguage

                if len(UniLanguagePrimaryTag) == 3:
                    UniLanguagePrimaryTag = LangConvTable.get(UniLanguagePrimaryTag)

                if PrimaryTag == UniLanguagePrimaryTag:
                    if UniLanguage not in UniLanguageListFiltered:
                        UniLanguageListFiltered.append(UniLanguage)
                    break
            else:
                # Here is rule 3 for "get best language"
                # If tag is not listed in the Unicode file, the default ("en") tag should be used for that language
                # for better processing, find the one that best suit for it.
                DefaultTag = 'en'
                if DefaultTag not in UniLanguageListFiltered:
                    # check whether language code with primary code equivalent with DefaultTag already in the list, if so, use that
                    for UniLanguage in UniLanguageList:
                        if UniLanguage.startswith('en-') or UniLanguage.startswith('eng-'):
                            if UniLanguage not in UniLanguageListFiltered:
                                UniLanguageListFiltered.append(UniLanguage)
                            break
                    else:
                        UniLanguageListFiltered.append(DefaultTag)
    return  UniLanguageListFiltered

## Create content of .c file
#
# Create content of .c file
#
# @param BaseName:        The basename of strings
# @param UniObjectClass   A UniObjectClass instance
# @param IsCompatibleMode Compatible mode
# @param UniBinBuffer     UniBinBuffer to contain UniBinary data.
# @param FilterInfo       Platform language filter information
#
# @retval Str:           A string of .c file content
#
def CreateCFileContent(BaseName, UniObjectClass, IsCompatibleMode, UniBinBuffer, FilterInfo):
    #
    # Init array length
    #
    TotalLength = EFI_HII_ARRAY_SIZE_LENGTH
    Str = ''
    Offset = 0

    EDK2Module = FilterInfo[0]
    if EDK2Module:
        LanguageFilterList = FilterInfo[1]
    else:
        # EDK module is using ISO639-2 format filter, convert to the RFC4646 format
        LanguageFilterList = [LangConvTable.get(F.lower()) for F in FilterInfo[1]]

    UniLanguageList = []
    for IndexI in range(len(UniObjectClass.LanguageDef)):
        UniLanguageList += [UniObjectClass.LanguageDef[IndexI][0]]

    UniLanguageListFiltered = GetFilteredLanguage(UniLanguageList, LanguageFilterList)

    #
    # Create lines for each language's strings
    #
    for IndexI in range(len(UniObjectClass.LanguageDef)):
        Language = UniObjectClass.LanguageDef[IndexI][0]
        if Language not in UniLanguageListFiltered:
            continue

        StringBuffer = BytesIO()
        StrStringValue = ''
        ArrayLength = 0
        NumberOfUseOtherLangDef = 0
        Index = 0
        for IndexJ in range(1, len(UniObjectClass.OrderedStringList[UniObjectClass.LanguageDef[IndexI][0]])):
            Item = UniObjectClass.OrderedStringListByToken[Language][IndexJ]

            Name = Item.StringName
            Value = Item.StringValueByteList
            Referenced = Item.Referenced
            Token = Item.Token
            UseOtherLangDef = Item.UseOtherLangDef

            if UseOtherLangDef != '' and Referenced:
                NumberOfUseOtherLangDef = NumberOfUseOtherLangDef + 1
                Index = Index + 1
            else:
                if NumberOfUseOtherLangDef > 0:
                    StrStringValue = WriteLine(StrStringValue, CreateArrayItem([StringSkipType] + DecToHexList(NumberOfUseOtherLangDef, 4)))
                    CreateBinBuffer (StringBuffer, ([StringSkipType] + DecToHexList(NumberOfUseOtherLangDef, 4)))
                    NumberOfUseOtherLangDef = 0
                    ArrayLength = ArrayLength + 3
                if Referenced and Item.Token > 0:
                    Index = Index + 1
                    StrStringValue = WriteLine(StrStringValue, "// %s: %s:%s" % (DecToHexStr(Index, 4), Name, DecToHexStr(Token, 4)))
                    StrStringValue = Write(StrStringValue, CreateCFileStringValue(Value))
                    CreateBinBuffer (StringBuffer, [StringBlockType] + Value)
                    ArrayLength = ArrayLength + Item.Length + 1 # 1 is for the length of string type

        #
        # EFI_HII_PACKAGE_HEADER
        #
        Offset = EFI_HII_STRING_PACKAGE_HDR_LENGTH + len(Language) + 1
        ArrayLength = Offset + ArrayLength + 1

        #
        # Create PACKAGE HEADER
        #
        Str = WriteLine(Str, '// PACKAGE HEADER\n')
        TotalLength = TotalLength + ArrayLength

        List = DecToHexList(ArrayLength, 6) + \
               [StringPackageType] + \
               DecToHexList(Offset) + \
               DecToHexList(Offset) + \
               DecToHexList(EFI_HII_LANGUAGE_WINDOW, EFI_HII_LANGUAGE_WINDOW_LENGTH * 2) * EFI_HII_LANGUAGE_WINDOW_NUMBER + \
               DecToHexList(EFI_STRING_ID, 4) + \
               AscToHexList(Language) + \
               DecToHexList(0, 2)
        Str = WriteLine(Str, CreateArrayItem(List, 16) + '\n')

        #
        # Create PACKAGE DATA
        #
        Str = WriteLine(Str, '// PACKAGE DATA\n')
        Str = Write(Str, StrStringValue)

        #
        # Add an EFI_HII_SIBT_END at last
        #
        Str = WriteLine(Str, '  ' + EFI_HII_SIBT_END + ",")

        #
        # Create binary UNI string
        #
        if UniBinBuffer:
            CreateBinBuffer (UniBinBuffer, List)
            UniBinBuffer.write (StringBuffer.getvalue())
            UniBinBuffer.write (pack("B", int(EFI_HII_SIBT_END, 16)))
        StringBuffer.close()

    #
    # Create line for string variable name
    # "unsigned char $(BaseName)Strings[] = {"
    #
    AllStr = WriteLine('', CHAR_ARRAY_DEFIN + ' ' + BaseName + COMMON_FILE_NAME + '[] = {\n')

    if IsCompatibleMode:
        #
        # Create FRAMEWORK_EFI_HII_PACK_HEADER in compatible mode
        #
        AllStr = WriteLine(AllStr, '// FRAMEWORK PACKAGE HEADER Length')
        AllStr = WriteLine(AllStr, CreateArrayItem(DecToHexList(TotalLength + 2)) + '\n')
        AllStr = WriteLine(AllStr, '// FRAMEWORK PACKAGE HEADER Type')
        AllStr = WriteLine(AllStr, CreateArrayItem(DecToHexList(2, 4)) + '\n')
    else:
        #
        # Create whole array length in UEFI mode
        #
        AllStr = WriteLine(AllStr, '// STRGATHER_OUTPUT_HEADER')
        AllStr = WriteLine(AllStr, CreateArrayItem(DecToHexList(TotalLength)) + '\n')

    #
    # Join package data
    #
    AllStr = Write(AllStr, Str)

    return "".join(AllStr)

## Create end of .c file
#
# Create end of .c file
#
# @retval Str:           A string of .h file end
#
def CreateCFileEnd():
    Str = Write('', '};')
    return Str

## Create a .c file
#
# Create a complete .c file
#
# @param BaseName:        The basename of strings
# @param UniObjectClass   A UniObjectClass instance
# @param IsCompatibleMode Compatible Mode
# @param FilterInfo       Platform language filter information
#
# @retval CFile:          A string of complete .c file
#
def CreateCFile(BaseName, UniObjectClass, IsCompatibleMode, FilterInfo):
    CFile = ''
    CFile = WriteLine(CFile, CreateCFileContent(BaseName, UniObjectClass, IsCompatibleMode, None, FilterInfo))
    CFile = WriteLine(CFile, CreateCFileEnd())
    return "".join(CFile)

## GetFileList
#
# Get a list for all files
#
# @param IncludeList:  A list of all path to be searched
# @param SkipList:     A list of all types of file could be skipped
#
# @retval FileList:    A list of all files found
#
def GetFileList(SourceFileList, IncludeList, SkipList):
    if IncludeList is None:
        EdkLogger.error("UnicodeStringGather", AUTOGEN_ERROR, "Include path for unicode file is not defined")

    FileList = []
    if SkipList is None:
        SkipList = []

    for File in SourceFileList:
        for Dir in IncludeList:
            if not os.path.exists(Dir):
                continue
            File = os.path.join(Dir, File.Path)
            #
            # Ignore Dir
            #
            if os.path.isfile(File) != True:
                continue
            #
            # Ignore file listed in skip list
            #
            IsSkip = False
            for Skip in SkipList:
                if os.path.splitext(File)[1].upper() == Skip.upper():
                    EdkLogger.verbose("Skipped %s for string token uses search" % File)
                    IsSkip = True
                    break

            if not IsSkip:
                FileList.append(File)

            break

    return FileList

## SearchString
#
# Search whether all string defined in UniObjectClass are referenced
# All string used should be set to Referenced
#
# @param UniObjectClass:  Input UniObjectClass
# @param FileList:        Search path list
# @param IsCompatibleMode Compatible Mode
#
# @retval UniObjectClass: UniObjectClass after searched
#
def SearchString(UniObjectClass, FileList, IsCompatibleMode):
    if FileList == []:
        return UniObjectClass

    for File in FileList:
        if os.path.isfile(File):
            Lines = open(File, 'r')
            for Line in Lines:
                for StrName in STRING_TOKEN.findall(Line):
                    EdkLogger.debug(EdkLogger.DEBUG_5, "Found string identifier: " + StrName)
                    UniObjectClass.SetStringReferenced(StrName)

    UniObjectClass.ReToken()

    return UniObjectClass

## GetStringFiles
#
# This function is used for UEFI2.1 spec
#
#
def GetStringFiles(UniFilList, SourceFileList, IncludeList, IncludePathList, SkipList, BaseName, IsCompatibleMode = False, ShellMode = False, UniGenCFlag = True, UniGenBinBuffer = None, FilterInfo = [True, []]):
    if len(UniFilList) > 0:
        if ShellMode:
            #
            # support ISO 639-2 codes in .UNI files of EDK Shell
            #
            Uni = UniFileClassObject(sorted (UniFilList), True, IncludePathList)
        else:
            Uni = UniFileClassObject(sorted (UniFilList), IsCompatibleMode, IncludePathList)
    else:
        EdkLogger.error("UnicodeStringGather", AUTOGEN_ERROR, 'No unicode files given')

    FileList = GetFileList(SourceFileList, IncludeList, SkipList)

    Uni = SearchString(Uni, sorted (FileList), IsCompatibleMode)

    HFile = CreateHFile(BaseName, Uni, IsCompatibleMode, UniGenCFlag)
    CFile = None
    if IsCompatibleMode or UniGenCFlag:
        CFile = CreateCFile(BaseName, Uni, IsCompatibleMode, FilterInfo)
    if UniGenBinBuffer:
        CreateCFileContent(BaseName, Uni, IsCompatibleMode, UniGenBinBuffer, FilterInfo)

    return HFile, CFile

#
# Write an item
#
def Write(Target, Item):
    if isinstance(Target,str):
        Target = [Target]
    if not Target:
        Target = []
    if isinstance(Item,list):
        Target.extend(Item)
    else:
        Target.append(Item)
    return Target

#
# Write an item with a break line
#
def WriteLine(Target, Item):
    if isinstance(Target,str):
        Target = [Target]
    if not Target:
        Target = []
    if isinstance(Item, list):
        Target.extend(Item)
    else:
        Target.append(Item)
    Target.append('\n')
    return Target

# This acts like the main() function for the script, unless it is 'import'ed into another
# script.
if __name__ == '__main__':
    EdkLogger.info('start')

    UniFileList = [
                   r'C:\\Edk\\Strings2.uni',
                   r'C:\\Edk\\Strings.uni'
    ]

    SrcFileList = []
    for Root, Dirs, Files in os.walk('C:\\Edk'):
        for File in Files:
            SrcFileList.append(File)

    IncludeList = [
                   r'C:\\Edk'
    ]

    SkipList = ['.inf', '.uni']
    BaseName = 'DriverSample'
    (h, c) = GetStringFiles(UniFileList, SrcFileList, IncludeList, SkipList, BaseName, True)
    hfile = open('unistring.h', 'w')
    cfile = open('unistring.c', 'w')
    hfile.write(h)
    cfile.write(c)

    EdkLogger.info('end')


text:
import Vue from "vue";
import App from "./App.vue";
import "./registerServiceWorker";

Vue.config.productionTip = false;

new Vue({
  render: h => h(App)
}).$mount("#app");


text:
@interface FontLabel : UILabel

@end


text:
//
//  NSString+Andy.h
//  AndyCategory_Test
//
//  Created by 李扬 on 16/8/4.
//  Copyright © 2016年 andyli. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface NSString (Andy)

- (nullable NSDictionary *)andy_decomposeUrlQueryStr;

// 对比两个字符串内容是否一致
- (BOOL)andy_equals:(NSString * __nullable)string;

// 判断字符串是否以指定的前缀开头
- (BOOL)andy_startsWith:(NSString * __nullable)prefix;

// 判断字符串是否以指定的后缀结束
- (BOOL)andy_endsWith:(NSString * __nullable)suffix;

// 转换成小写
- (nullable NSString *)andy_toLowerCase;

// 转换成大写
- (nonnull NSString *)andy_toUpperCase;

// 截取字符串前后空格
- (nonnull NSString *)andy_trim;

// 用指定分隔符将字符串分割成数组
- (nonnull NSArray *)andy_split:(NSString * __nullable)separator;

// 用指定字符串替换原字符串
- (nonnull NSString *)andy_replaceAll:(NSString * __nullable)oldStr with:(NSString * __nullable)newStr;

// 从指定的开始位置和结束位置开始截取字符串
- (nullable NSString *)andy_substringFromIndex:(int)begin toIndex:(int)end;

/**
 *  md5加密
 */
- (nullable NSString *)andy_md5HexDigest;

/**
 *  sha1加密
 */
- (nonnull NSString *)andy_sha1HexDigest;

// UTF-8转码
- (nonnull NSString *)andy_UTF8String;

//判断是否为整形
+(BOOL)andy_isValidPureInt:(NSString * __nullable)string;

//判断是否为浮点形
+(BOOL)andy_isValidPureFloat:(NSString * _Nullable)string;

// 正则IP地址
- (BOOL)andy_isValidIPAdddress;

// 正则匹配邮箱号
- (BOOL)andy_isValidMailInput;

// 正则匹配手机号
- (BOOL)andy_isValidTelNumber;

// 正则匹配用户密码6-18位数字和字母组合
- (BOOL)andy_isValidPassword;

// 正则匹配用户姓名,20位的中文或英文
- (BOOL)andy_isValidUserName;

// 正则匹配用户身份证号
- (BOOL)andy_isValidUserIdCard;

// 正则匹员工号,12位的数字
- (BOOL)andy_isValidEmployeeNumber;

// 正则匹配URL
- (BOOL)andy_isValidURL;

// 正则匹配昵称
- (BOOL)andy_isValidNickname;

// 正则只能输入数字和字母
- (BOOL)andy_isValidOnlyCharAndNumber;

// 车牌号验证
- (BOOL)andy_isValidCarNumber;

// 格式化手机号
- (nonnull NSString *)andy_standardPhone;

// 格式化手机号
- (nonnull NSString *)andy_standardTele;

// 手机号*处理
- (nonnull NSString *)andy_securitPhone;

/**
 *  返回字符串所占用的尺寸
 *
 *  @param font    字体
 *  @param maxSize 最大尺寸
 */
- (CGSize)andy_sizeWithFont:(UIFont * __nonnull)font maxSize:(CGSize)maxSize;

// AES加密
- (nullable NSString *)andy_aes256_encrypt:(NSString * __nullable)key;

// AES解密
- (nullable NSString *)andy_aes256_decrypt:(NSString * __nullable)key;

//- (NSString *)andy_mimeType;
- (nonnull NSString *)andy_mimeType2;

/*
 返回汉字拼音,无声调
 */
- (nonnull NSString *)andy_pinyin;

/*
 返回汉字拼音,包含声调
 */
- (nonnull NSString *)andy_pinyinAndTone;

- (nullable NSString *)andy_base64EncodedString;

+ (nullable NSString *)andy_stringWithBase64EncodedString:( NSString * __nullable )base64EncodedString;

- (nullable NSString *)andy_stringByURLEncode;

- (nullable NSString *)andy_stringByURLDecode;

- (nullable NSString *)andy_stringByEscapingHTML;

//判空字符串
+ (BOOL)andy_isEmptyString:(NSString * __nullable)string;

+ (BOOL)andy_stringContainsEmoji:(NSString * __nullable)string;

+ (nullable NSString *)andy_uuidString;

+ (nullable NSString *)andy_stringOfFileSize:(unsigned long long)size;

//字符转emoji
- (nullable NSString *)andy_stringByReplacingEmojiCheatCodesWithUnicode;

//emoji转字符
- (nullable NSString *)andy_stringByReplacingEmojiUnicodeWithCheatCodes;

- (CGSize)andy_sizeWithFont:(UIFont * __nonnull)font;

- (CGSize)andy_sizeWithFont:(UIFont * __nonnull)font constrainedToWidth:(CGFloat)width;

- (CGSize)andy_sizeWithFont:(UIFont * __nonnull)font constrainedToWidth:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode;

- (CGSize)andy_sizeWithFont:(UIFont * __nonnull)font constrainedToSize:(CGSize)size;

- (CGSize)andy_sizeWithFont:(UIFont * __nonnull)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode;

/** 生成length长度的随机字符串(不包含数字) */
+ (nonnull instancetype)andy_randomStringWithoutDigitalWithLength:(int)length;

/** 去除空格 */
- (nullable instancetype)andy_stringByRemovingSpace;

/** 将字符串用空格分割成数组 */
- (nullable NSArray *)andy_componentsSeparatedBySpace;

/** 从mainBundle中加载文件数据 */
+ (nullable instancetype)andy_stringWithFilename:(NSString * __nullable)filename
                            extension:(NSString * __nullable)extension;

/** 生成crc32 */
- (nullable NSString *)andy_crc32;

@end

// oc 语言 是一个很严密的语言,不那么宽松,所以逻辑如果处理不好的时候,在各种数据类型转换、变化时候会导致各种闪退,比如说字典的value不能为nil,数组越界,字符串截取失败等等

@interface NSString (ParametersSafe)

// 安全初始化方法
- (nullable instancetype)andy_safe_initWithString:(NSString * __nullable)aString;

// 安全截取方法
- (nullable NSString *)andy_safe_substringToIndex:(NSInteger)to;

// 安全截取方法
- (nullable NSString *)andy_safe_substringFromIndex:(NSInteger)from;

@end

@interface NSAttributedString (Andy)

// 富文本设置行高
- (nonnull NSAttributedString *)andy_adjustlineSpace:(float)space;

@end


text:
import * as clc from "colorette";
import * as functionsConfig from "../functionsConfig";

import { Command } from "../command";
import { FirebaseError } from "../error";
import { Options } from "../options";
import { needProjectId } from "../projectUtils";
import { promptOnce } from "../prompt";
import { reduceFlat } from "../functional";
import { requirePermissions } from "../requirePermissions";
import * as args from "../deploy/functions/args";
import * as helper from "../deploy/functions/functionsDeployHelper";
import * as utils from "../utils";
import * as backend from "../deploy/functions/backend";
import * as planner from "../deploy/functions/release/planner";
import * as fabricator from "../deploy/functions/release/fabricator";
import * as executor from "../deploy/functions/release/executor";
import * as reporter from "../deploy/functions/release/reporter";
import * as containerCleaner from "../deploy/functions/containerCleaner";
import { getProjectNumber } from "../getProjectNumber";

export const command = new Command("functions:delete [filters...]")
  .description("delete one or more Cloud Functions by name or group name.")
  .option(
    "--region <region>",
    "Specify region of the function to be deleted. " +
      "If omitted, functions from all regions whose names match the filters will be deleted. "
  )
  .withForce()
  .before(requirePermissions, ["cloudfunctions.functions.list", "cloudfunctions.functions.delete"])
  .action(async (filters: string[], options: { force: boolean; region?: string } & Options) => {
    if (!filters.length) {
      return utils.reject("Must supply at least function or group name.");
    }

    const context: args.Context = {
      projectId: needProjectId(options),
      filters: filters.map((f) => ({ idChunks: f.split(".") })),
    };

    const [config, existingBackend] = await Promise.all([
      functionsConfig.getFirebaseConfig(options),
      backend.existingBackend(context),
    ]);
    await backend.checkAvailability(context, /* want=*/ backend.empty());
    const appEngineLocation = functionsConfig.getAppEngineLocation(config);

    if (options.region) {
      existingBackend.endpoints = { [options.region]: existingBackend.endpoints[options.region] };
    }
    const plan = planner.createDeploymentPlan({
      wantBackend: backend.empty(),
      haveBackend: existingBackend,
      codebase: "",
      filters: context.filters,
      deleteAll: true,
    });
    const allEpToDelete = Object.values(plan)
      .map((changes) => changes.endpointsToDelete)
      .reduce(reduceFlat, [])
      .sort(backend.compareFunctions);
    if (allEpToDelete.length === 0) {
      throw new FirebaseError(
        `The specified filters do not match any existing functions in project ${clc.bold(
          context.projectId
        )}.`
      );
    }

    const deleteList = allEpToDelete.map((func) => `\t${helper.getFunctionLabel(func)}`).join("\n");
    const confirmDeletion = await promptOnce(
      {
        type: "confirm",
        name: "force",
        default: false,
        message:
          "You are about to delete the following Cloud Functions:\n" +
          deleteList +
          "\n  Are you sure?",
      },
      options
    );
    if (!confirmDeletion) {
      throw new FirebaseError("Command aborted.");
    }

    const functionExecutor: executor.QueueExecutor = new executor.QueueExecutor({
      retries: 30,
      backoff: 20000,
      concurrency: 40,
      maxBackoff: 40000,
    });

    try {
      const fab = new fabricator.Fabricator({
        functionExecutor,
        appEngineLocation,
        executor: new executor.QueueExecutor({}),
        sources: {},
        projectNumber:
          options.projectNumber || (await getProjectNumber({ projectId: context.projectId })),
      });
      const summary = await fab.applyPlan(plan);
      await reporter.logAndTrackDeployStats(summary);
      reporter.printErrors(summary);
    } catch (err: any) {
      throw new FirebaseError("Failed to delete functions", {
        original: err as Error,
        exit: 1,
      });
    }

    // Clean up image caches too
    await containerCleaner.cleanupBuildImages([], allEpToDelete);
  });


text:
<?xml version="1.0" encoding="UTF-8"?>
<executionPlan name="FlightStatsExecutionPlan" statistics="disable"
  trace="disable" xmlns="http://wso2.org/carbon/eventprocessor">
  <description>This execution plan is used to identify the delayed flight details</description>
  <siddhiConfiguration>
    <property name="siddhi.enable.distributed.processing">false</property>
    <property name="siddhi.persistence.snapshot.time.interval.minutes">0</property>
  </siddhiConfiguration>
  <importedStreams>
    <stream as="flightStatsStream" name="FlightArrivalStatsStream" version="1.0.0"/>
  </importedStreams>
  <queryExpressions><![CDATA[from flightStatsStream[status != 'On-Time']
select flightName, flightId, flightType, arrivalTime, trackNo
insert into delayedFlightStream]]></queryExpressions>
  <exportedStreams>
    <stream name="delayedFlightStream" valueOf="delayedFlightStream" version="1.0.0"/>
  </exportedStreams>
</executionPlan>


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2021 Google LLC
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/touchFeedback" />

    <item android:drawable="@drawable/completedTaskBackground" />
</selector>


text:
<?php

defined('_JEXEC') or die;

/**
 * @package		Joomla.Administrator
 * @subpackage	com_messages
 * @since		1.6
 */
class MessagesHelper
{
	/**
	 * Configure the Linkbar.
	 *
	 * @param	string	The name of the active view.
	 *
	 * @return	void
	 * @since	1.6
	 */

	public static function addSubmenu($vName)
	{
		JSubMenuHelper::addEntry(
			JText::_('COM_MESSAGES_ADD'),
			'index.php?option=com_messages&view=message&layout=edit',
			$vName == 'message'
		);

		JSubMenuHelper::addEntry(
			JText::_('COM_MESSAGES_READ'),
			'index.php?option=com_messages',
			$vName == 'messages'
		);
	}

	/**
	 * Gets a list of the actions that can be performed.
	 *
	 * @return	JObject
	 */
	public static function getActions()
	{
		$user	= JFactory::getUser();
		$result	= new JObject;

		$actions = JAccess::getActions('com_messages');

		foreach ($actions as $action) {
			$result->set($action->name,	$user->authorise($action->name, 'com_messages'));
		}

		return $result;
	}

	/**
	 * Get a list of filter options for the state of a module.
	 *
	 * @return	array	An array of JHtmlOption elements.
	 */
	static function getStateOptions()
	{
		// Build the filter options.
		$options	= array();
		$options[]	= JHtml::_('select.option',	'1',	JText::_('COM_MESSAGES_OPTION_READ'));
		$options[]	= JHtml::_('select.option',	'0',	JText::_('COM_MESSAGES_OPTION_UNREAD'));
		$options[]	= JHtml::_('select.option',	'-2',	JText::_('JTRASHED'));
		return $options;
	}
}


text:
package function.cohort.collapsing;

import function.annotation.base.AnnotationLevelFilterCommand;
import function.annotation.base.GeneManager;
import function.annotation.base.TranscriptManager;
import function.cohort.base.Sample;
import function.cohort.base.SampleManager;
import function.cohort.vargeno.ListVarGenoLite;
import function.cohort.vargeno.VariantGenoLite;
import function.external.knownvar.KnownVarCommand;
import function.external.knownvar.KnownVarManager;
import global.Data;
import global.Index;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import org.apache.commons.csv.CSVRecord;
import utils.CommonCommand;
import utils.ErrorManager;
import utils.LogManager;
import utils.ThirdPartyToolManager;

/**
 *
 * @author nick
 */
public class CollapsingLite extends ListVarGenoLite {

    private static BufferedWriter bwSampleMatrix = null;
    private static BufferedWriter bwSummary = null;

    private static final String matrixFilePath = CommonCommand.outputPath + "matrix.txt";
    private static final String summaryFilePath = CommonCommand.outputPath + "summary.csv";
    private static final String geneFetPQQPlotPath = CommonCommand.outputPath + "summary.fet.p.qq.plot.pdf";

    private static ArrayList<CollapsingSummary> summaryList = new ArrayList<>();
    private static HashMap<String, CollapsingSummary> summaryMap = new HashMap<>();

    private void init() {
        initOutput();

        initSummaryMap();

        if (KnownVarCommand.isIncludeOMIM) {
            KnownVarManager.initOMIMMap();
        }
    }

    @Override
    public void initOutput() {
        try {
            super.initOutput();

            bwSampleMatrix = new BufferedWriter(new FileWriter(matrixFilePath));
            bwSummary = new BufferedWriter(new FileWriter(summaryFilePath));

            if (!AnnotationLevelFilterCommand.transcriptBoundaryFile.isEmpty()) {
                bwSampleMatrix.write("sample/transcript" + "\t");
                bwSummary.write(CollapsingTranscriptSummary.getHeader());
            } else { // default is gene collapsing
                bwSampleMatrix.write("sample/gene" + "\t");
                bwSummary.write(CollapsingGeneSummary.getHeader());
            }

            bwSummary.newLine();

            for (Sample sample : SampleManager.getList()) {
                bwSampleMatrix.write(sample.getName() + "\t");
            }
            bwSampleMatrix.newLine();
        } catch (Exception ex) {
            ErrorManager.send(ex);
        }
    }

    @Override
    public void closeOutput() {
        try {
            super.closeOutput();

            bwSummary.flush();
            bwSummary.close();
        } catch (IOException ex) {
            ErrorManager.send(ex);
        }
    }

    @Override
    public void run() {
        try {
            LogManager.writeAndPrint("Start running collapsing lite function");

            init();

            boolean isHeaderOutput = false;
            String previousVariantID = Data.STRING_NA;
            Iterable<CSVRecord> records = getRecords();
            for (CSVRecord record : records) {
                if (!isHeaderOutput) {
                    outputHeader(record);
                    isHeaderOutput = true;
                }

                // each variantLite object represent one row data record in genotype file
                VariantGenoLite variantLite = new VariantGenoLite(record);

                if (variantLite.isValid()) {
                    if (!AnnotationLevelFilterCommand.transcriptBoundaryFile.isEmpty()) {
                        updateTranscriptSummary(variantLite, previousVariantID);
                    } else {
                        updateGeneSummary(variantLite, previousVariantID);
                    }

                    // output qualifed record to genotypes file
                    outputGenotype(variantLite);
                }

                previousVariantID = variantLite.getVariantIdStr();
            }

            outputSummary();
            closeOutput();

            if (CollapsingCommand.isMannWhitneyTest) {
                ThirdPartyToolManager.runMannWhitneyTest(genotypeLiteFilePath);
            }
            generatePvaluesQQPlot();
            gzipFiles();
        } catch (Exception e) {
            ErrorManager.send(e);
        }
    }

    private void updateGeneSummary(VariantGenoLite variantLite, String previousVariantID) {
        for (String geneName : variantLite.getGeneList()) {
            summaryMap.putIfAbsent(geneName, new CollapsingGeneSummary(geneName));

            countQV(geneName, variantLite, previousVariantID);
        }
    }

    private void updateTranscriptSummary(VariantGenoLite variantLite, String previousVariantID) {
        for (int id : variantLite.getTranscriptSet()) {
            String idStr = String.valueOf(id);
            summaryMap.putIfAbsent(idStr, new CollapsingTranscriptSummary(idStr));

            countQV(idStr, variantLite, previousVariantID);
        }
    }

    private void countQV(String collapsingKey, VariantGenoLite variantLite, String previousVariantID) {
        String sampleName = variantLite.getRecord().get(SAMPLE_NAME_HEADER);
        Sample sample = SampleManager.getSampleByName(sampleName);

        String gtStr = variantLite.getRecord().get(GT_HEADER);
        byte geno = getGeno(gtStr);

        CollapsingSummary summary = summaryMap.get(collapsingKey);
        summary.countQualifiedVariantBySample(geno, sample.getIndex());

        // only count variant once per gene
        if (!previousVariantID.equals(variantLite.getVariantIdStr())) {
            summary.updateVariantCount(variantLite.isSNV());
        }
    }

    private void initSummaryMap() {
        if (!AnnotationLevelFilterCommand.transcriptBoundaryFile.isEmpty()) {
            initTranscriptSummaryMap();
        } else {
            initGeneSummaryMap();
        }
    }

    private void initGeneSummaryMap() {
        GeneManager.getMap().values().stream().forEach((geneSet) -> {
            geneSet.stream().forEach((gene) -> {
                summaryMap.putIfAbsent(gene.getName(), new CollapsingGeneSummary(gene.getName()));
            });
        });
    }

    private void initTranscriptSummaryMap() {
        TranscriptManager.getTranscriptBoundaryMap().values().stream().forEach((transcriptBoundary) -> {
            String idStr = String.valueOf(transcriptBoundary.getId());
            summaryMap.putIfAbsent(idStr, new CollapsingTranscriptSummary(idStr));
        });
    }

    private byte getGeno(String geno) {
        switch (geno) {
            case "hom":
                return Index.HOM;
            case "het":
                return Index.HET;
            case "hom ref":
                return Index.REF;
            default:
                return Data.BYTE_NA;
        }
    }

    private void outputSummary() {
        LogManager.writeAndPrint("Output the data to matrix & summary file");

        try {
            summaryList.addAll(summaryMap.values());

            outputMatrix();

            Collections.sort(summaryList);

            int rank = 1;
            for (CollapsingSummary summary : summaryList) {
                bwSummary.write(rank++ + ",");
                bwSummary.write(summary.toString());
                bwSummary.newLine();
            }
        } catch (Exception e) {
            ErrorManager.send(e);
        }
    }

    private void outputMatrix() throws Exception {
        for (CollapsingSummary summary : summaryList) {
            bwSampleMatrix.write(summary.name + "\t");

            for (Sample sample : SampleManager.getList()) {
                bwSampleMatrix.write(summary.hasQualifiedVariantBySample[sample.getIndex()] + "\t");
            }

            bwSampleMatrix.newLine();

            summary.countSample();

            try {
                summary.calculateFetP();
            } catch (Exception e) {
                System.out.println();
            }
        }

        bwSampleMatrix.flush();
        bwSampleMatrix.close();
    }

    private void generatePvaluesQQPlot() {
        if (AnnotationLevelFilterCommand.transcriptBoundaryFile.isEmpty()) {
            ThirdPartyToolManager.generateQQPlot4CollapsingFetP(summaryFilePath, matrixFilePath, geneFetPQQPlotPath);
        }
    }

    private void gzipFiles() {
        ThirdPartyToolManager.gzipFile(matrixFilePath);

        if (CommonCommand.gzip) {
            ThirdPartyToolManager.gzipFile(genotypeLiteFilePath);
        }
    }
}


text:
using Dopple.BackTracers;
using Dopple.InstructionNodes;
using Dopple.Tracers.PredciateProviders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dopple.Tracers.DynamicTracing
{
    public class DynamicDataTracer
    {
        private int CountVisitedNodes;
        private List<InstructionNode> GlobalVisited = new List<InstructionNode>();

        internal void BackTraceOutsideFunctionBounds(List<InstructionNode> instructionNodes)
        {
            CountVisitedNodes = 0;
            var mergingNodesData = new Dictionary<InstructionNode, MergeNodeTraceData>();
            foreach (var mergingNode in instructionNodes.Where(x => x.ProgramFlowBackRoutes.Count > 1))
            {
                mergingNodesData.Add(mergingNode, new MergeNodeTraceData());
            }
            TraceOutsideFunctionBoundsRec(instructionNodes[0], mergingNodesData);
            var nonPassedThrough = instructionNodes.Except(GlobalVisited).ToArray().OrderBy(x => x.InstructionIndex).ToArray();
            if (nonPassedThrough.Any())
            {
                var wasntReached = instructionNodes.Except(GlobalVisited).ToArray().OrderBy(x => x.InstructionIndex).First();
                Console.WriteLine("Node wasn't reached is " + wasntReached.InstructionIndex + " " + wasntReached.Instruction);
                //throw new Exception("some nodes not reached");
            }
            Console.WriteLine("Visited node count is " + GlobalVisited.Count);
            CountVisitedNodes = 0;
            ForwardDynamicData(instructionNodes);
        }

        private void ForwardDynamicData(List<InstructionNode> instructionNodes)
        {
            foreach(var node in instructionNodes.Where(x => x is IDynamicDataLoadNode))
            {
                var loadedDynamicData = node.DataFlowBackRelated.Where(x => x.ArgIndex == ((IDynamicDataLoadNode) node).DataFlowDataProdivderIndex).Select(x => x.Argument).ToList();
                foreach (var forwardNode in node.DataFlowForwardRelated)
                {
                    forwardNode.Argument.DataFlowBackRelated.AddTwoWay(loadedDynamicData, forwardNode.ArgIndex);
                }
                node.DataFlowBackRelated.RemoveAll(x => loadedDynamicData.Contains(x.Argument));
            }
        }

        private void TraceOutsideFunctionBoundsRec(InstructionNode currentNode, Dictionary<InstructionNode, MergeNodeTraceData> mergingNodesData, InstructionNode lastNode = null, StateProviderCollection stateProviders = null, List<InstructionNode> visited = null)
        {
            if (visited == null)
            {
                visited = new List<InstructionNode>();
                lastNode = currentNode;
                stateProviders = new StateProviderCollection();
                GlobalVisited.Clear();
            }
            while (true)
            {
                if (visited.Contains(currentNode))
                {
                    if (!currentNode.BranchProperties.MergingNodeProperties.IsMergingNode)
                    {
                        return;
                    }
                }
                visited.Add(currentNode);
                GlobalVisited.Add(currentNode);
                bool reachedMergeNodeNotLast;
                int stateProviderCount = stateProviders.Count;
                ActOnCurrentNode(currentNode, mergingNodesData, lastNode, stateProviders, out reachedMergeNodeNotLast);
                if (reachedMergeNodeNotLast)
                {
                    return;
                }
                lastNode = currentNode;
                if (currentNode.ProgramFlowForwardRoutes.Count == 1)
                {
                    currentNode = currentNode.ProgramFlowForwardRoutes[0];
                }
                else
                {
                    break;
                }
            }
            if (currentNode.ProgramFlowForwardRoutes.Count == 0)
            {
                return;
            }
            if (!(currentNode is ConditionalJumpNode))
            {
                Console.WriteLine("Splitting without a conditional");
            }
            foreach (var node in currentNode.ProgramFlowForwardRoutes)
            {
                TraceOutsideFunctionBoundsRec(node, mergingNodesData, currentNode, stateProviders, visited);
            }
        }

        private static void ActOnCurrentNode(InstructionNode currentNode, Dictionary<InstructionNode, MergeNodeTraceData> mergingNodesData, InstructionNode lastNode, StateProviderCollection stateProviders, out bool reachedMergeNodeNotLast)
        {
            if (currentNode.BranchProperties.MergingNodeProperties.IsMergingNode)
            {
                lock (mergingNodesData)
                {
                    mergingNodesData[currentNode].ReachedNodes.Add(lastNode);
                    mergingNodesData[currentNode].AccumelatedStateProviders.AddNewProviders(stateProviders);
                    bool allBranchesReached = !currentNode.ProgramFlowBackRoutes.Except(mergingNodesData[currentNode].ReachedNodes).Any();
                    if (allBranchesReached)
                    {
                        mergingNodesData[currentNode].AllBranchesReached = true;
                        mergingNodesData[currentNode].AccumelatedStateProviders.MergeBranches(currentNode);
                        stateProviders.AddNewProviders(mergingNodesData[currentNode].AccumelatedStateProviders);
                    }
                    else
                    {
                        reachedMergeNodeNotLast = true;
                        return;
                    }
                }
            }
            var newStoreState = StoreDynamicDataStateProvider.GetMatchingStateProvider(currentNode);
            if (newStoreState != null)
            {
                stateProviders.AddNewProvider(newStoreState);
            }
            IDynamicDataLoadNode loadNode = currentNode as IDynamicDataLoadNode;
            if (loadNode != null)
            {
                foreach (var storeNode in stateProviders.MatchLoadToStore(currentNode))
                {
                    currentNode.DataFlowBackRelated.AddTwoWay(storeNode, loadNode.DataFlowDataProdivderIndex);
                }
            }
            reachedMergeNodeNotLast = false;
        }

    }
}


text:
using System;
using XCommon.Patterns.Specification.Validation.Implementation;

namespace XCommon.Patterns.Specification.Validation.Extensions
{
    public static class SpecificationRegex
    {
        public static SpecificationList<TEntity> AndRegexValid<TEntity>(this SpecificationList<TEntity> specification, Func<TEntity, string> selector, string expression, string message, params object[] args)
            => specification.AndRegexValid(selector, expression, c => true, false, message, args);

        public static SpecificationList<TEntity> AndRegexValid<TEntity>(this SpecificationList<TEntity> specification, Func<TEntity, string> selector, string expression, bool condition, bool stopIfInvalid, string message, params object[] args)
            => specification.AndRegexValid(selector, expression, c => condition, stopIfInvalid, message, args);

        public static SpecificationList<TEntity> AndRegexValid<TEntity>(this SpecificationList<TEntity> specification, Func<TEntity, string> selector, string expression, Func<TEntity, bool> condition, bool stopIfInvalid, string message, params object[] args)
        {
            specification.Add(new AndIsValidRegex<TEntity>(selector, expression, condition, message, args), stopIfInvalid);
            return specification;
        }
    }
}


text:
package com.example.android.uamp.ui;

import android.Manifest;
import android.app.Activity;
import android.app.UiModeManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android.uamp.R;
import com.example.android.uamp.ui.tv.TvPlaybackActivity;
import com.example.android.uamp.utils.LogHelper;

import java.util.Random;

/**
 * The main activity launched when the app starts (in example was call "Now Playing Activity"
 * This just detects whether on TV or Mobile and launches the appropriate activity
 * In my case I am only testing/running on mobile, so really it just starts FullScreenPlayQueue Activity.
 * https://developer.android.com/training/tv/playback/now-playing.html
 *
 * This activity determines which activity to launch based on the current UI mode.
 */
public class MainLauncherActivity extends Activity {

    private static final String TAG = LogHelper.makeLogTag(MainLauncherActivity.class);

    private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;

    /**
     * The time that the splash screen will be on the screen in milliseconds.
     */
    private static int                 TIMEOUT_IN_MS       = 5000;

    /** The time when this {@link Activity} was created. */
    private long                startTimeMillis     = 0;

    /** A random number generator for the background colors. */
    private static final Random random              = new Random();

    /**
     * The TextView which is used to inform the user whether the permissions are
     * granted.
     */
    private TextView tvMessage = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogHelper.i(TAG, "onCreate");

        setContentView(R.layout.activity_main_launcher);
        tvMessage = (TextView) findViewById(R.id.tvMessage);
        tvMessage.setText(R.string.waiting_for_permissions);

        /**
         * Save the start time of this Activity, which will be used to determine
         * when the splash screen should timeout.
         */
        startTimeMillis = System.currentTimeMillis();
        LogHelper.i(TAG, "check permissiions");
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
        } else {
            startNextActivity();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay!
                    startNextActivity();
                } else {
                    // permission denied, boo!"
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }

    }

    private void startNextActivity() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                tvMessage.setText(R.string.permissions_granted);
            }
        });
        startActivity(new Intent(MainLauncherActivity.this, getNextActivityClass()));
        finish();
        /* Don't do the delay
        long delayMillis = TIMEOUT_IN_MS - (System.currentTimeMillis() - startTimeMillis);
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(MainLauncherActivity.this, getNextActivityClass()));
                finish();
            }
        }, delayMillis);
        */
    }

    private Class getNextActivityClass() {
        UiModeManager uiModeManager = (UiModeManager) getSystemService(UI_MODE_SERVICE);
        if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION) {
            LogHelper.i(TAG, "Running on a TV Device");
            return TvPlaybackActivity.class;
        } else {
            LogHelper.i(TAG, "Running on a non-TV Device");
            return FullScreenRecyclerPlayQueueActivity.class;
        }
    }

}


text:
import os
import re
import shutil
import sys

from setuptools import setup

def get_version(package):
    """
    Return package version as listed in `__version__` in `init.py`.
    """
    with open(os.path.join(package, '__init__.py'), 'rb') as init_py:
        src = init_py.read().decode('utf-8')
        return re.search("__version__ = ['\"]([^'\"]+)['\"]", src).group(1)

name = 'skurt-djangorestframework-jwt'
version = get_version('skurt_rest_framework_jwt')
package = 'skurt_rest_framework_jwt'
description = 'JSON Web Token based authentication for Django REST framework'
url = 'https://github.com/skurtapp/django-rest-framework-jwt'
author = 'Jose Padilla'
author_email = 'jpadilla@getblimp.com'
license = 'MIT'
install_requires = [
    'PyJWT>=1.4.0,<2.0.0'
]

def read(*paths):
    """
    Build a file path from paths and return the contents.
    """
    with open(os.path.join(*paths), 'r') as f:
        return f.read()

def get_packages(package):
    """
    Return root package and all sub-packages.
    """
    return [dirpath
            for dirpath, dirnames, filenames in os.walk(package)
            if os.path.exists(os.path.join(dirpath, '__init__.py'))]

def get_package_data(package):
    """
    Return all files under the root package, that are not in a
    package themselves.
    """
    walk = [(dirpath.replace(package + os.sep, '', 1), filenames)
            for dirpath, dirnames, filenames in os.walk(package)
            if not os.path.exists(os.path.join(dirpath, '__init__.py'))]

    filepaths = []
    for base, filenames in walk:
        filepaths.extend([os.path.join(base, filename)
                          for filename in filenames])
    return {package: filepaths}

if sys.argv[-1] == 'publish':
    if os.system('pip freeze | grep wheel'):
        print('wheel not installed.\nUse `pip install wheel`.\nExiting.')
        sys.exit()
    if os.system('pip freeze | grep twine'):
        print('twine not installed.\nUse `pip install twine`.\nExiting.')
        sys.exit()
    os.system('python setup.py sdist bdist_wheel')
    os.system('twine upload dist/*')
    shutil.rmtree('dist')
    shutil.rmtree('build')
    shutil.rmtree('skurt_djangorestframework_jwt.egg-info')
    print('You probably want to also tag the version now:')
    print("  git tag -a {0} -m 'version {0}'".format(version))
    print('  git push --tags')
    sys.exit()

setup(
    name=name,
    version=version,
    url=url,
    license=license,
    description=description,
    long_description=read('README.rst'),
    author=author,
    author_email=author_email,
    packages=get_packages(package),
    package_data=get_package_data(package),
    install_requires=install_requires,
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Internet :: WWW/HTTP',
    ]
)


text:
<?php

class Admission extends CI_Model {

	//extend the parent construct
	function __construct()
	{
		parent::__construct();

		$this->db_prefix = DB_PREFIX.$this->session->userdata('client_id');

	}

	public function new_admission($variable)
	{
		$variable = (object)$variable;

		//secure admission number before admission
		if($variable->actionf == 'secure_admission_number')
		{
			$tablename = $this->db_prefix.'.student_information';

			$this->db->query(" INSERT INTO $tablename (f_name) VALUES('demo') ");
			$number = $this->db->insert_id();

			return $number;

		}

		//check if admission number is already in use
		if($variable->actionf == 'check_admission_number')
		{
			$tablename = $this->db_prefix.'.student_information';

			$sql = $this->db->query(" SELECT * FROM  $tablename WHERE adm = $variable->adm ");

			return $sql;

		}

		//add new student records into the database
		if($variable->actionf == 'add_new_student')
		{
			$tablename = $this->db_prefix.'.student_information';

			$data = array(
						'adm' => $variable->adm,
						'f_name' => $variable->f_name,
						'm_name' => $variable->m_name,
						'l_name' => $variable->l_name,
						'dob' => $variable->dob,
						'pob' => $variable->pob,
						'bcn' => $variable->bcn,
						'gender' => $variable->gender,
						'nationality' => $variable->nationality,
						'county' => $variable->county,
						'photo' => $variable->photo,
						'doa' => $variable->doa,
						'coa' => $variable->coa,
						'soa' => $variable->soa,
						'p_address' => $variable->p_address,
						'p_code' => $variable->p_code,
						'town' => $variable->town,
						'pg_f_name' => $variable->pg_f_name,
						'pg_l_name' => $variable->pg_l_name,
						'phone' => $variable->phone,
						'email' => $variable->email
					);

			$this->db->where('id', $variable->id);
			$sql = $this->db->update($tablename, $data);

			return $sql;

		}

	}

	//this model will handle all classes related controls
	public function classes($variable)
	{
		$variable = (object)$variable;

		if($variable->actionf == 'check_classes')
		{
			$tablename = $this->db_prefix.'.options';
			$sql = $this->db->query(" SELECT * FROM $tablename ");

			return $sql;

		}

		if($variable->actionf == 'delete_classes')
		{
			$tablename = $this->db_prefix.'.options';
			$this->db->query(" DELETE FROM $tablename WHERE class = '$variable->class' ");

			return;

		}

		if($variable->actionf == 'add_new_class')
		{
			$tablename = $this->db_prefix.'.options';

			$sql = $this->db->insert($tablename, $variable->options_array);

			return $sql;

		}

		if($variable->actionf == 'get_class_options')
		{
			$tablename = $this->db_prefix.'.options';

			$sql = $this->db->query(" SELECT * FROM $tablename WHERE class = '$variable->class' ");

			return $sql;

		}

		if($variable->actionf == 'add_class_options')
		{

			$tablename = $this->db_prefix.'.options';

			$sql = $this->db->query(" UPDATE $tablename SET $variable->option = '$variable->option_array' WHERE class = '$variable->class' ");

			return $sql;

		}

	}

	public function records($variable)
	{
		$variable = (object)$variable;

		if($variable->actionf == 'get_all_students')
		{
			$tablename = $this->db_prefix.'.student_information';

			$records = $this->db->get($tablename);

			return $records;

		}

		if($variable->actionf == 'get_all_by_class')
		{
			$tablename = $this->db_prefix.'.student_information';

			$records = $this->db->query(" SELECT * FROM $tablename WHERE coa = '$variable->class'");

			return $records;

		}

		if($variable->actionf == 'get_all_by_class_n_stream')
		{
			$tablename = $this->db_prefix.'.student_information';

			$records = $this->db->query(" SELECT * FROM $tablename WHERE coa = '$variable->class' AND soa = '$variable->stream'");

			return $records;
		}

	}

}


text:
import { WeElement } from 'omi';
import '@omiu/transition';
interface Props {
    effect?: string;
    position?: string;
    trigger?: string;
}
export default class Popover extends WeElement<Props> {
    static css: any;
    static defaultProps: {
        effect: string;
        position: string;
        trigger: string;
    };
    static propTypes: {
        content: StringConstructor;
        effect: StringConstructor;
        position: StringConstructor;
        trigger: StringConstructor;
    };
    installed(): void;
    onEnter: (evt: any) => void;
    timeout: any;
    onLeave: () => void;
    onEnterPopover: (evt: any) => void;
    updatePosition(): void;
    onLeavePopover: () => void;
    isShow: boolean;
    render(props: any): JSX.Element;
}
export {};


text:
package dnsserver

import (
	"context"
	"net"
	"syscall"

	"golang.org/x/sys/unix"
)

const supportsReusePort = true

func reuseportControl(network, address string, c syscall.RawConn) (opErr error) {
	err := c.Control(func(fd uintptr) {
		opErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
	})
	if err != nil {
		return err
	}
	return opErr
}

func listen(network, addr string) (net.Listener, error) {
	lc := net.ListenConfig{Control: reuseportControl}
	return lc.Listen(context.Background(), network, addr)
}

func listenPacket(network, addr string) (net.PacketConn, error) {
	lc := net.ListenConfig{Control: reuseportControl}
	return lc.ListenPacket(context.Background(), network, addr)
}


text:
==================
djangocms-revealjs
==================

.. image:: https://badge.fury.io/py/djangocms-revealjs.png
    :target: https://badge.fury.io/py/djangocms-revealjs

.. image:: http://img.shields.io/pypi/dm/djangocms-page-tags.png
        :target: https://pypi.python.org/pypi/djangocms-page-meta

django CMS plugin to create reveal.js presentations

**Still Experimental and largely undocumented**

Quickstart
----------

Install djangocms-revealjs::

    pip install djangocms-revealjs

Then add it to INSTALLED_APPS along with its dependencies::

    'filer',
    'djangocms_revealjs',

Download and install `reveal.js`_ in your django CMS project.

Features
--------

Provides four django CMS plugins to edit Reveal.JS presentations:

Slide (RevealSlidePlugin)
+++++++++++++++++++++++++

This is the plugin to insert normal slides.

It supports settings transitions, background color and images, markdown syntax.

Container (RevealSlidesContainer)
+++++++++++++++++++++++++++++++++

Containers allow to nest slides in a vertical way.

Only slides can be put in a container; only one-level of container is supported.

Slide fragment (RevealFragmentPlugin)
+++++++++++++++++++++++++++++++++++++

Fragments allow to display part of a slide progressively. This plugin handles
inline fragments (i.e.: like `span` elements).

Block slide fragment (RevealBlockFragmentPlugin)
++++++++++++++++++++++++++++++++++++++++++++++++

This plugin is equal to the above, but renders block fragments
(i.e.: like `div` elements).

Dependencies
------------

* `django-filer`_ >= 0.9.5

.. _django-filer: https://pypi.python.org/pypi/django-filer
.. _reveal.js: http://lab.hakim.se/reveal-js/


text:
<?php
/**
 * The base configurations of the WordPress.
 *
 * This file has the following configurations: MySQL settings, Table Prefix,
 * Secret Keys, WordPress Language, and ABSPATH. You can find more information
 * by visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing
 * wp-config.php} Codex page. You can get the MySQL settings from your web host.
 *
 * This file is used by the wp-config.php creation script during the
 * installation. You don't have to use the web site, you can just copy this file
 * to "wp-config.php" and fill in the values.
 *
 * @package WordPress
 */

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'lzinssmeister wordpress');

/** MySQL database username */
define('DB_USER', 'root');

/** MySQL database password */
define('DB_PASSWORD', 'root');

/** MySQL hostname */
define('DB_HOST', 'localhost');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

/**#@+
 * Authentication Unique Keys and Salts.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
 * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define('AUTH_KEY',         '%YIkFGo7rIJDe`OW1;PcL1],5qm~@5$l=umUe_=-uc=tD1kbU4<x@hYFrd4FlGa7');
define('SECURE_AUTH_KEY',  '3+@2yJH*2ED^jPp0]PS,i+8]wS?]a{};AR5+27~D]Ctv!tA>o>qL>^%k*+ApZEu5');
define('LOGGED_IN_KEY',    'TPVK?er4BS/dFA0%M;9?7e}7 R):i.Z8B4T}b9q9mC{Y_o?v]Pyb85Efzdme>*kz');
define('NONCE_KEY',        'a2,W|G]Uiob`qO&zX=}j eO)QBso,)e?( ((ae2uC*8hV*L.>0<_?a4F1)2sMs(U');
define('AUTH_SALT',        '57[._R=FOx99k[L$6j`jG2rZ[+_aQ8x&a3dw[*2@hYqHUA3m+M3Mqf08LQW3;9U!');
define('SECURE_AUTH_SALT', ')mbOt:k$P7iXuTr5v9E5<P^GV[mJTZGY:jI>1IvHBI}RTv)Y4[o2,`}O38UKw@ [');
define('LOGGED_IN_SALT',   'g^:>q|`/~v_O!<N9hf%E?Qa&7G9B0NrXou^e0R}KJX5fLb^D+C3RbfE@CDB/0HVc');
define('NONCE_SALT',       '!;.VLt|bzPG@&~Qx].:#-)M+ZOx;^ttB+BO_oBQosZ1|z0C+qgLW/1v<kF;f_yV#');

/**#@-*/

/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each a unique
 * prefix. Only numbers, letters, and underscores please!
 */
$table_prefix  = 'wp_';

/**
 * WordPress Localized Language, defaults to English.
 *
 * Change this to localize WordPress. A corresponding MO file for the chosen
 * language must be installed to wp-content/languages. For example, install
 * de_DE.mo to wp-content/languages and set WPLANG to 'de_DE' to enable German
 * language support.
 */
define('WPLANG', '');

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 */
define('WP_DEBUG', false);

/* That's all, stop editing! Happy blogging. */

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
	define('ABSPATH', dirname(__FILE__) . '/');

/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');


text:
<?php

namespace Doctrine\Tests\ODM\PHPCR\Functional;

use Doctrine\ODM\PHPCR\Document\File;
use Doctrine\ODM\PHPCR\DocumentManager;
use Doctrine\ODM\PHPCR\Mapping\Annotations as PHPCRODM;
use Doctrine\Tests\ODM\PHPCR\PHPCRFunctionalTestCase;
use PHPCR\NodeInterface;

/**
 * @group functional
 */
class FixPHPCR1Test extends PHPCRFunctionalTestCase
{
    /**
     * @var DocumentManager
     */
    private $dm;

    /**
     * @var NodeInterface
     */
    private $node;

    public function setUp(): void
    {
        $this->dm = $this->createDocumentManager();
        $this->node = $this->resetFunctionalNode($this->dm);
    }

    public function testCreateFromFile(): void
    {
        $parent = new FixPHPCR1TestObj();
        $parent->id = '/functional/filetest';
        $this->dm->persist($parent);

        $parent->file = new File();
        $parent->file->setFileContentFromFilesystem(__DIR__.'/_files/foo.txt');

        $this->dm->flush();
        $this->dm->clear();

        $this->assertTrue($this->node->getNode('filetest')->hasNode('file'));
        $this->assertTrue($this->node->getNode('filetest')->getNode('file')->hasNode('jcr:content'));
        $this->assertTrue($this->node->getNode('filetest')->getNode('file')->getNode('jcr:content')->hasProperty('jcr:data'));
    }
}

/**
 * @PHPCRODM\Document()
 */
class FixPHPCR1TestObj
{
    /** @PHPCRODM\Id */
    public $id;

    /** @PHPCRODM\Node */
    public $node;

    /** @PHPCRODM\Child(cascade="persist") */
    public $file;
}


text:
import { RECEIVE_CHAMP_DATA, RECEIVE_CHAMPS,RESET_LIST, RECEIVE_SELECTED_CHAMP } from '../actions/champions';

export default function champions(state = {
  defaultText: 'Annie',
  selectedChamp: '',
  champList: [],
  isFetching: false,
  champSelected: '',
  champData: [],
  champInfo: [],
  champName: '',
  champId: '',
},action){
  switch(action.type){
    case RECEIVE_CHAMPS:
      console.log('r->RECEIVE_CHAMPS');
      return Object.assign({}, state, {
        champList: _.pluck(action.list, 'name'),
      });
    case RESET_LIST:
      console.log('r->RESET_LIST');
      return Object.assign({}, state, {
        champList: ['reset','via','actionCreator']
      });
    case RECEIVE_CHAMP_DATA:
      console.log('r->RECEIVE_CHAMP_DATA',action);
      return Object.assign({}, state, {
        champName: action.champName,
        champData: action.champData.data,
        champId: _.result(_.find(action.champData.data, 'name', action.champName), 'id'),
      });
    default:
      return state;
  }
}