text:
package de.wellnerbou.polopoly.test;

import com.google.common.collect.Lists;
import com.polopoly.cm.ContentId;
import com.polopoly.cm.ExternalContentId;
import com.polopoly.cm.VersionInfo;
import com.polopoly.cm.VersionedContentId;
import com.polopoly.cm.app.policy.ContentListWrapperPolicy;
import com.polopoly.cm.app.policy.SelectPolicy;
import com.polopoly.cm.app.policy.SelectableSubFieldPolicy;
import com.polopoly.cm.app.policy.SingleValuePolicy;
import com.polopoly.cm.client.CMException;
import com.polopoly.cm.client.Content;
import com.polopoly.cm.client.InputTemplate;
import com.polopoly.cm.client.impl.VersionInfoImpl;
import com.polopoly.cm.collections.ContentList;
import com.polopoly.cm.collections.ContentListSimple;
import com.polopoly.cm.collections.ContentListUtil;
import com.polopoly.cm.policy.ContentPolicy;
import com.polopoly.cm.policy.Policy;
import com.polopoly.cm.policy.PolicyCMServer;
import com.polopoly.siteengine.layout.slot.SlotPolicy;
import com.polopoly.user.server.UserId;
import org.mockito.stubbing.Answer;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

/**
 * @author Paul Wellner Bou <paul@wellnerbou.de>
 */
public class MockPolicyBuilder<T extends Policy> {

	public static final int CHILD_POLICY_MAJOR = 14;
	public static final String POLICY_NAME_OF_NAME_CHILD_POLICY = "nameField";
	public static final String P_TEXT_INPUT = "p.TextInput";
	private static int minorCounter = 1;

	private final InstanceCreator<T> instanceCreator;
	private VersionedContentId parentContentId = new VersionedContentId(2, 999, 999);
	private Content content = ContentFactory.createContentMock();

	private PolicyCMServer policyCmServer = mock(PolicyCMServer.class);
	private int major = 1;

	private String inputTemplateExternalId = "de.wellnerbou.defaultInputTemplateName";
	private int minor = MockPolicyBuilder.minorCounter++;
	private String policyName = "TestPolicy#" + minor;
	private Map<String, Policy> childPolicies = new LinkedHashMap<>();
	private Map<String, ContentList> contentLists = new LinkedHashMap<>();
	private Map<ComponentIdentifier, String> components = new HashMap<>();
	private String externalContentIdString;
	private InputTemplate inputTemplateInstance;
	private boolean committed = false;

	private class ComponentIdentifier {
		String componentGroupName;
		String componentName;

		public ComponentIdentifier(final String componentGroupName, final String componentName) {
			this.componentGroupName = componentGroupName;
			this.componentName = componentName;
		}
	}

	public MockPolicyBuilder(final Class<T> policyClass, final PolicyCMServer mockedPolicyCmServer) {
		this(new InstanceFromClassCreator<T>(policyClass), mockedPolicyCmServer);
	}

	public MockPolicyBuilder(final InstanceCreator<T> instanceCreator, final PolicyCMServer policyCMServer) {
		this.instanceCreator = instanceCreator;
		this.policyCmServer = policyCMServer;
	}

	public MockPolicyBuilder<T> withParent(VersionedContentId parentContentId) {
		this.parentContentId = parentContentId;
		return this;
	}

	public MockPolicyBuilder<T> withContent(final Content mockedContent) {
		this.content = mockedContent;
		return this;
	}

	public MockPolicyBuilder<T> withContentList(final String modelPath, final ContentId... contentListContents) {
		final List<ContentId> contentIds = Arrays.asList(contentListContents);
		final ContentListSimple contentListSimple = new ContentListSimple(contentIds, modelPath);
		contentLists.put(modelPath, ContentListUtil.unmodifiableContentList(contentListSimple));
		return this;
	}

	public MockPolicyBuilder<T> withMajor(int major) {
		this.major = major;
		return this;
	}

	public MockPolicyBuilder<T> withExternalContentIdString(String externalContentIdString) {
		this.externalContentIdString = externalContentIdString;
		return this;
	}

	/**
	 * This is the internal name used to initialize the policy, not the name retrieved by {@link ContentPolicy#getName()} of {@link ContentPolicy}.
	 *
	 * @param name
	 * @return MockPolicyBuilder
	 */
	public MockPolicyBuilder<T> withInternalPolicyName(String name) {
		this.policyName = name;
		return this;
	}

	public MockPolicyBuilder<T> withChildPolicy(final String childPolicyName, final Policy childPolicy) {
		childPolicies.put(childPolicyName, childPolicy);
		return this;
	}

	public MockPolicyBuilder<T> withInputTemplateExternalId(final String inputTemplateExternalId) {
		this.inputTemplateExternalId = inputTemplateExternalId;
		return this;
	}

	public MockPolicyBuilder<T> withInputTemplate(final InputTemplate inputTemplate) {
		this.inputTemplateInstance = inputTemplate;
		return this;
	}

	public MockPolicyBuilder<T> withSlot(final String slotName, final ContentId... contentListContents) {
		return withSlot(slotName, new InstanceFromClassCreator<>(SlotPolicy.class), contentListContents);
	}

	public MockPolicyBuilder<T> withSlot(final String slotName, final Policy... contentListContents) {
		return withSlot(slotName, new InstanceFromClassCreator<>(SlotPolicy.class), contentListContents);
	}

	public MockPolicyBuilder<T> withSlot(final String slotName, final InstanceCreator<? extends SlotPolicy> policyInstanceCreator, final ContentId... contentListContents) {
		final ContentListWrapperPolicy slotElementsPolicy = new MockPolicyBuilder<>(ContentListWrapperPolicy.class, policyCmServer)
				.withContentList("default", contentListContents)
				.build();
		final SlotPolicy slotPolicy = new MockPolicyBuilder<>(policyInstanceCreator, policyCmServer)
				.withChildPolicy("slotElements", slotElementsPolicy)
				.build();
		this.withChildPolicy(slotName, slotPolicy);
		return this;
	}

	public MockPolicyBuilder<T> withSlot(final String slotName, final InstanceCreator<? extends SlotPolicy> policyInstanceCreator, final Policy... contentListContents) {
		return withSlot(slotName, policyInstanceCreator, Arrays.asList(contentListContents).stream().map(input -> input.getContentId()).toArray(ContentId[]::new));
	}

	public MockPolicyBuilder<T> withSingleValuedChildPolicyValue(final String childPolicyName, final String childPolicyValue, final InstanceCreator<? extends SingleValuePolicy> childPolicyInstanceCreator) {
		return this.withSingleValuedChildPolicyValue(childPolicyName, childPolicyValue, P_TEXT_INPUT, childPolicyInstanceCreator);
	}

	public MockPolicyBuilder<T> withSingleValuedChildPolicyValue(final String childPolicyName, final String childPolicyValue, final String childPolicyInputTemplateExternalId, final InstanceCreator<? extends SingleValuePolicy> childPolicyInstanceCreator) {
		final Content childPolicyContent = ContentFactory.createContentMock();
		final InputTemplate inputTemplate = InputTemplateFactory.createInputTemplateMock(childPolicyName, childPolicyInputTemplateExternalId);
		final Policy childPolicy = new MockPolicyBuilder<>(childPolicyInstanceCreator, policyCmServer)
				.withMajor(CHILD_POLICY_MAJOR).withContent(childPolicyContent)
				.withInputTemplate(inputTemplate).withInternalPolicyName(childPolicyName).build();
		try {
			when(childPolicyContent.getComponent(childPolicyName, getChildPolicyValueModelPath(childPolicy))).thenReturn(childPolicyValue);
		} catch (CMException e) {
			throw new RuntimeException(e);
		}
		return withChildPolicy(childPolicyName, childPolicy);
	}

	public MockPolicyBuilder<T> withNameChildPolicy(final String name) {
		return this.withComponent("polopoly.Content", "name", name)
				.withSingleValuedChildPolicyValue(POLICY_NAME_OF_NAME_CHILD_POLICY, name, "p.ContentName",
						new InstanceFromClassCreator<>(SingleValuePolicy.class));
	}

	public MockPolicyBuilder<T> withComponent(final String componentGroupName, final String componentName, final String componentValue) {
		components.put(new ComponentIdentifier(componentGroupName, componentName), componentValue);
		return this;
	}

	private String getChildPolicyValueModelPath(Policy childPolicy) {
		if (childPolicy instanceof SelectPolicy) {
			return "selected_0";
		} else if (childPolicy instanceof SelectableSubFieldPolicy) {
			return "subField";
		}
		return "value";
	}

	public MockPolicyBuilder<T> withSingleValuedChildPolicyValue(final String childPolicyName, final String childPolicyValue) {
		return withChildPolicyValue(childPolicyName, childPolicyValue, SingleValuePolicy.class);
	}

	public MockPolicyBuilder<T> withChildPolicyValue(final String childPolicyName, final String childPolicyValue, final Class<? extends Policy> childPolicyClass) {
		return withSingleValuedChildPolicyValue(childPolicyName, childPolicyValue, new InstanceFromClassCreator(childPolicyClass));
	}

	public MockPolicyBuilder<T> withCommittedVersion() {
		this.committed = true;
		return this;
	}

	public T build() {
		final VersionedContentId versionedContentId = new VersionedContentId(major, minor, getTimestamp());
		return build(versionedContentId);
	}

	public T build(int major, int minor) {
		final VersionedContentId versionedContentId = new VersionedContentId(major, minor, getTimestamp());
		return build(versionedContentId);
	}

	private int getTimestamp() {
		return new BigDecimal(System.currentTimeMillis() / 1000).intValueExact();
	}

	public T build(VersionedContentId versionedContentId) {
		try {
			T policy = internalBuildWithoutMockigCmServer(versionedContentId);
			persistInMockedCmServer(policy, content);
			return policy;
		} catch (CMException e) {
			throw new RuntimeException(e);
		}
	}

	public T buildNewVersionFor(T currentVersionOfPolicy) {
		final VersionedContentId currentVersionedContentId = currentVersionOfPolicy.getContentId();
		int version = getTimestamp();
		if(currentVersionedContentId.getVersion() >= version) {
			version++;
		}
		final VersionedContentId newVersionedContentId = new VersionedContentId(currentVersionedContentId.getMajor(), currentVersionedContentId.getMinor(), version);
		return build(newVersionedContentId);
	}

	private T internalBuildWithoutMockigCmServer(final VersionedContentId versionedContentId) throws CMException {
		when(content.getContentId()).thenReturn(versionedContentId);
		when(content.getSecurityParentId()).thenReturn(parentContentId);
		InputTemplate inputTemplate = getInputTemplate();

		T policy = spy(instanceCreator.instantiate());
		when(content.getName()).thenReturn(this.policyName);
		if (externalContentIdString != null) {
			final ExternalContentId externalContentId = new ExternalContentId(versionedContentId.getMajor(), versionedContentId.getMinor(), versionedContentId.getVersion(), externalContentIdString);
			when(content.getExternalId()).thenReturn(externalContentId);
		}
		for (Map.Entry<String, ContentList> entry : contentLists.entrySet()) {
			if (entry.getKey().equals("default")) {
				when(content.getContentList()).thenReturn(entry.getValue());
			}
			when(content.getContentList(entry.getKey())).thenReturn(entry.getValue());
			for (int i = 0; i < entry.getValue().size(); i++) {
				when(content.getContentReference(entry.getKey(), String.valueOf(i))).thenReturn(entry.getValue().getEntry(i).getReferredContentId());
			}
		}
		when(content.getAvailableContentListNames()).thenReturn(contentLists.keySet().toArray(new String[0]));
		mockComponentNames(components, content);

		when(content.getName()).thenAnswer((Answer<String>) invocation -> ((Content) invocation.getMock()).getComponent("polopoly.Content", "name"));

		initPolicy(policy, content, policyCmServer, inputTemplate);
		for (Map.Entry<String, Policy> entry : childPolicies.entrySet()) {
			final Policy childPolicy = entry.getValue();
			doReturn(childPolicy).when(policy).getChildPolicy(entry.getKey());
		}
		doReturn(Lists.newArrayList(childPolicies.keySet())).when(policy).getChildPolicyNames();

		final VersionInfo versionInfo = createVersionInfo(versionedContentId, committed ? System.currentTimeMillis() : -1L);
		when(content.getVersionInfo()).thenReturn(versionInfo);

		persistInMockedCmServer(policy, content);
		mockRemove(content);
		return policy;
	}

	private void mockRemove(final Content content) throws CMException {
		when(content.remove()).thenAnswer(invocationOnMock -> {
			removeContentVersionFromCmServer(content.getContentId());

			final ContentId unversionedContentId = content.getContentId().getContentId();
			if(policyCmServer.contentExists(unversionedContentId)) {
				final VersionInfo versionInfo = policyCmServer.getContent(unversionedContentId).getVersionInfo();
				if(versionInfo.getVersion() == content.getContentId().getVersion()) {
					if(versionInfo.getPreviousVersion() > 0) {
						final Policy policy = policyCmServer.getPolicy(unversionedContentId);
						persistInMockedCmServer(policy, policy.getContent());
					} else {
						removeContentVersionFromCmServer(unversionedContentId);
					}
				}
			}

			return new VersionedContentId[]{content.getContentId()};
		});
	}

	private void removeContentVersionFromCmServer(final ContentId contentId) throws CMException {
		when(policyCmServer.getPolicy(contentId)).thenThrow(new CMException("Policy " + contentId + " does not exist any more."));
		when(policyCmServer.getContent(contentId)).thenThrow(new CMException("Content " + contentId + " does not exist any more."));
		when(policyCmServer.contentExists(contentId)).thenReturn(false);
	}

	private VersionInfo createVersionInfo(final VersionedContentId versionedContentId, final long committed) throws CMException {
		final UserId sysadminUserId = sysadminUserId();
		final VersionInfoImpl versionInfo = new VersionInfoImpl(versionedContentId.getVersion(),
				0, getPreviousVersionIfExists(versionedContentId),
				committed, sysadminUserId, sysadminUserId);
		return versionInfo;
	}

	private int getPreviousVersionIfExists(final VersionedContentId versionedContentId) throws CMException {
		if(policyCmServer.contentExists(versionedContentId.getContentId())) {
			return policyCmServer.getContent(versionedContentId.getContentId()).getContentId().getVersion();
		} else {
			return -1;
		}
	}

	private UserId sysadminUserId() {
		return new UserId("98");
	}

	private InputTemplate getInputTemplate() {
		if (this.inputTemplateInstance != null) {
			return this.inputTemplateInstance;
		} else {
			return InputTemplateFactory.createInputTemplateMock(this.policyName, this.inputTemplateExternalId);
		}
	}

	private void mockComponentNames(final Map<ComponentIdentifier, String> components, final Content content) throws CMException {
		final ArrayList<String> componentGroupNames = new ArrayList<>();
		for (Map.Entry<ComponentIdentifier, String> entry : components.entrySet()) {
			componentGroupNames.add(entry.getValue());
			when(content.getComponent(entry.getKey().componentGroupName, entry.getKey().componentName)).thenReturn(entry.getValue());
			when(content.getComponentNames(entry.getKey().componentGroupName)).thenReturn(getAllComponentNamesForGroup(entry.getKey().componentGroupName, components));
		}
		when(content.getComponentGroupNames()).thenReturn(componentGroupNames.toArray(new String[0]));
	}

	private String[] getAllComponentNamesForGroup(final String componentGroupName, final Map<ComponentIdentifier, String> components) {
		final ArrayList<String> componentNames = new ArrayList<>();
		for (Map.Entry<ComponentIdentifier, String> entry : components.entrySet()) {
			if (entry.getKey().componentGroupName.equals(componentGroupName)) {
				componentNames.add(entry.getKey().componentName);
			}
		}
		return componentNames.toArray(new String[0]);
	}

	private void persistInMockedCmServer(Policy policy, Content content) throws CMException {
		when(policyCmServer.contentExists(policy.getContentId())).thenReturn(true);
		when(policyCmServer.contentExists(policy.getContentId().getContentId())).thenReturn(true);
		when(policyCmServer.getPolicy(policy.getContentId())).thenReturn(policy);
		when(policyCmServer.getPolicy(policy.getContentId().getContentId())).thenReturn(policy);
		when(policyCmServer.getContent(policy.getContentId())).thenReturn(content);
		when(policyCmServer.getContent(policy.getContentId().getContentId())).thenReturn(content);
		if (content.getExternalId() != null) {
			when(policyCmServer.getPolicy(content.getExternalId())).thenReturn(policy);
			when(policyCmServer.getContent(content.getExternalId())).thenReturn(content);
			final ExternalContentId externalContentIdWithoutVersion = new ExternalContentId(content.getExternalId().getExternalId());
			when(policyCmServer.getPolicy(externalContentIdWithoutVersion)).thenReturn(policy);
			when(policyCmServer.getContent(externalContentIdWithoutVersion)).thenReturn(content);
		}
	}

	private void initPolicy(final Policy policy, final Content content, final PolicyCMServer policyCMServer, final InputTemplate inputTemplate) throws CMException {
		// be sure to have an input template external ID
		if (inputTemplate.getExternalId() == null) {
			when(inputTemplate.getExternalId()).thenReturn(new ExternalContentId("de.wellnerbou.defaultInputTemplateName"));
		}
		policy.init(policyName, new Content[]{content}, inputTemplate, null, policyCMServer);
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.dou361.dialogui.holder;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.R;
import com.dou361.dialogui.bean.BuildBean;
import com.dou361.dialogui.utils.ToolUtils;

import java.util.Map;

/**
 * Created by 魏文强 on 2017/5/20.
 */

public class IosAddCommStandardHolder extends SuperHolder {
    protected TextView tvTitle;
    protected Button btn1;
    protected Button btn2;
    protected Button btn3;
    protected LinearLayout lyt_add_editview;
    protected ScrollView sv;

    public IosAddCommStandardHolder(Context context) {
        super(context);
    }

    @Override
    protected void findViews() {
        tvTitle = (TextView) rootView.findViewById(R.id.tv_title);
        btn1 = (Button) rootView.findViewById(R.id.btn_1);
        btn2 = (Button) rootView.findViewById(R.id.btn_2);
        btn3 = (Button) rootView.findViewById(R.id.btn_3);
        lyt_add_editview = (LinearLayout) rootView.findViewById(R.id.lyt_add_editview);
        sv = (ScrollView) rootView.findViewById(R.id.sv);

    }

    @Override
    protected int setLayoutRes() {
        return R.layout.dialog_ios_add_attr;
    }

    @Override
    public void assingDatasAndEvents(final Context context, final BuildBean bean) {
        btn3.setTextSize(bean.btnTxtSize);
        btn2.setTextSize(bean.btnTxtSize);
        btn1.setTextSize(bean.btnTxtSize);

        btn1.setTextColor(ToolUtils.getColor(btn1.getContext(), bean.btn1Color));
        btn2.setTextColor(ToolUtils.getColor(btn1.getContext(), bean.btn2Color));
        btn3.setTextColor(ToolUtils.getColor(btn1.getContext(), bean.btn3Color));

        if (TextUtils.isEmpty(bean.title)) {
            tvTitle.setVisibility(View.GONE);
        } else {
            tvTitle.setVisibility(View.VISIBLE);
            tvTitle.setText(bean.title);
            tvTitle.setTextColor(ToolUtils.getColor(tvTitle.getContext(), bean.titleTxtColor));
            tvTitle.setTextSize(bean.titleTxtSize);
        }

        /**
         * 编辑商品时初始化属性列表
         */

        if(!TextUtils.isEmpty(bean.strArray)){
            for(String str : bean.strArray.toString().trim().split(",")){
                LinearLayout layout = initLinearLayout(context, bean);
//                editText.setText(str);
                lyt_add_editview.addView(layout);
            }
        }
        if(bean.map != null){
            for (Map.Entry<String, String> entry : bean.map.entrySet()) {
                LinearLayout layout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.widget_view_standard, null);
                EditText editName = (EditText) layout.findViewById(R.id.edt_name);
                editName.setText(entry.getKey());
                EditText editMoney = (EditText) layout.findViewById(R.id.edt_money);
                editMoney.setText(entry.getValue());
                lyt_add_editview.addView(layout);
            }
        }else {
            lyt_add_editview.addView(initLinearLayout(context, bean));
        }

        //事件
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(lyt_add_editview.getChildCount() < bean.addNumber){
                    lyt_add_editview.addView(initLinearLayout(context, bean));
                }else {
                    Toast.makeText(context, "无法添加更多", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(lyt_add_editview.getChildCount() < 2){
                    DialogUIUtils.dismiss(bean.dialog, bean.alertDialog);
                }else{
                    lyt_add_editview.removeViewAt(lyt_add_editview.getChildCount()-1);
                }
            }
        });

        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                StringBuffer sb = new StringBuffer("");
                for(int i=0; i< lyt_add_editview.getChildCount(); i++){
                    LinearLayout layout = (LinearLayout) lyt_add_editview.getChildAt(i);
                    EditText editName = (EditText) layout.findViewById(R.id.edt_name);
                    String name = editName.getText().toString().trim();

                    EditText editMoney = (EditText) layout.findViewById(R.id.edt_money);
                    String money = editMoney.getText().toString().trim();

                    if(TextUtils.isEmpty(name) || TextUtils.isEmpty(money)){
                        Toast.makeText(context, "请完整填写属性", Toast.LENGTH_SHORT).show();
                        return;
                    } else if(name.indexOf(",")!= -1 || money.indexOf(",")!= -1){
                        Toast.makeText(context, "输入包含非法字符", Toast.LENGTH_SHORT).show();
                        return;
                    }else {
                        sb.append(name+":"+money+",");
                    }
                }
                String text = TextUtils.isEmpty(sb.toString().trim()) ? "" : sb.substring(0, sb.length()-1);
                bean.addListener.onAddAttribute(text);
                Toast.makeText(context, sb.toString(), Toast.LENGTH_SHORT).show();
                DialogUIUtils.dismiss(bean.dialog, bean.alertDialog);
            }
        });

    }

    private LinearLayout initLinearLayout(Context context, final BuildBean bean){
        LinearLayout layout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.widget_view_standard, null);
        EditText editName = (EditText) layout.findViewById(R.id.edt_name);
        editName.setHint(bean.hint1);

        EditText editMoney = (EditText) layout.findViewById(R.id.edt_money);
        editMoney.setHint(bean.hint2);

        return layout;
    }
}


text:
autoHighlight.vim
============

Auto highlight word under cursor


text:
<form class="form-horizontal">

		Owner

{{ project.owner }} (me) Cannot be changed, forthcoming feature.

</form>

<form name="contributorForm" class="form-horizontal" ng-submit="addContributor();">

		Contributors

							{{ email }} — me

 Remove

No contributors

				<input type="text" class="form-control" ng-model="newContributor" placeholder="Enter the email address of a new contributor...">

					<button class="btn btn-primary">Add contributor</button>

An email invitation will be sent to the new contributor with a link to sign up and access this project—if they're already on ThoughtJot! they'll receive a notification.

Contributors have read/write access to the Project. However, they do not have control over sharing.

</form>

All changes are live! No need to save here!


text:
FROM openjdk
RUN mkdir -p /opt/fixturefinder
WORKDIR /opt/fixturefinder
ENV PORT 8080
ADD ./target/fixture-finder-0.0.1.jar /opt/fixturefinder/bin/fixture-finder-0.0.1.jar


text:
package model.service;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.Query;

import main.TradeProperties;
import model.Result;

public class ResultService {

	public static Result getRecord(int dte, double shortDelta, double longDelta, double width, double profitTarget, double stopLoss, int closeDte) {

		EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAOptionsTrader");
		EntityManager em = emf.createEntityManager();

		// Note: table name refers to the Entity Class and is case sensitive
		//       field names are property names in the Entity Class
		Query query = em.createQuery("select res from Result res where "
				+ "res.dte = :dte "
				+ "and res.shortDelta = :shortDelta "
				+ "and res.longDelta = :longDelta "
				+ "and res.width = :width "
				+ "and res.profitTarget = :profitTarget "
				+ "and res.stopLoss = :stopLoss "
				+ "and res.closeDte = :closeDte "
				+ "and res.symbol = :symbol "
				+ "and res.tradeType = :tradeType "
				);

		query.setParameter("dte", dte);
		query.setParameter("shortDelta", shortDelta);
		query.setParameter("longDelta", longDelta);
		query.setParameter("width", width);
		query.setParameter("profitTarget", profitTarget);
		query.setParameter("stopLoss", stopLoss);
		query.setParameter("closeDte", closeDte);
		query.setParameter("symbol", TradeProperties.SYMBOL);
//		String s1 = TradeProperties.tradeType.getTradeName();
//		String s2 = TradeProperties.tradeType.name();
		query.setParameter("tradeType", TradeProperties.tradeType.name());

		//query.setHint("odb.read-only", "true");

		Result resultRecord = null;
		try {
			resultRecord = (Result) query.getSingleResult();
		} catch (NoResultException ignore) {
		} catch  (Exception ex) {
			System.err.println(ex.getMessage());
			System.err.println(" dte: " + dte + " shortDelta: " + shortDelta + " longDelta: " + longDelta + " width: " + width + " profitTarget: " + profitTarget + " stopLoss: " + stopLoss + " closeDte: " + closeDte);
			ex.printStackTrace();
			throw ex;
		}
		em.close();

		return resultRecord;
	}

	public static void main(String[] args) {

		EntityManagerFactory emf = null;
		EntityManager em = null;

		emf = Persistence.createEntityManagerFactory("JPAOptionsTrader");
		em = emf.createEntityManager();

		Result result = ResultService.getRecord(7, 0.1, 0, 50.0, 0.0, 0.0, 0);

		if (result != null) {
			// test edit
			System.out.println("Width: " + result.getWidth());

			em.getTransaction().begin();
			result.setMaxDd(400.25);
			result.setUpdated(new Date());
			em.merge(result);
			em.getTransaction().commit();
		} else {
			// test create
			em.getTransaction().begin();

			// id = 0 after new
			result = new Result();

			result.setSymbol("XYZ");
			result.setTradeType("SHORT_CALL");
			result.setDte(7);
			result.setShortDelta(0.1);
			result.setWidth(50.0);

			em.persist(result);
			em.getTransaction().commit();
		}

		em.close();
		emf.close();

		System.out.println("Finished");
	}

}


text:
<?php

//$auth_code = "DQAAAL0AAAB51YAoFUuCUIqpyAg1ELVumMh108cjZzD9-fdLGU2N1-4rnby86X_L5fffvVH2-jXzxyDoJfB5z7xd_d4zRsCY3mXCVrvLqpr9dY0wPam9O2okBi_cbUu9wrgaf1LlTwqjPFt2xH_ojHvVqn0wElERgYlOKnaWwa0X5Oa1g3H5nhlseoD9EtOt3u1RGLDbYo3inVIlj6sWD32CCe4FUfciBAtPCZdb2losUPSl3YYbieq-X6MgTjRMNSRW-yA29FY";
//$registrationId = "APA91bELfPQhZAYm1lBmVonU4FM3Sr-UjURhYA8HNsQSBg9G_yKWPixFdH-ADMkZMRxEVLMF3hQeya20Zx5x22oT4a-066xhjgJ4-NJK4QiUsydv934qBPL7-aS8ysGY99GrnNbt9wVu";

$auth_code = $_POST["auth_code"];
$registrationId = $_POST["registrationId"];

sendMessageToPhone($auth_code, $registrationId, "0", "This is the second message ");

function sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText) {

        $headers = array('Authorization: GoogleLogin auth=' . $authCode);
        $data = array(
            'registration_id' => $deviceRegistrationId,
            'collapse_key' => $msgType,
            'data.payload' => $messageText //TODO Add more params with just simple data instead
        );

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");
        if ($headers)
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        $response = curl_exec($ch);

        curl_close($ch);

        return $response;
    }

?>


text:
=========================

##How to install and setup the app.

1. There is some required software in order to setup this project.
Ensure you have Eclipse along with the Google App Engine and EGit plugins installed.
Instructions for installing the GAE plugin for Eclipse can be found here:
https://cloud.google.com/appengine/docs/java/tools/eclipse

2. In order to add the project to Eclipse, go to File -> Import and under Git select Projects from Git.
3. Enter the following url to clone the repository: https://github.com/mcmathews/CSE-360-Digital-Scrapbook.git
4. Add all of the jars in /war/WEB-INF/lib directory to the build path.
5. Ensure the proper src directory is set as the project source directory (which would be /src).
6. Ensure under Project properties -> Google, Use App Engine is checked.
7. You should be good to go!

============================

##Running Tests

###Unit Tests

Once the app is set up in eclipse, the JUnit tests can be run through the Eclipse.
Running the AllTests.java test suite will run all the unit tests.

###Functional Tests

1. The Functional Tests we're written using Selenium IDE, so this plugin is required for Firefox to run the tests.
2. In Firefox, make sure to log out of all Google Services before continuing.
3. In Firefox, go to http://accounts.google.com and sign in with the username: CSE.360.Project.Test.User@gmail.com and the password: mUOkM9$#3c6P8KMXRAWP&59r!JcMQoSaEYWF
4. Then log out of Google.
5. Now open Selenium IDE
6. Open the test suite in the project folder in /war/tests/FunctionalTestSuite.html
7. Make sure to set the slider in the top left corner of the Selenium IDE to "Slow"
8. Run the Suite.


text:
import copy
import platform

import pytest

from datadog_checks.base.utils.platform import Platform

from . import common

pytestmark = pytest.mark.integration

@pytest.mark.usefixtures("dd_environment")
def test_check(aggregator, check, instance):
    check_instance = check(instance)
    check_instance.check({})

    expected_metrics = copy.deepcopy(common.EXPECTED_METRICS)
    if Platform.is_windows() or Platform.is_linux():
        expected_metrics += common.EXPECTED_WINDOWS_LINUX_METRICS
    for metric in expected_metrics:
        aggregator.assert_metric(metric)

@pytest.mark.skipif(platform.system() != 'Linux', reason="Only runs on Linux systems")
@pytest.mark.usefixtures("dd_environment")
def test_check_linux(aggregator, check, instance_blacklist):
    check_instance = check(instance_blacklist)
    check_instance.check({})

    for metric in common.CONNTRACK_METRICS:
        aggregator.assert_metric(metric)


text:
class Texture {
public:
	TextureType getType() const;
	unsigned int getTextureID() const;

	Texture( const char*, const TextureType );
	~Texture();

private:
	void setupTexture( const char * filename );

private:
	TextureType type;
	unsigned int textureID;
};


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Gäumann, Beitr. Kryptfl. Schweiz 5(4): 291 (1923)

#### Original name
Peronospora gei Syd., 1923

### Remarks
null


text: {{ object.description }}


text: console.log(event.target + "");


text:
'use strict';

const common = require('../common');
const fs = require('fs');
const path = require('path');

const bench = common.createBenchmark(main, {
  n: [1e4],
});

function main({ n }) {
  bench.start();
  for (var i = 0; i < n; i++) {
    fs.readdirSync(path.resolve(__dirname, '../../lib/'));
  }
  bench.end(n);
}


text:
(function () {
    'use strict';

    angular.module('mgApp').factory('PracticeService', PracticeService);

    PracticeService.$inject = ['$http', '$q'];
    function PracticeService($http, $q) {
        var service = {
            create: function (wordListId) {
                var deferred = $q.defer();
                $http.post(
                    '/api/practicesession',
                    {
                        wordListId: wordListId
                    })
                    .success(function (result) {
                        deferred.resolve(result.practiceSessionId);
                    })
                    .error(function (response) {
                        deferred.reject(response);
                    });
                return deferred.promise;
            },
            getUnfinished: function (wordListId) {
                var deferred = $q.defer();
                $http.get(
                    '/api/unfinishedpracticesession',
                    {
                        params:
                        {
                            wordListId: wordListId
                        }
                    })
                    .success(function (result) {
                        deferred.resolve(result);
                    })
                    .error(function (response) {
                        deferred.reject(response);
                    });
                return deferred.promise;
            }
        };

        return service;
    }
})();


text:
enum Test {
    DivZero = 1/0,
    //~^ attempt to divide `1_isize` by zero
    //~| ERROR evaluation of constant value failed
    RemZero = 1%0,
    //~^ attempt to calculate the remainder of `1_isize` with a divisor of zero
    //~| ERROR evaluation of constant value failed
}

fn main() {}


text:
package krasa.mavenhelper.action;

import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClassOwner;
import com.intellij.psi.PsiFile;
import krasa.mavenhelper.analyzer.ComparableVersion;
import krasa.mavenhelper.icons.MyIcons;
import krasa.mavenhelper.model.ApplicationSettings;
import org.apache.maven.shared.utils.io.MatchPatterns;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.execution.MavenRunnerParameters;
import org.jetbrains.idea.maven.model.MavenPlugin;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.utils.actions.MavenActionUtil;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

public class RunTestFileAction extends DumbAwareAction {
	private final Logger LOG = Logger.getInstance("#" + getClass().getCanonicalName());
	protected boolean alwaysVisible;

	public RunTestFileAction() {
		super("Test file", "Run current File with Maven", MyIcons.MAVEN_LOGO);
	}

	public RunTestFileAction(String text, @Nullable String description, @Nullable Icon icon) {
		super(text, description, icon);
	}

	@Override
	public void actionPerformed(AnActionEvent e) {
		MavenProject mavenProject = Utils.getMavenProject(e.getDataContext());
		if (mavenProject != null) {

			PsiFile psiFile = LangDataKeys.PSI_FILE.getData(e.getDataContext());
			if (psiFile instanceof PsiClassOwner) {
				List<String> goals = getGoals(e, (PsiClassOwner) psiFile, mavenProject);

				final DataContext context = e.getDataContext();
				MavenRunnerParameters params = new MavenRunnerParameters(true, mavenProject.getDirectory(), null, goals,
						MavenActionUtil.getProjectsManager(context).getExplicitProfiles());
				params.setResolveToWorkspace(ApplicationSettings.get().isResolveWorkspaceArtifacts());
				run(context, params);
			} else {
				Messages.showWarningDialog(e.getProject(), "Cannot run for current file", "Maven Test File");
			}
		}
	}

	protected void run(DataContext context, MavenRunnerParameters params) {
		Project project = MavenActionUtil.getProject(context);
		ProgramRunnerUtils.run(project, params);
	}

	protected List<String> getGoals(AnActionEvent e, PsiClassOwner psiFile, MavenProject mavenProject) {
		List<String> goals = new ArrayList<String>();
		boolean skipTests = isSkipTests(mavenProject);
		// so many possibilities...
		if (skipTests || isExcludedFromSurefire(psiFile, mavenProject)) {
			MavenPlugin failsafePlugin = mavenProject.findPlugin("org.apache.maven.plugins", "maven-failsafe-plugin");
			if (failsafePlugin != null) {
				addFailSafeParameters(e, psiFile, goals, failsafePlugin);
			} else {
				addSurefireParameters(e, psiFile, goals);
			}
			goals.add("verify");
		} else {
			addSurefireParameters(e, psiFile, goals);
			goals.add("test-compile");
			goals.add("surefire:test");
		}

		return goals;
	}

	private void addSurefireParameters(AnActionEvent e, PsiClassOwner psiFile, List<String> goals) {
		goals.add("-Dtest=" + Utils.getTestArgument(psiFile, ConfigurationContext.getFromContext(e.getDataContext())));
	}

	private void addFailSafeParameters(AnActionEvent e, PsiClassOwner psiFile, List<String> goals, MavenPlugin mavenProjectPlugin) {
		ComparableVersion version = new ComparableVersion(mavenProjectPlugin.getVersion());
		ComparableVersion minimumForMethodTest = new ComparableVersion("2.7.3");
		if (minimumForMethodTest.compareTo(version) == 1) {
			goals.add("-Dit.test=" + Utils.getTestArgumentWithoutMethod(e, psiFile));
		} else {
			goals.add("-Dit.test=" + Utils.getTestArgument(psiFile, ConfigurationContext.getFromContext(e.getDataContext())));
		}
	}

	private boolean isExcludedFromSurefire(PsiClassOwner psiFile, MavenProject mavenProject) {
		boolean excluded = false;
		try {
			Element pluginConfiguration = mavenProject.getPluginConfiguration("org.apache.maven.plugins",
					"maven-surefire-plugin");
			excluded = false;
			String fullName = null;
			if (pluginConfiguration != null) {
				Element excludes = pluginConfiguration.getChild("excludes");
				if (excludes != null) {
					List<Element> exclude = excludes.getChildren("exclude");
					for (Element element : exclude) {
						if (fullName == null) {
							fullName = getPsiFilePath(psiFile);
						}
						excluded = matchClassRegexPatter(fullName, element.getText());
						if (excluded) {
							break;
						}
					}
				}
			}
		} catch (Exception e) {
			LOG.warn(e);
		}
		return excluded;
	}

	protected static boolean matchClassRegexPatter(String testClassFile, String classPattern) {
		return MatchPatterns.from(classPattern).matches(testClassFile, true);
	}

	@NotNull
	private String getPsiFilePath(PsiClassOwner psiFile) {
		String packageName = psiFile.getPackageName();
		String fullName;
		if (packageName.isEmpty()) {
			fullName = psiFile.getName();
		} else {
			fullName = packageName.replace(".", "/") + "/" + psiFile.getVirtualFile().getName();
		}
		return fullName;
	}

	private boolean isSkipTests(MavenProject mavenProject) {
		Element pluginConfiguration = mavenProject.getPluginConfiguration("org.apache.maven.plugins",
				"maven-surefire-plugin");
		boolean skipTests = false;
		if (pluginConfiguration != null) {
			Element skip;
			if ((skip = pluginConfiguration.getChild("skip")) != null) {
				skipTests = Boolean.parseBoolean(skip.getText());
			} else if ((skip = pluginConfiguration.getChild("skipTests")) != null) {
				skipTests = Boolean.parseBoolean(skip.getText());
			}
		}
		return skipTests;
	}

	@Override
	public void update(AnActionEvent e) {
		super.update(e);
		Project eventProject = getEventProject(e);
		if (eventProject == null) {
			return;
		}
		if (DumbService.isDumb(eventProject)) {
			Presentation p = e.getPresentation();
			p.setVisible(false);
			return;
		}
		if (!MavenActionUtil.isMavenizedProject(e.getDataContext())) {
			Presentation p = e.getPresentation();
			p.setVisible(false);
			return;
		}

		//TODO #71  perhaps by com.intellij.execution.actions.BaseRunConfigurationAction.fullUpdate
		PsiFile psiFile = PlatformDataKeys.PSI_FILE.getData(e.getDataContext());
		boolean isTest = psiFile != null;
		boolean available = isAvailable(e);
		boolean visible = isVisible(e);

		Presentation p = e.getPresentation();
		p.setEnabled(isTest && available);
		p.setVisible(alwaysVisible || (isTest && available));
		if (isTest && available && visible) {
			VirtualFile virtualFile = psiFile.getVirtualFile();
			String name;
			if (virtualFile != null) {
				name = virtualFile.getNameWithoutExtension();
			} else {
				name = psiFile.getName();
			}
			p.setText(getText(name));
		}
	}

	protected String getText(String s) {
		return "Test " + s;
	}

	protected boolean isAvailable(AnActionEvent e) {
		boolean isFile = false;
		VirtualFile data = PlatformDataKeys.VIRTUAL_FILE.getData(e.getDataContext());
		if (data != null) {
			isFile = !data.isDirectory();
		}

		return isFile && MavenActionUtil.hasProject(e.getDataContext());
	}

	protected boolean isVisible(AnActionEvent e) {
		MavenProject mavenProject = Utils.getMavenProject(e.getDataContext());
		return mavenProject != null;
	}

	public AnAction alwaysVisible() {
		alwaysVisible = true;
		return this;
	}
}


text:
@interface SIObject ()
//@property (nonatomic, readonly, retain) NILinkedList* list;
@property (nonatomic, readonly, retain) NSMutableDictionary* data;
@end

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
@implementation SIObject

@synthesize ID   = _ID;
@synthesize data = _data;

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)dealloc {
    [_data removeAllObjects];
    _data = nil;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (id)init {
    NIDERROR(@"Use initWithID: instead");
    NIDASSERT(NO);
    return nil;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// TODO initWithFormat or concate???
- (id)initWithID:(NSString *)ID, ... {
    if (self = [super init]) {
        va_list vargs;
        va_start(vargs, ID);
        _ID = [[NSString alloc] initWithFormat:ID arguments:vargs];
        va_end(vargs);
    }
    return self;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Private properties

///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSMutableDictionary *)data {
    if (! _data) {
        _data = [NSMutableDictionary dictionary];
    }
    return _data;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - NSObject

///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSString *)description {
    return [NSString stringWithFormat:@"<%@: %@>", self.className, self.ID];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - NSFastEnumeration

///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
                                  objects:(WeakRef id [])buffer
                                    count:(NSUInteger)len {
    return [self.data countByEnumeratingWithState:state objects:buffer count:len];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Public methods

///////////////////////////////////////////////////////////////////////////////////////////////////
- (id)objectForKey:(NSString *)key {
    return [self.data objectForKey:key];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (id)popForKey:(NSString *)key {
    id object = [self objectForKey:key];
    [self setObject:nil forKey:key];
    return object;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setObject:(id)object forKey:(NSString *)key {
    [self.data setObject:object forKey:key];
}

@end


text:
extern "C" {
#include "postgres.h"

#include "nodes/primnodes.h"
#include "nodes/value.h"
}
#include "gpos/error/CAutoTrace.h"

#include "gpopt/gpdbwrappers.h"
#include "gpopt/translate/CMappingVarColId.h"
#include "gpopt/translate/CTranslatorUtils.h"
#include "naucrates/dxl/CDXLUtils.h"
#include "naucrates/md/IMDIndex.h"

using namespace gpdxl;
using namespace gpmd;

//---------------------------------------------------------------------------
//	@function:
//		CMappingVarColId::CMappingVarColId
//
//	@doc:
//		Ctor
//
//---------------------------------------------------------------------------
CMappingVarColId::CMappingVarColId(CMemoryPool *mp) : m_mp(mp)
{
	// This map can have many entries if there are many tables with many columns
	// in the query, so use a larger hash map to minimize collisions
	m_gpdb_att_opt_col_mapping =
		GPOS_NEW(m_mp) GPDBAttOptColHashMap(m_mp, 2047);
}

//---------------------------------------------------------------------------
//	@function:
//		CMappingVarColId::GetGPDBAttOptColMapping
//
//	@doc:
//		Given a gpdb attribute, return the mapping info to opt col
//
//---------------------------------------------------------------------------
const CGPDBAttOptCol *
CMappingVarColId::GetGPDBAttOptColMapping(
	ULONG current_query_level, const Var *var,
	EPlStmtPhysicalOpType plstmt_physical_op_type) const
{
	GPOS_ASSERT(NULL != var);
	GPOS_ASSERT(current_query_level >= var->varlevelsup);

	// absolute query level of var
	ULONG abs_query_level = current_query_level - var->varlevelsup;

	// extract varno
	ULONG var_no = var->varno;
	if (EpspotWindow == plstmt_physical_op_type ||
		EpspotAgg == plstmt_physical_op_type ||
		EpspotMaterialize == plstmt_physical_op_type)
	{
		// Agg and Materialize need to employ OUTER, since they have other
		// values in GPDB world
		var_no = OUTER_VAR;
	}

	CGPDBAttInfo *gpdb_att_info =
		GPOS_NEW(m_mp) CGPDBAttInfo(abs_query_level, var_no, var->varattno);
	CGPDBAttOptCol *gpdb_att_opt_col_info =
		m_gpdb_att_opt_col_mapping->Find(gpdb_att_info);

	if (NULL == gpdb_att_opt_col_info)
	{
		// TODO: Sept 09 2013, remove temporary fix (revert exception to assert) to avoid crash during algebrization
		GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLError,
				   GPOS_WSZ_LIT("No variable"));
	}

	gpdb_att_info->Release();
	return gpdb_att_opt_col_info;
}

//---------------------------------------------------------------------------
//	@function:
//		CMappingVarColId::GetOptColName
//
//	@doc:
//		Given a gpdb attribute, return a column name in optimizer world
//
//---------------------------------------------------------------------------
const CWStringBase *
CMappingVarColId::GetOptColName(
	ULONG current_query_level, const Var *var,
	EPlStmtPhysicalOpType plstmt_physical_op_type) const
{
	return GetGPDBAttOptColMapping(current_query_level, var,
								   plstmt_physical_op_type)
		->GetOptColInfo()
		->GetOptColName();
}

//---------------------------------------------------------------------------
//	@function:
//		CMappingVarColId::GetColId
//
//	@doc:
//		given a gpdb attribute, return a column id in optimizer world
//
//---------------------------------------------------------------------------
ULONG
CMappingVarColId::GetColId(ULONG current_query_level, const Var *var,
						   EPlStmtPhysicalOpType plstmt_physical_op_type) const
{
	return GetGPDBAttOptColMapping(current_query_level, var,
								   plstmt_physical_op_type)
		->GetOptColInfo()
		->GetColId();
}

//---------------------------------------------------------------------------
//	@function:
//		CMappingVarColId::Insert
//
//	@doc:
//		Insert a single entry into the hash map
//
//---------------------------------------------------------------------------
void
CMappingVarColId::Insert(ULONG query_level, ULONG var_no, INT attrnum,
						 ULONG colid, CWStringBase *column_name)
{
	// GPDB agg node uses 0 in Var, but that should've been taken care of
	// by translator
	GPOS_ASSERT(var_no > 0);

	// create key
	CGPDBAttInfo *gpdb_att_info =
		GPOS_NEW(m_mp) CGPDBAttInfo(query_level, var_no, attrnum);

	// create value
	COptColInfo *opt_col_info = GPOS_NEW(m_mp) COptColInfo(colid, column_name);

	// key is part of value, bump up refcount
	gpdb_att_info->AddRef();
	CGPDBAttOptCol *gpdb_att_opt_col_info =
		GPOS_NEW(m_mp) CGPDBAttOptCol(gpdb_att_info, opt_col_info);

	BOOL result GPOS_ASSERTS_ONLY = m_gpdb_att_opt_col_mapping->Insert(
		gpdb_att_info, gpdb_att_opt_col_info);

	GPOS_ASSERT(result);
}

//---------------------------------------------------------------------------
//	@function:
//		CMappingVarColId::LoadTblColumns
//
//	@doc:
//		Load up information from GPDB's base table RTE and corresponding
//		optimizer table descriptor
//
//---------------------------------------------------------------------------
void
CMappingVarColId::LoadTblColumns(ULONG query_level, ULONG RTE_index,
								 const CDXLTableDescr *table_descr)
{
	GPOS_ASSERT(NULL != table_descr);
	const ULONG size = table_descr->Arity();

	// add mapping information for columns
	for (ULONG i = 0; i < size; i++)
	{
		const CDXLColDescr *dxl_col_descr = table_descr->GetColumnDescrAt(i);
		this->Insert(query_level, RTE_index, dxl_col_descr->AttrNum(),
					 dxl_col_descr->Id(),
					 dxl_col_descr->MdName()->GetMDName()->Copy(m_mp));
	}
}

//---------------------------------------------------------------------------
//	@function:
//		CMappingVarColId::LoadIndexColumns
//
//	@doc:
//		Load up information from GPDB index and corresponding
//		optimizer table descriptor
//
//---------------------------------------------------------------------------
void
CMappingVarColId::LoadIndexColumns(ULONG query_level, ULONG RTE_index,
								   const IMDIndex *index,
								   const CDXLTableDescr *table_descr)
{
	GPOS_ASSERT(NULL != table_descr);

	const ULONG size = index->Keys();

	// add mapping information for columns
	for (ULONG i = 0; i < size; i++)
	{
		ULONG pos = index->KeyAt(i);
		const CDXLColDescr *dxl_col_descr = table_descr->GetColumnDescrAt(pos);
		this->Insert(query_level, RTE_index, INT(i + 1), dxl_col_descr->Id(),
					 dxl_col_descr->MdName()->GetMDName()->Copy(m_mp));
	}
}

//---------------------------------------------------------------------------
//	@function:
//		CMappingVarColId::Load
//
//	@doc:
//		Load column mapping information from list of column names
//
//---------------------------------------------------------------------------
void
CMappingVarColId::Load(ULONG query_level, ULONG RTE_index,
					   CIdGenerator *id_generator, List *col_names)
{
	ListCell *col_name = NULL;
	ULONG i = 0;

	// add mapping information for columns
	ForEach(col_name, col_names)
	{
		Value *value = (Value *) lfirst(col_name);
		CHAR *col_name_char_array = strVal(value);

		CWStringDynamic *column_name =
			CDXLUtils::CreateDynamicStringFromCharArray(m_mp,
														col_name_char_array);

		this->Insert(query_level, RTE_index, INT(i + 1),
					 id_generator->next_id(), column_name->Copy(m_mp));

		i++;
		GPOS_DELETE(column_name);
	}
}

//---------------------------------------------------------------------------
//	@function:
//		CMappingVarColId::LoadColumns
//
//	@doc:
//		Load up columns information from the array of column descriptors
//
//---------------------------------------------------------------------------
void
CMappingVarColId::LoadColumns(ULONG query_level, ULONG RTE_index,
							  const CDXLColDescrArray *column_descrs)
{
	GPOS_ASSERT(NULL != column_descrs);
	const ULONG size = column_descrs->Size();

	// add mapping information for columns
	for (ULONG i = 0; i < size; i++)
	{
		const CDXLColDescr *dxl_col_descr = (*column_descrs)[i];
		this->Insert(query_level, RTE_index, dxl_col_descr->AttrNum(),
					 dxl_col_descr->Id(),
					 dxl_col_descr->MdName()->GetMDName()->Copy(m_mp));
	}
}

//---------------------------------------------------------------------------
//	@function:
//		CMappingVarColId::LoadDerivedTblColumns
//
//	@doc:
//		Load up information from column information in derived tables
//
//---------------------------------------------------------------------------
void
CMappingVarColId::LoadDerivedTblColumns(
	ULONG query_level, ULONG RTE_index,
	const CDXLNodeArray *derived_columns_dxl, List *target_list)
{
	GPOS_ASSERT(NULL != derived_columns_dxl);
	GPOS_ASSERT((ULONG) gpdb::ListLength(target_list) >=
				derived_columns_dxl->Size());

	ULONG drvd_tbl_col_counter =
		0;	// counter for the dynamic array of DXL nodes
	ListCell *lc = NULL;
	ForEach(lc, target_list)
	{
		TargetEntry *target_entry = (TargetEntry *) lfirst(lc);
		if (!target_entry->resjunk)
		{
			GPOS_ASSERT(0 < target_entry->resno);
			CDXLNode *dxlnode = (*derived_columns_dxl)[drvd_tbl_col_counter];
			GPOS_ASSERT(NULL != dxlnode);
			CDXLScalarIdent *dxl_sc_ident =
				CDXLScalarIdent::Cast(dxlnode->GetOperator());
			const CDXLColRef *dxl_colref = dxl_sc_ident->GetDXLColRef();
			this->Insert(query_level, RTE_index, INT(target_entry->resno),
						 dxl_colref->Id(),
						 dxl_colref->MdName()->GetMDName()->Copy(m_mp));
			drvd_tbl_col_counter++;
		}
	}
}

//---------------------------------------------------------------------------
//	@function:
//		CMappingVarColId::LoadCTEColumns
//
//	@doc:
//		Load CTE column mappings
//
//---------------------------------------------------------------------------
void
CMappingVarColId::LoadCTEColumns(ULONG query_level, ULONG RTE_index,
								 const ULongPtrArray *CTE_columns,
								 List *target_list)
{
	GPOS_ASSERT(NULL != CTE_columns);
	GPOS_ASSERT((ULONG) gpdb::ListLength(target_list) >= CTE_columns->Size());

	ULONG idx = 0;
	ListCell *lc = NULL;
	ForEach(lc, target_list)
	{
		TargetEntry *target_entry = (TargetEntry *) lfirst(lc);
		if (!target_entry->resjunk)
		{
			GPOS_ASSERT(0 < target_entry->resno);
			ULONG CTE_colid = *((*CTE_columns)[idx]);

			CWStringDynamic *column_name =
				CDXLUtils::CreateDynamicStringFromCharArray(
					m_mp, target_entry->resname);
			this->Insert(query_level, RTE_index, INT(target_entry->resno),
						 CTE_colid, column_name);
			idx++;
		}
	}
}

//---------------------------------------------------------------------------
//	@function:
//		CMappingVarColId::LoadProjectElements
//
//	@doc:
//		Load up information from projection list created from GPDB join expression
//
//---------------------------------------------------------------------------
void
CMappingVarColId::LoadProjectElements(ULONG query_level, ULONG RTE_index,
									  const CDXLNode *project_list_dxlnode)
{
	GPOS_ASSERT(NULL != project_list_dxlnode);
	const ULONG size = project_list_dxlnode->Arity();
	// add mapping information for columns
	for (ULONG i = 0; i < size; i++)
	{
		CDXLNode *dxlnode = (*project_list_dxlnode)[i];
		CDXLScalarProjElem *dxl_proj_elem =
			CDXLScalarProjElem::Cast(dxlnode->GetOperator());
		this->Insert(query_level, RTE_index, INT(i + 1), dxl_proj_elem->Id(),
					 dxl_proj_elem->GetMdNameAlias()->GetMDName()->Copy(m_mp));
	}
}

//---------------------------------------------------------------------------
//	@function:
//		CMappingVarColId::CopyMapColId
//
//	@doc:
//		Create a deep copy
//
//---------------------------------------------------------------------------
CMappingVarColId *
CMappingVarColId::CopyMapColId(ULONG query_level) const
{
	CMappingVarColId *var_colid_mapping = GPOS_NEW(m_mp) CMappingVarColId(m_mp);

	// iterate over full map
	GPDBAttOptColHashMapIter col_map_iterator(this->m_gpdb_att_opt_col_mapping);
	while (col_map_iterator.Advance())
	{
		const CGPDBAttOptCol *gpdb_att_opt_col_info = col_map_iterator.Value();
		const CGPDBAttInfo *gpdb_att_info =
			gpdb_att_opt_col_info->GetGPDBAttInfo();
		const COptColInfo *opt_col_info =
			gpdb_att_opt_col_info->GetOptColInfo();

		if (gpdb_att_info->GetQueryLevel() <= query_level)
		{
			// include all variables defined at same query level or before
			CGPDBAttInfo *gpdb_att_info_new = GPOS_NEW(m_mp) CGPDBAttInfo(
				gpdb_att_info->GetQueryLevel(), gpdb_att_info->GetVarNo(),
				gpdb_att_info->GetAttNo());
			COptColInfo *opt_col_info_new = GPOS_NEW(m_mp) COptColInfo(
				opt_col_info->GetColId(),
				GPOS_NEW(m_mp) CWStringConst(
					m_mp, opt_col_info->GetOptColName()->GetBuffer()));
			gpdb_att_info_new->AddRef();
			CGPDBAttOptCol *gpdb_att_opt_col_new = GPOS_NEW(m_mp)
				CGPDBAttOptCol(gpdb_att_info_new, opt_col_info_new);

			// insert into hashmap
			BOOL result GPOS_ASSERTS_ONLY =
				var_colid_mapping->m_gpdb_att_opt_col_mapping->Insert(
					gpdb_att_info_new, gpdb_att_opt_col_new);
			GPOS_ASSERT(result);
		}
	}

	return var_colid_mapping;
}

//---------------------------------------------------------------------------
//	@function:
//		CMappingVarColId::CopyMapColId
//
//	@doc:
//		Create a deep copy
//
//---------------------------------------------------------------------------
CMappingVarColId *
CMappingVarColId::CopyMapColId(CMemoryPool *mp) const
{
	CMappingVarColId *var_colid_mapping = GPOS_NEW(mp) CMappingVarColId(mp);

	// iterate over full map
	GPDBAttOptColHashMapIter col_map_iterator(this->m_gpdb_att_opt_col_mapping);
	while (col_map_iterator.Advance())
	{
		const CGPDBAttOptCol *gpdb_att_opt_col_info = col_map_iterator.Value();
		const CGPDBAttInfo *gpdb_att_info =
			gpdb_att_opt_col_info->GetGPDBAttInfo();
		const COptColInfo *opt_col_info =
			gpdb_att_opt_col_info->GetOptColInfo();

		CGPDBAttInfo *gpdb_att_info_new = GPOS_NEW(mp)
			CGPDBAttInfo(gpdb_att_info->GetQueryLevel(),
						 gpdb_att_info->GetVarNo(), gpdb_att_info->GetAttNo());
		COptColInfo *opt_col_info_new = GPOS_NEW(mp) COptColInfo(
			opt_col_info->GetColId(),
			GPOS_NEW(mp)
				CWStringConst(mp, opt_col_info->GetOptColName()->GetBuffer()));
		gpdb_att_info_new->AddRef();
		CGPDBAttOptCol *gpdb_att_opt_col_new =
			GPOS_NEW(mp) CGPDBAttOptCol(gpdb_att_info_new, opt_col_info_new);

		// insert into hashmap
		BOOL result GPOS_ASSERTS_ONLY =
			var_colid_mapping->m_gpdb_att_opt_col_mapping->Insert(
				gpdb_att_info_new, gpdb_att_opt_col_new);
		GPOS_ASSERT(result);
	}

	return var_colid_mapping;
}

//---------------------------------------------------------------------------
//	@function:
//		CMappingVarColId::CopyRemapColId
//
//	@doc:
//		Create a copy of the mapping replacing the old column ids by new ones
//
//---------------------------------------------------------------------------
CMappingVarColId *
CMappingVarColId::CopyRemapColId(CMemoryPool *mp, ULongPtrArray *old_colids,
								 ULongPtrArray *new_colids) const
{
	GPOS_ASSERT(NULL != old_colids);
	GPOS_ASSERT(NULL != new_colids);
	GPOS_ASSERT(new_colids->Size() == old_colids->Size());

	// construct a mapping old cols -> new cols
	UlongToUlongMap *old_new_col_mapping =
		CTranslatorUtils::MakeNewToOldColMapping(mp, old_colids, new_colids);

	CMappingVarColId *var_colid_mapping = GPOS_NEW(mp) CMappingVarColId(mp);

	GPDBAttOptColHashMapIter col_map_iterator(this->m_gpdb_att_opt_col_mapping);
	while (col_map_iterator.Advance())
	{
		const CGPDBAttOptCol *gpdb_att_opt_col_info = col_map_iterator.Value();
		const CGPDBAttInfo *gpdb_att_info =
			gpdb_att_opt_col_info->GetGPDBAttInfo();
		const COptColInfo *opt_col_info =
			gpdb_att_opt_col_info->GetOptColInfo();

		CGPDBAttInfo *gpdb_att_info_new = GPOS_NEW(mp)
			CGPDBAttInfo(gpdb_att_info->GetQueryLevel(),
						 gpdb_att_info->GetVarNo(), gpdb_att_info->GetAttNo());
		ULONG colid = opt_col_info->GetColId();
		ULONG *new_colid = old_new_col_mapping->Find(&colid);
		if (NULL != new_colid)
		{
			colid = *new_colid;
		}

		COptColInfo *opt_col_info_new = GPOS_NEW(mp) COptColInfo(
			colid, GPOS_NEW(mp) CWStringConst(
					   mp, opt_col_info->GetOptColName()->GetBuffer()));
		gpdb_att_info_new->AddRef();
		CGPDBAttOptCol *gpdb_att_opt_col_new =
			GPOS_NEW(mp) CGPDBAttOptCol(gpdb_att_info_new, opt_col_info_new);

		BOOL result GPOS_ASSERTS_ONLY =
			var_colid_mapping->m_gpdb_att_opt_col_mapping->Insert(
				gpdb_att_info_new, gpdb_att_opt_col_new);
		GPOS_ASSERT(result);
	}

	old_new_col_mapping->Release();

	return var_colid_mapping;
}

// EOF


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.jisuanqi"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.jisuanqi.JiSuanQi"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"></action>
                <category android:name="android.intent.category.LAUNCHER"></category>
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
<?xml version="1.0" encoding="UTF-8"?>

<config version="1.0" htmlParse="false">
	<item id="studyTitle">Qu'est ce qu'un bon médecin ?</item>
	<item id="textAlign">left</item>
	<item id="shuffleCards">true</item>

	<item id="loginrequired">false</item>
	<item id="loginPassword"></item>
	<item id="loginUrl"></item>
	<item id="loginUrlMethod"></item>

	<item id="showStep3">false</item>
	<item id="showStep4">false</item>
	<item id="showStep5">true</item>
	<item id="disableBackButton">true</item>

	<item id="form">
		Age
		<note>Quelle est votre année de naissance ? (Saisissez par exemple, 1980).</note>
		<input type="text" required="true" maxlength="4" restricted="0-9"></input>

		Genre
		<note>Sélectionnez votre genre.</note>
		<input type="radio" required="true">Femme;Homme</input>

		Département
		<note>Quel est votre département ? (Saisissez par exemple, 75).</note>
		<input type="text" required="true" maxlength="2" restricted="0-9"></input>

		Quel est le diplôme le plus élevé que vous ayez obtenu ?
		<input type="radio" required="true">Sans diplôme;Certificat de Formation Générale (CFG);
			Certificat d'études primaires, Diplôme National du Brevet (BEPC ou Brevet des Collèges);
			Certificat d'Aptitude Professionnelle (CAP); Brevet d'Etudes Professionnelles (BEP);
			Baccalauréat ou diplôme équivalent;
			BAC +2 ou BAC +3;BAC +4;BAC +5 ou plus;
			Autre
		</input>

		Si autre, précisez
		<input type="textarea" required="false"></input>

		Avez vous une activité professionnelle ?
		<input type="radio" required="true">Oui;Non</input>

		Si oui, laquelle
		<input type="textarea" required="false"></input>
		Si non, précisez (étudiant, chômeur, retraité...)
		<input type="textarea" required="false"></input>
		Si retraité, précisez la dernière profession exercée.
		<input type="textarea" required="false"></input>

		Concernant votre situation sociale actuelle, disposez-vous de :
		<input type="radio" required="true">
			Sécurité sociale seule;
			Sécurité sociale et mutuelle;
			CMUc (Couverture Maladie Universelle);
			AME (Aide Médicale de l'Etat);
			ACS (Aide Complémentaire de Santé);
			Aucune;
			Autre
		</input>

		Si autre, précisez:
		<input type="textarea" required="false"></input>

		Bénéficiez-vous actuellement d'une prise en charge à 100% dans le cadre d'une affection de longue durée (ALD) ?
		<input type="radio" required="true">Oui;Non; Ne se prononce pas</input>

		Présentez-vous un problème de santé chronique ?
		<note>Une maladie ou un problème de santé est chronique s'il nécessite un traitement ou une surveillance (consultations, médicaments, rééducation, surveillance, régime particulier...) depuis au moins 6 mois.</note>
		<input type="radio" required="true">Oui;Non;Ne se prononce pas</input>

		Si oui, précisez
		<input type="textarea" required="false"></input>

		Avez-vous un médecin dans votre famille ?
		<input type="radio" required="true">Oui;Non </input>

		Si oui, précisez le lien de parenté :
		<input type="textarea" required="false"></input>

		Avez-vous un médecin traitant déclaré ?
		<input type="radio" required="true">Oui;Non </input>

		Depuis combien d'années le consultez-vous ?
		<input type="text" required="true" maxlength="4" restricted="0-9"></input>

			Par an, combien de fois consultez-vous votre médecin ?
		<input type="radio" required="true">Aucune;
			Moins d'une fois par an;
			1-2 fois par an;
			3-4 fois par an;
			Plus de 4 fois par an
		</input>

		<note bg="false">Tous les champs sont obligatoires.</note>
	</item>

	<item id="submitUrl">exe.php?do=save</item>

	<item id="submitUrlMethod">firebase</item>

	<item id="submitMail">yourdomain.com</item>
</config>


text:
from django.db import models
from django.test import TestCase
from django_fsm import FSMField, transition, can_proceed

class DeferrableModel(models.Model):
    state = FSMField(default='new')

    @transition(field=state, source='new', target='published')
    def publish(self):
        pass

    @transition(field=state, source='+', target='removed')
    def remove(self):
        pass

    class Meta:
        app_label = 'testapp'

class Test(TestCase):
    def setUp(self):
        DeferrableModel.objects.create()
        self.model = DeferrableModel.objects.only('id').get()

    def test_usecase(self):
        self.assertEqual(self.model.state, 'new')
        self.assertTrue(can_proceed(self.model.remove))
        self.model.remove()

        self.assertEqual(self.model.state, 'removed')
        self.assertFalse(can_proceed(self.model.remove))


text:
/**
 * @file This is a module (i.e. not classic) javascript file. It will be loaded
 * by QuerySubmitCanvas_domSide_script.js by dynamic import().
 *
 * This provides a namespace to load other scripts and modules.
 */

export { ModuleLoader };

import * as ScriptLoader from "./util/ScriptLoader.js"

//!!! ...unfinished... (2022/08/25)
// Google Visualization API, Google Tag Manager should be load here
// (before window_onload) by append HTMLScriptElement to document head.
// (ScriptLoader.createPromise)
//
// Ourselves neural network library should be loaded here by dynamic import() function.
//

const debugPrefix = "QuerySubmitCanvas_ModuleLoader.js";

/**
 * Load the following modules:
 *   - Google Visualization API

//!!! ...unfinished... (2022/08/25)

 *   - Google Tag Manager
 *   - NeuralNet
 *
 */
class ModuleLoader {

  /** */
  async initAsync() {
    return Promise.all( [
      // (2022/08/26 Remarked) GSheet/GVizTQ.js needs not google charts library.
      //this.googleCharts_initAsync(),

//!!! ...unfinished... (2022/08/25)
// should wait for Google Tag Manager and our modules.

    ] );
  }

  /** */
  async googleCharts_initAsync() {

    const googleChartsLoaderUrl = "https://www.gstatic.com/charts/loader.js";
    const googleChartsLoaderHTMLElementId = "googleChartsLoaderJs";

    let googleChartsLoader = ScriptLoader.createPromise(
      googleChartsLoaderUrl, false, googleChartsLoaderHTMLElementId );

    await googleChartsLoader;
    // console.log( `${debugPrefix}: googleChartsLoader done...` );

    let googleChartsSafeLoad = google.charts.safeLoad( "current", {
      // packages: [ "corechart" ],
    } );

    await googleChartsSafeLoad;
    // console.log( `${debugPrefix}: google.charts.load() done...` );

    return true;
  }

}

ModuleLoader.Singleton = new ModuleLoader();


text:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System;
using Microsoft.Xna.Framework.Input;
using System.Collections.Generic;

namespace PowerOfOne
{
    public static class Scripts
    {
        public static Texture2D LoadTexture(string asset)
        {
            try
            {
                return Main.content.Load<Texture2D>(asset) as Texture2D;
            }
            catch (ContentLoadException)
            {
                Console.WriteLine("Texture not found: " + asset);
                return null;
            }
        }

        public static bool CheckIfMouseIsOver(Rectangle rect)
        {
            if (rect.Contains(Main.mouse.clickRectangle))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool KeyIsPressed(Keys key)
        {
            return Main.keyboard.JustPressed(key) || Main.keyboard.IsHeld(key);
        }

        public static bool KeyIsReleased(Keys key)
        {
            return Main.keyboard.IsReleased(key)||(!Main.keyboard.JustPressed(key) && !Main.keyboard.IsHeld(key));
        }

        public static void ForEach<T>(this IEnumerable<T> collection,Action<T> action)
        {

            foreach (var item in collection)
            {
                action(item);
            }

        }

        public static void RemoveLast<T>(this List<T> list)
        {
            list.RemoveAt(list.Count - 1);
        }

        public static bool CheckPixelPerfectCollision(Texture2D texture,Rectangle rect,Texture2D destructionTexture, Rectangle destructionnRectangle)
        {
            Rectangle intersectRect = MathAid.GetIntersectingRectangle(destructionnRectangle, rect);

            Color[] colorData = new Color[texture.Width * texture.Height];
            texture.GetData(colorData);

            Color[] destructionTextureData = new Color[destructionTexture.Width * destructionTexture.Height];
            destructionTexture.GetData(destructionTextureData);

            Point startPos1 = new Point(intersectRect.X - destructionnRectangle.X, intersectRect.Y - destructionnRectangle.Y);
            Point startPos2 = new Point(intersectRect.X - rect.X, intersectRect.Y - rect.Y);

            for (int x = 0; x < intersectRect.Width; x++)
            {

                for (int y = 0; y < intersectRect.Height; y++)
                {

                    if (destructionTextureData[(startPos1.X + x) + (startPos1.Y + y) * destructionTexture.Width].A != 0)
                    {
                        int X = startPos2.X + x;
                        int Y = startPos2.Y + y;
                        if (colorData[X + Y * texture.Width].A != 0)
                        {
                            return true;
                        }
                    }

                }

            }
            return false;
        }

        public static bool Contains(this Rectangle rect, Vector2 point)
        {
            float left = rect.X;
            float top = rect.Y;
            float right = rect.Right;
            float bottom = rect.Bottom;

            if (point.X > left && point.X < right && point.Y > top && point.Y < bottom)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static List<Rectangle> GetSourceRectangles(int startingId, int endId, int rectWidth, int rectHeight, Texture2D texture)
        {
            int rectsPerRow = texture.Width / rectWidth;
            List<Rectangle> result = new List<Rectangle>();

            for (int i = startingId; i <= endId; i++)
            {
                int sourceY = i / rectsPerRow;
                int sourceX = i - sourceY * rectsPerRow;
                result.Add(new Rectangle(sourceX * rectWidth, sourceY * rectHeight, rectWidth, rectHeight));
            }

            return result;
        }

        public static Dictionary<Direction,Animation> LoadEntityWalkAnimation(Texture2D spriteSheet)
        {
            int frameWidth = spriteSheet.Width / 4;
            int frameHeight = spriteSheet.Height / 4;

            Dictionary<Direction, Animation> walkingAnimation = new Dictionary<Direction,Animation>();
            List<Rectangle> Down = Scripts.GetSourceRectangles(0, 3, frameWidth, frameHeight, spriteSheet);
            Animation animation = new Animation(Down, spriteSheet, 15, true);
            walkingAnimation.Add(Direction.Down, animation);

            List<Rectangle> Left = Scripts.GetSourceRectangles(4, 7, frameWidth, frameHeight, spriteSheet);
            animation = new Animation(Left, spriteSheet, 15, true);
            walkingAnimation.Add(Direction.Left, animation);

            List<Rectangle> Right = Scripts.GetSourceRectangles(8, 11, frameWidth, frameHeight, spriteSheet);
            animation = new Animation(Right, spriteSheet, 15, true);
            walkingAnimation.Add(Direction.Right, animation);

            List<Rectangle> Up = Scripts.GetSourceRectangles(12, 15, frameWidth, frameHeight, spriteSheet);
            animation = new Animation(Up, spriteSheet, 15, true);
            walkingAnimation.Add(Direction.Up, animation);

            return walkingAnimation;
        }

        public static void VoidRemove<T>(this List<T> list, T item)
        {
            list.Remove(item);
        }

        public static Rectangle GetWalkingRect(Vector2 Position,int Width,int Height)
        {
            return new Rectangle((int)Position.X, (int)Position.Y, Width, Height - 24);
        }

        internal static Vector2 GetWalkingOrigin(int EntityWidth, int EntityHeight)
        {
            return new Vector2(EntityWidth / 2, EntityHeight / 2 - Math.Min(TileSet.tileHeight, EntityHeight / 2));
        }
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
        <meta name="description" content="" />
        <meta name="author" content="" />
        <title>Molecule Travel Agency - conorisadesigner</title>

        <link rel="icon" type="image/x-icon" href="assets/img/branding/Favicon-32x32.png" />

        <link rel="preconnect" href="https://fonts.gstatic.com">
        <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;700&display=swap" rel="stylesheet">

        <link href="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css" rel="stylesheet" />

        <link href="css/styles.css" rel="stylesheet" />
        <link href="css/project.css" rel="stylesheet" />

                conorisadesigner
                <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"></button>

Home

CV

web design

molecule travel

project outline

Molecule is a Travel Agency that's currently operating out of a single office. The company wants to move into a more digital space, with the potential of closing the office space if all goes well and working remotely. The company has no online presence and needs a brand to reflect this move.

client name: Molecule

project date: August 2020

category: Web Design

my role

My primary function here is to build them an online brand identity however this will be fleshed out with the design of a website. I won't be building the website for them however my content will be handed over to a developer to implement. I'll also be educating Molecule on what each online channel is best suited for.

the solution

In order to solve these problems for Molecule Travel. I was going to update their Visual Identity with a revised logo design aimed towards their online audience of 18-30 year olds who use them for booking hotel and flight packages. As the company has no online presence I'll be designing a website that will be aimed at allowing customers to book flights and hotels through it whilst informing them on the best deals.

software used:

Adobe Photoshop

 Adobe Illustrator

Adobe After Effects

"I went for an identity that puts the emphasis on finding your perfect holiday can be an exact science"

my design process

How I started this was to break down the needs and purpose of the website. I've partially done this while outlining the solution. From that I could begin to think about the branding and how to target the specific audience. I started by creating the logo, coming up with keywords and phrases that'd be associated with the brand. I went for an identity that puts the emphasis on 'finding your perfect holiday can be an exact science'.

challenges

One of the main challenges was focusing the main call to action on the top of the website. I wasn't sure whether it should be about understanding more about the company or lead straight to a booking as the company doesn't have any online presence whatsoever. However I decided on ensuring people could begin booking a holiday as soon as they arrived onto the website. I added a secondary call to action as an alternative to learn more.

see my other projects

                        henry's honey
                        the winchester silverbacks
                        bark application
                        logofolio vol. 1
                        totaljobs landing page
                        portfolio website
                        html5 banner designs
                        the hungry bunch

conorisadesigner

2021 © Copyright Conor Cresswell. All rights reserved.

Thanks for visiting!


text:
package biz.paluch.logging.gelf.log4j;

import static biz.paluch.logging.gelf.LogMessageField.NamedLogField.*;

import java.util.Collections;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

import biz.paluch.logging.RuntimeContainer;
import biz.paluch.logging.gelf.LogMessageField;
import biz.paluch.logging.gelf.MdcGelfMessageAssembler;
import biz.paluch.logging.gelf.intern.*;

/**
 * Logging-Handler for GELF (Graylog Extended Logging Format). This Java-Util-Logging Handler creates GELF Messages and posts
 * them using UDP (default) or TCP. Following parameters are supported/needed:
 *

 *
host (Mandatory): Hostname/IP-Address of the Logstash Host
 *

 *
(the host) for UDP, e.g. 127.0.0.1 or some.host.com

 *
See docs for more details

 *

 *

 *
port (Optional): Port, default 12201

 *
version (Optional): GELF Version 1.0 or 1.1, default 1.0

 *
originHost (Optional): Originating Hostname, default FQDN Hostname

 *
extractStackTrace (Optional): Post Stack-Trace to StackTrace field (true/false/throwable reference [0 = throwable, 1 =
 * throwable.cause, -1 = root cause]), default false

 *
filterStackTrace (Optional): Perform Stack-Trace filtering (true/false), default false

 *
includeLocation (Optional): Include source code location, default true

 *
mdcProfiling (Optional): Perform Profiling (Call-Duration) based on MDC Data. See MDC
 * Profiling, default false

 *
facility (Optional): Name of the Facility, default gelf-java

 *
threshold (Optional): Log-Level, default INFO

 *
filter (Optional): Class-Name of a Log-Filter, default none

 *
additionalFields(number) (Optional): Post additional fields. Eg.
 * .GelfLogHandler.additionalFields=fieldName=Value,field2=value2

 *
additionalFieldTypes (Optional): Type specification for additional and MDC fields. Supported types: String, long, Long,
 * double, Double and discover (default if not specified, discover field type on parseability). Eg. field=String,field2=double

 *
mdcFields (Optional): Post additional fields, pull Values from MDC. Name of the Fields are comma-separated
 * mdcFields=Application,Version,SomeOtherFieldName

 *
dynamicMdcFields (Optional): Dynamic MDC Fields allows you to extract MDC values based on one or more regular
 * expressions. Multiple regex are comma-separated. The name of the MDC entry is used as GELF field name.

 *
dynamicMdcFieldTypes (Optional): Pattern-based type specification for additional and MDC fields. Key-value pairs are
 * comma-separated. Supported types: String, long, Long, double, Double. Eg. my_field.*=String,business\..*\.field=double

 *
includeFullMdc (Optional): Include all fields from the MDC, default false

 *

 *
MDC Profiling

 *

 * MDC Profiling allows to calculate the runtime from request start up to the time until the log message was generated. You must
 * set one value in the MDC:
 *

 *
profiling.requestStart.millis: Time Millis of the Request-Start (Long or String)

 *

 *

 * Two values are set by the Log Appender:
 *

 *

 *
profiling.requestEnd: End-Time of the Request-End in Date.toString-representation

 *
profiling.requestDuration: Duration of the request (e.g. 205ms, 16sec)

 *

 *
 * The {@link #append(LoggingEvent)} method is thread-safe and may be called by different threads at any time.
 *
 * @author Mark Paluch
 */
public class GelfLogAppender extends AppenderSkeleton implements ErrorReporter {

    protected GelfSender gelfSender;
    protected MdcGelfMessageAssembler gelfMessageAssembler;
    private final ErrorReporter errorReporter = new MessagePostprocessingErrorReporter(this);

    public GelfLogAppender() {
        super();

        RuntimeContainer.initialize(errorReporter);
        gelfMessageAssembler = new MdcGelfMessageAssembler();
        gelfMessageAssembler.addFields(LogMessageField.getDefaultMapping(Time, Severity, ThreadName, SourceClassName,
                SourceMethodName, SourceLineNumber, SourceSimpleClassName, LoggerName, NDC, Server));
    }

    @Override
    protected void append(LoggingEvent event) {

        if (event == null) {
            return;
        }

        try {
            GelfMessage message = createGelfMessage(event);
            if (!message.isValid()) {
                reportError("GELF Message is invalid: " + message.toJson(), null);
                return;
            }

            if (null == gelfSender || !gelfSender.sendMessage(message)) {
                reportError("Could not send GELF message", null);
            }
        } catch (Exception e) {
            reportError("Could not send GELF message: " + e.getMessage(), e);
        }
    }

    protected GelfSender createGelfSender() {
        return GelfSenderFactory.createSender(gelfMessageAssembler, errorReporter, Collections.<String, Object>emptyMap());
    }

    @Override
    public void reportError(String message, Exception exception) {
        errorHandler.error(message, exception, 0);
    }

    @Override
    public boolean requiresLayout() {
        return false;
    }

    @Override
    public void activateOptions() {

        if (null == gelfSender) {
            gelfSender = createGelfSender();
        }
    }

    @Override
    public void close() {
        if (null != gelfSender) {
            Closer.close(gelfSender);
            gelfSender = null;
        }
    }

    protected GelfMessage createGelfMessage(final LoggingEvent loggingEvent) {
        return gelfMessageAssembler.createGelfMessage(new Log4jLogEvent(loggingEvent));
    }

    public void setAdditionalFields(String spec) {
        ConfigurationSupport.setAdditionalFields(spec, gelfMessageAssembler);
    }

    public void setAdditionalFieldTypes(String spec) {
        ConfigurationSupport.setAdditionalFieldTypes(spec, gelfMessageAssembler);
    }

    public void setMdcFields(String spec) {
        ConfigurationSupport.setMdcFields(spec, gelfMessageAssembler);
    }

    public void setDynamicMdcFields(String spec) {
        ConfigurationSupport.setDynamicMdcFields(spec, gelfMessageAssembler);
    }

    public void setDynamicMdcFieldTypes(String spec) {
        ConfigurationSupport.setDynamicMdcFieldTypes(spec, gelfMessageAssembler);
    }

    public String getGraylogHost() {
        return gelfMessageAssembler.getHost();
    }

    public void setGraylogHost(String graylogHost) {
        gelfMessageAssembler.setHost(graylogHost);
    }

    public int getGraylogPort() {
        return gelfMessageAssembler.getPort();
    }

    public void setGraylogPort(int graylogPort) {
        gelfMessageAssembler.setPort(graylogPort);
    }

    public String getHost() {
        return gelfMessageAssembler.getHost();
    }

    public void setHost(String host) {
        gelfMessageAssembler.setHost(host);
    }

    public int getPort() {
        return gelfMessageAssembler.getPort();
    }

    public void setPort(int port) {
        gelfMessageAssembler.setPort(port);
    }

    public String getOriginHost() {
        return gelfMessageAssembler.getOriginHost();
    }

    public void setOriginHost(String originHost) {
        gelfMessageAssembler.setOriginHost(originHost);
    }

    public String getFacility() {
        return gelfMessageAssembler.getFacility();
    }

    public void setFacility(String facility) {
        gelfMessageAssembler.setFacility(facility);
    }

    public String getExtractStackTrace() {
        return gelfMessageAssembler.getExtractStackTrace();
    }

    public void setExtractStackTrace(String extractStacktrace) {
        gelfMessageAssembler.setExtractStackTrace(extractStacktrace);
    }

    public boolean isFilterStackTrace() {
        return gelfMessageAssembler.isFilterStackTrace();
    }

    public void setFilterStackTrace(boolean filterStackTrace) {
        gelfMessageAssembler.setFilterStackTrace(filterStackTrace);
    }

    public boolean isIncludeLocation() {
        return gelfMessageAssembler.isIncludeLocation();
    }

    public void setIncludeLocation(boolean includeLocation) {
        gelfMessageAssembler.setIncludeLocation(includeLocation);
    }

    public boolean isMdcProfiling() {
        return gelfMessageAssembler.isMdcProfiling();
    }

    public void setMdcProfiling(boolean mdcProfiling) {
        gelfMessageAssembler.setMdcProfiling(mdcProfiling);
    }

    public String getTimestampPattern() {
        return gelfMessageAssembler.getTimestampPattern();
    }

    public void setTimestampPattern(String timestampPattern) {
        gelfMessageAssembler.setTimestampPattern(timestampPattern);
    }

    public int getMaximumMessageSize() {
        return gelfMessageAssembler.getMaximumMessageSize();
    }

    public void setMaximumMessageSize(int maximumMessageSize) {
        gelfMessageAssembler.setMaximumMessageSize(maximumMessageSize);
    }

    public boolean isIncludeFullMdc() {
        return gelfMessageAssembler.isIncludeFullMdc();
    }

    public void setIncludeFullMdc(boolean includeFullMdc) {
        gelfMessageAssembler.setIncludeFullMdc(includeFullMdc);
    }

    public String getVersion() {
        return gelfMessageAssembler.getVersion();
    }

    public void setVersion(String version) {
        gelfMessageAssembler.setVersion(version);
    }

}


text:
<?php

namespace Sylius\Bundle\CoreBundle\Form\Type;

use Sylius\Bundle\ChannelBundle\Form\Type\ChannelType as BaseChannelType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Configurable channel form type.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class ChannelType extends BaseChannelType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $builder
            ->add('taxons', 'sylius_taxon_choice', [
                'label' => 'sylius.form.channel.taxons',
                'multiple' => true,
            ])
            ->add('locales', 'sylius_locale_choice', [
                'label' => 'sylius.form.channel.locales',
                'multiple' => true,
            ])
            ->add('defaultLocale', 'sylius_locale_choice', [
                'label' => 'sylius.form.channel.locale_default',
            ])
            ->add('currencies', 'sylius_currency_choice', [
                'label' => 'sylius.form.channel.currencies',
                'multiple' => true,
            ])
            ->add('defaultCurrency', 'sylius_currency_choice', [
                'label' => 'sylius.form.channel.currency_default',
            ])
            ->add('theme', 'sylius_theme_choice', [
                'label' => 'sylius.form.channel.theme',
                'required' => false,
                'empty_data' => null,
            ])
            ->add('shippingMethods', 'sylius_shipping_method_choice', [
                'label' => 'sylius.form.channel.shipping_methods',
                'multiple' => true,
            ])
            ->add('paymentMethods', 'sylius_payment_method_choice', [
                'label' => 'sylius.form.channel.payment_methods',
                'multiple' => true,
            ])
        ;
    }
}


text:
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_carrot_Comment]'))
DROP VIEW [dbo].[vw_carrot_Comment]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[vw_carrot_Comment]
AS

SELECT cc.ContentCommentID, cc.CreateDate, cc.CommenterIP, cc.CommenterName, cc.CommenterEmail, cc.CommenterURL, cc.PostComment, cc.IsApproved, cc.IsSpam,
	c.Root_ContentID, c.SiteID, c.[FileName], c.PageHead, c.TitleBar, c.NavMenuText, c.ContentTypeID, c.IsRetired, c.IsUnReleased, c.RetireDate, c.GoLiveDate
FROM [dbo].carrot_ContentComment AS cc
	INNER JOIN [dbo].vw_carrot_Content AS c on cc.Root_ContentID = c.Root_ContentID
WHERE c.IsLatestVersion = 1

GO

--==============================================================

GO

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_carrot_TrackbackQueue_Root_ContentID]') )
ALTER TABLE [dbo].[carrot_TrackbackQueue] DROP CONSTRAINT [FK_carrot_TrackbackQueue_Root_ContentID]
GO

IF  EXISTS (SELECT * FROM [dbo].sysobjects WHERE id = OBJECT_ID(N'[DF_carrot_TrackbackQueue_TrackbackQueueID]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[carrot_TrackbackQueue] DROP CONSTRAINT [DF_carrot_TrackbackQueue_TrackbackQueueID]
END
GO

IF  EXISTS (SELECT * FROM [dbo].sysobjects WHERE id = OBJECT_ID(N'[DF_carrot_TrackbackQueue_CreateDate]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[carrot_TrackbackQueue] DROP CONSTRAINT [DF_carrot_TrackbackQueue_CreateDate]
END
GO

IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[carrot_TrackbackQueue]') AND type in (N'U')) BEGIN

	CREATE TABLE [dbo].[carrot_TrackbackQueue](
		[TrackbackQueueID] [uniqueidentifier] NOT NULL,
		[Root_ContentID] [uniqueidentifier] NOT NULL,
		[TrackBackURL] [nvarchar](256) NOT NULL,
		[TrackBackResponse] [nvarchar](2048) NULL,
		[ModifiedDate] [datetime] NOT NULL,
		[CreateDate] [datetime] NOT NULL,
		[TrackedBack] [bit] NOT NULL,
	 CONSTRAINT [PK_carrot_TrackbackQueue] PRIMARY KEY NONCLUSTERED
	(
		[TrackbackQueueID] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]

END

GO

ALTER TABLE [dbo].[carrot_TrackbackQueue] ADD  CONSTRAINT [DF_carrot_TrackbackQueue_TrackbackQueueID]  DEFAULT (newid()) FOR [TrackbackQueueID]
GO

ALTER TABLE [dbo].[carrot_TrackbackQueue]  WITH CHECK ADD  CONSTRAINT [FK_carrot_TrackbackQueue_Root_ContentID] FOREIGN KEY([Root_ContentID])
REFERENCES [dbo].[carrot_RootContent] ([Root_ContentID])
GO

ALTER TABLE [dbo].[carrot_TrackbackQueue] CHECK CONSTRAINT [FK_carrot_TrackbackQueue_Root_ContentID]
GO

ALTER TABLE [dbo].[carrot_TrackbackQueue] ADD  CONSTRAINT [DF_carrot_TrackbackQueue_CreateDate]  DEFAULT (getdate()) FOR [CreateDate]
GO

--==============================================================

GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_carrot_TrackbackQueue]'))
DROP VIEW [dbo].[vw_carrot_TrackbackQueue]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[vw_carrot_TrackbackQueue]
AS

SELECT tb.TrackbackQueueID, tb.TrackBackURL, tb.TrackBackResponse, tb.CreateDate, tb.ModifiedDate, tb.TrackedBack, c.Root_ContentID, c.PageActive, c.SiteID
FROM [dbo].carrot_TrackbackQueue AS tb
INNER JOIN [dbo].carrot_RootContent AS c ON tb.Root_ContentID = c.Root_ContentID

GO

--==============================

IF NOT EXISTS( select * from [INFORMATION_SCHEMA].[COLUMNS]
		where table_name = 'carrot_Sites' and column_name = 'SendTrackbacks') BEGIN

	ALTER TABLE [dbo].[carrot_Sites] ADD [SendTrackbacks] [bit] NULL

	ALTER TABLE [dbo].[carrot_Sites] ADD [AcceptTrackbacks] [bit] NULL

END

GO

ALTER TABLE [dbo].[carrot_Sites]
	ALTER COLUMN  [SendTrackbacks] [bit] NULL

ALTER TABLE [dbo].[carrot_Sites]
	ALTER COLUMN  [AcceptTrackbacks] [bit] NULL

GO

UPDATE [dbo].[carrot_Sites]
SET [SendTrackbacks] = 0
WHERE ISNULL([SendTrackbacks], 0) = 0

UPDATE [dbo].[carrot_Sites]
SET [AcceptTrackbacks] = 0
WHERE ISNULL([AcceptTrackbacks], 0) = 0

GO

ALTER TABLE [dbo].[carrot_Sites]
	ALTER COLUMN  [SendTrackbacks] [bit] NOT NULL

ALTER TABLE [dbo].[carrot_Sites]
	ALTER COLUMN  [AcceptTrackbacks] [bit] NOT NULL

GO

--========================================

GO

ALTER VIEW [dbo].[vw_carrot_Content]
AS

select rc.Root_ContentID, rc.SiteID, rc.Heartbeat_UserId, rc.EditHeartbeat, rc.[FileName], rc.PageActive,
		rc.CreateDate, c.ContentID, c.Parent_ContentID, c.IsLatestVersion, c.TitleBar, c.NavMenuText, c.PageHead,
		c.PageText, c.LeftPageText, c.RightPageText, c.NavOrder, c.EditUserId, c.EditDate, c.TemplateFile, c.MetaKeyword, c.MetaDescription,
		ct.ContentTypeID, ct.ContentTypeValue, rc.PageSlug, rc.PageThumbnail, s.TimeZone,
		rc.RetireDate, rc.GoLiveDate, rc.GoLiveDateLocal,
		cast(case when rc.RetireDate < GetUTCDate() then 1 else 0 end as bit) as IsRetired,
		cast(case when rc.GoLiveDate > GetUTCDate() then 1 else 0 end as bit) as IsUnReleased
from [dbo].carrot_RootContent AS rc
inner join [dbo].carrot_Sites AS s ON rc.SiteID = s.SiteID
inner join [dbo].carrot_Content AS c ON rc.Root_ContentID = c.Root_ContentID
inner join [dbo].carrot_ContentType AS ct ON rc.ContentTypeID = ct.ContentTypeID

GO