text:
/* task.c - test microkernel task APIs */

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

/*
DESCRIPTION
This module tests the following task APIs:
    isr_task_id_get(), isr_task_priority_get(), task_id_get(), task_priority_get(),
    task_resume(), task_suspend(), task_priority_set(),
    task_sleep(), task_yield()
 */

#include <tc_util.h>
#include <zephyr.h>
#include <arch/cpu.h>
#include <irq_offload.h>

#include <util_test_common.h>

#define  RT_PRIO         10     /* RegressionTask prio - must match prj.mdef */
#define  HT_PRIO         20     /* HelperTask prio - must match prj.mdef */

#define  SLEEP_TIME SECONDS(1)

#define  CMD_TASKID    0
#define  CMD_PRIORITY  1

typedef struct {
	int  cmd;
	int  data;
} ISR_INFO;

static ISR_INFO   isrInfo;

static int tcRC = TC_PASS;         /* test case return code */
static int helperData;

static volatile int is_main_task_ready = 0;

#ifdef TEST_PRIV_TASKS
/* Note this is in reverse order of what is defined under
 * test_task/prj.mdef. This is due to compiler filling linker
 * section like a stack. This is to preserve the same order
 * in memory as test_task.
 */
DEFINE_TASK(RT_TASKID, 10, RegressionTask, 2048, EXE);
DEFINE_TASK(HT_TASKID, 20, HelperTask, 2048, EXE);
#endif

/**
 *
 * @brief ISR handler to call isr_task_id_get() and isr_task_priority_get()
 *
 * @return N/A
 */

void isr_task_command_handler(void *data)
{
	ISR_INFO   *pInfo = (ISR_INFO *) data;
	int         value = -1;

	switch (pInfo->cmd) {
	case CMD_TASKID:
		value = isr_task_id_get();
		break;

	case CMD_PRIORITY:
		value = isr_task_priority_get();
		break;
	}

	pInfo->data = value;
}

/**
 *
 * @brief Test isr_task_id_get() and isr_task_priority_get
 *
 * @return TC_PASS on success, TC_FAIL on failure
 */

int isrAPIsTest(int taskId, int taskPrio)
{
	isrInfo.cmd = CMD_TASKID;
	irq_offload(isr_task_command_handler, &isrInfo);
	if (isrInfo.data != taskId) {
		TC_ERROR("isr_task_id_get() returned %d, not %d\n",
				 isrInfo.data, taskId);
		return TC_FAIL;
	}

	isrInfo.cmd = CMD_PRIORITY;
	irq_offload(isr_task_command_handler, &isrInfo);
	if (isrInfo.data != taskPrio) {
		TC_ERROR("isr_task_priority_get() returned %d, not %d\n",
				 isrInfo.data, taskPrio);
		return TC_FAIL;
	}

	return TC_PASS;
}

/**
 *
 * @brief Test task_id_get() and task_priority_get() macros
 *
 * @return TC_PASS on success, TC_FAIL on failure
 */

int taskMacrosTest(int taskId, int taskPrio)
{
	int  value;

	value = task_id_get();
	if (value != taskId) {
		TC_ERROR("task_id_get() returned 0x%x, not 0x%x\n",
				 value, taskId);
		return TC_FAIL;
	}

	value = task_priority_get();
	if (value != taskPrio) {
		TC_ERROR("task_priority_get() returned %d, not %d\n",
				 value, taskPrio);
		return TC_FAIL;
	}

	return TC_PASS;
}

/**
 *
 * @brief Helper task portion to test setting the priority
 *
 * @return N/A
 */

void helperTaskSetPrioTest(void)
{
	task_sem_take(HT_SEM, TICKS_UNLIMITED);
	helperData = task_priority_get();     /* Helper task priority lowered by 5 */
	task_sem_give(RT_SEM);

	task_sem_take(HT_SEM, TICKS_UNLIMITED);
	helperData = task_priority_get();     /* Helper task prioirty raised by 10 */
	task_sem_give(RT_SEM);

	task_sem_take(HT_SEM, TICKS_UNLIMITED);
	helperData = task_priority_get();     /* Helper task prioirty restored */
	task_sem_give(RT_SEM);
}

/**
 *
 * @brief Test the task_priority_set() API
 *
 * @return N/A
 */

int taskSetPrioTest(void)
{
	int  rv;

	/* Lower the priority of the current task (RegressionTask) */
	task_priority_set(RT_TASKID, RT_PRIO + 5);
	rv = task_priority_get();
	if (rv != RT_PRIO + 5) {
		TC_ERROR("Expected priority to be changed to %d, not %d\n",
				 RT_PRIO + 5, rv);
		return TC_FAIL;
	}

	/* Raise the priority of the current task (RegressionTask) */
	task_priority_set(RT_TASKID, RT_PRIO - 5);
	rv = task_priority_get();
	if (rv != RT_PRIO - 5) {
		TC_ERROR("Expected priority to be changed to %d, not %d\n",
				 RT_PRIO - 5, rv);
		return TC_FAIL;
	}

	/* Restore the priority of the current task (RegressionTask) */
	task_priority_set(RT_TASKID, RT_PRIO);
	rv = task_priority_get();
	if (rv != RT_PRIO) {
		TC_ERROR("Expected priority to be changed to %d, not %d\n",
				 RT_PRIO, rv);
		return TC_FAIL;
	}

	/* Lower the priority of the helper task (HelperTask) */
	task_priority_set(HT_TASKID, HT_PRIO + 5);
	task_sem_give(HT_SEM);
	task_sem_take(RT_SEM, TICKS_UNLIMITED);
	if (helperData != HT_PRIO + 5) {
		TC_ERROR("Expected priority to be changed to %d, not %d\n",
				 HT_PRIO + 5, helperData);
		return TC_FAIL;
	}

	/* Raise the priority of the helper task (HelperTask) */
	task_priority_set(HT_TASKID, HT_PRIO - 5);
	task_sem_give(HT_SEM);
	task_sem_take(RT_SEM, TICKS_UNLIMITED);
	if (helperData != HT_PRIO - 5) {
		TC_ERROR("Expected priority to be changed to %d, not %d\n",
				 HT_PRIO - 5, helperData);
		return TC_FAIL;
	}

	/* Restore the priority of the helper task (HelperTask) */
	task_priority_set(HT_TASKID, HT_PRIO);
	task_sem_give(HT_SEM);
	task_sem_take(RT_SEM, TICKS_UNLIMITED);
	if (helperData != HT_PRIO) {
		TC_ERROR("Expected priority to be changed to %d, not %d\n",
				 HT_PRIO, helperData);
		return TC_FAIL;
	}

	return TC_PASS;
}

/**
 *
 * @brief Helper task portion to test task_sleep()
 *
 * @return N/A
 */

void helperTaskSleepTest(void)
{
	int32_t  firstTick;

	task_sem_take(HT_SEM, TICKS_UNLIMITED);

	firstTick = sys_tick_get_32();
	while (!is_main_task_ready) {
		/* busy work */
	}
	helperData = sys_tick_get_32() - firstTick;

	task_sem_give(RT_SEM);
}

/**
 *
 * @brief Test task_sleep()
 *
 * @return TC_PASS on success, TC_FAIL on failure
 */

int taskSleepTest(void)
{
	int32_t  tick;

	task_sem_give(HT_SEM);

	/* align on tick boundary and get current tick */
	tick = sys_tick_get_32();
	while (tick == sys_tick_get_32()) {
	}

	/* compensate for the extra tick we just waited */
	++tick;

	task_sleep(SLEEP_TIME);

	tick = sys_tick_get_32() - tick;

	is_main_task_ready = 1;
	task_sem_take(RT_SEM, TICKS_UNLIMITED);

	/*
	 * By design this should be exact, but at least one cycle of
	 * slop is required experimentally on Qemu.
	 */
	if (tick < SLEEP_TIME || tick > SLEEP_TIME + 1) {
		TC_ERROR("task_sleep() slept for %d ticks, not %d\n", tick, SLEEP_TIME);
		return TC_FAIL;
	}

	/*
	 * Similarly check that the helper task ran for approximately
	 * SLEEP_TIME. On QEMU, when the host CPU is overloaded, it
	 * has been observed that the tick count can be missed by 1 on
	 * either side. Allow for 2 ticks to be sure.  This check is
	 * only there to make sure that the helper task did run for
	 * approximately the whole time the main task was sleeping.
	 */
	const int tick_error_allowed = 2;
	if (helperData > SLEEP_TIME + tick_error_allowed ||
		helperData < SLEEP_TIME - tick_error_allowed) {
		TC_ERROR("helper task should have run for around %d ticks "
				 "(+/-%d), but ran for %d ticks\n",
					SLEEP_TIME, tick_error_allowed, helperData);
		return TC_FAIL;
	}

	return TC_PASS;
}

/**
 *
 * @brief Helper task portion of task_yield() test
 *
 * @return N/A
 */

void helperTaskYieldTest(void)
{
	int  i;
	task_sem_take(HT_SEM, TICKS_UNLIMITED);

	for (i = 0; i < 5; i++) {
		helperData++;
		task_yield();
	}

	task_sem_give(RT_SEM);
}

/**
 *
 * @brief Test task_yield()
 *
 * @return TC_PASS on success, TC_FAIL on failure
 */

int taskYieldTest(void)
{
	int  prevHelperData;
	int  i;

	helperData = 0;

	/* 1st raise the priority of the helper task */
	task_priority_set(HT_TASKID, RT_PRIO);
	task_sem_give(HT_SEM);

	for (i = 0; i < 5; i++) {
		prevHelperData = helperData;
		task_yield();

		if (helperData == prevHelperData) {
			TC_ERROR("Iter %d.  helperData did not change (%d)\n",
					 i + 1, helperData);
			return TC_FAIL;
		}
	}

	/* Restore helper task priority */
	task_priority_set(HT_TASKID, HT_PRIO);

	/* Ensure that the helper task finishes */
	task_sem_take(RT_SEM, TICKS_UNLIMITED);

	return TC_PASS;
}

/**
 *
 * @brief Helper task portion of task_suspend() and
 *                         task_resume() tests
 *
 * @return N/A
 */

void helperTaskSuspendTest(void)
{
	helperData++;

	task_sem_take(HT_SEM, TICKS_UNLIMITED);
}

/**
 *
 * @brief Test task_suspend() and task_resume()
 *
 * This test suspends the helper task.  Once it is suspended, the main task
 * (RegressionTask) sleeps for one second.  If the helper task is truly
 * suspended, it will not execute and modify <helperData>.  Once confirmed,
 * the helper task is resumed, and the main task sleeps once more.  If the
 * helper task has truly resumed, it will modify <helperData>.
 *
 * @return TC_PASS on success or TC_FAIL on failure
 */

int taskSuspendTest(void)
{
	int  prevHelperData;

	task_suspend(HT_TASKID);    /* Suspend the helper task */

	prevHelperData = helperData;
	task_sleep(SLEEP_TIME);

	if (prevHelperData != helperData) {
		TC_ERROR("Helper task did not suspend!\n");
		return TC_FAIL;
	}

	task_resume(HT_TASKID);
	task_sleep(SLEEP_TIME);

	if (prevHelperData == helperData) {
		TC_ERROR("Helper task did not resume!\n");
		return TC_FAIL;
	}

	task_sem_give(HT_SEM);
	return TC_PASS;
}

/**
 *
 * @brief Helper task to test the task APIs
 *
 * @return  N/A
 */

void HelperTask(void)
{
	int  rv;

	task_sem_take(HT_SEM, TICKS_UNLIMITED);
	rv = isrAPIsTest(HT_TASKID, HT_PRIO);
	if (rv != TC_PASS) {
		tcRC = TC_FAIL;
		return;
	}
	task_sem_give(RT_SEM);

	task_sem_take(HT_SEM, TICKS_UNLIMITED);
	rv = taskMacrosTest(HT_TASKID, HT_PRIO);
	if (rv != TC_PASS) {
		tcRC = TC_FAIL;
		return;
	}
	task_sem_give(RT_SEM);

	helperTaskSetPrioTest();

	helperTaskSleepTest();

	helperTaskYieldTest();

	helperTaskSuspendTest();
}

/**
 *
 * @brief Main task to test the task APIs
 *
 * @return  N/A
 */

void RegressionTask(void)
{
	int    rv;

	TC_START("Test Microkernel Task API");

	PRINT_LINE;

	task_start(HT_TASKID);

	TC_PRINT("Testing isr_task_id_get() and isr_task_priority_get()\n");
	rv = isrAPIsTest(RT_TASKID, RT_PRIO);
	if (rv != TC_PASS) {
		tcRC = TC_FAIL;
		goto errorReturn;
	}

	task_sem_give(HT_SEM);
	task_sem_take(RT_SEM, TICKS_UNLIMITED);

	TC_PRINT("Testing task_id_get() and task_priority_get()\n");
	rv = taskMacrosTest(RT_TASKID, RT_PRIO);
	if (rv != TC_PASS) {
		tcRC = TC_FAIL;
		goto errorReturn;
	}

	task_sem_give(HT_SEM);
	task_sem_take(RT_SEM, TICKS_UNLIMITED);

	TC_PRINT("Testing task_priority_set()\n");
	if (taskSetPrioTest() != TC_PASS) {
		tcRC = TC_FAIL;
		goto errorReturn;
	}

	TC_PRINT("Testing task_sleep()\n");
	if (taskSleepTest() != TC_PASS) {
		tcRC = TC_FAIL;
		goto errorReturn;
	}

	TC_PRINT("Testing task_yield()\n");
	if (taskYieldTest() != TC_PASS) {
		tcRC = TC_FAIL;
		goto errorReturn;
	}

	TC_PRINT("Testing task_suspend() and task_resume()\n");
	if (taskSuspendTest() != TC_PASS) {
		tcRC = TC_FAIL;
		goto errorReturn;
	}

errorReturn:
	TC_END_RESULT(tcRC);
	TC_END_REPORT(tcRC);
}  /* RegressionTask */


text:
package org.unitime.timetable.util;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.Map;

import org.unitime.localization.impl.Localization;
import org.unitime.timetable.gwt.resources.GwtConstants;
import org.unitime.timetable.gwt.resources.StudentSectioningConstants;

/**
 * To prevent concurrency issues (see bug JDK-6609686, http://bugs.sun.com/view_bug.do?bug_id=4264153) and to
 * promote localization, all date and number formating needs should be routed through this class.
 *
 * @author Tomas Muller
 */
public class Formats {
	private static StudentSectioningConstants SCT_CONSTANTS = Localization.create(StudentSectioningConstants.class);
	private static GwtConstants GWT_CONSTANTS = Localization.create(GwtConstants.class);

	private static final ThreadLocal<FormatBundle> sBundle = new ThreadLocal<FormatBundle>() {
		 @Override
		 protected FormatBundle initialValue() {
            return new FormatBundle();
		 }
	};

	public enum Pattern implements Serializable {
		DATE_EXAM_PERIOD(new PatternHolder() {
			public String getPattern() { return GWT_CONSTANTS.examPeriodDateFormat(); }
		}),
		DATE_EVENT(new PatternHolder() {
			public String getPattern() { return GWT_CONSTANTS.eventDateFormat(); }
		}),
		DATE_EVENT_SHORT(new PatternHolder() {
			public String getPattern() { return GWT_CONSTANTS.eventDateFormatShort(); }
		}),
		DATE_EVENT_LONG(new PatternHolder() {
			public String getPattern() { return GWT_CONSTANTS.eventDateFormatLong(); }
		}),
		DATE_TIME_STAMP(new PatternHolder() {
			public String getPattern() { return GWT_CONSTANTS.timeStampFormat(); }
		}),
		DATE_TIME_STAMP_SHORT(new PatternHolder() {
			public String getPattern() { return GWT_CONSTANTS.timeStampFormatShort(); }
		}),
		DATE_REQUEST(new PatternHolder() {
			public String getPattern() { return SCT_CONSTANTS.requestDateFormat(); }
		}),
		DATE_PATTERN(new PatternHolder() {
			public String getPattern() { return SCT_CONSTANTS.patternDateFormat(); }
		}),
		DATE_DAY_OF_WEEK(new PatternHolder() {
			public String getPattern() { return "EEE"; }
		}),
		DATE_MEETING(new PatternHolder() {
			public String getPattern() { return GWT_CONSTANTS.meetingDateFormat(); }
		}),
		DATE_SHORT(new PatternHolder() {
			public String getPattern() { return GWT_CONSTANTS.dateFormatShort(); }
		}),
		TIME_SHORT(new PatternHolder() {
			public String getPattern() { return GWT_CONSTANTS.timeFormatShort(); }
		}),
		SESSION_DATE(new PatternHolder() {
			public String getPattern() { return GWT_CONSTANTS.sessionDateFormat(); }
		}),
		DATE_ENTRY_FORMAT(new PatternHolder() {
			public String getPattern() { return GWT_CONSTANTS.dateEntryFormat(); }
		}),
		FILTER_DATE(new PatternHolder() {
			public String getPattern() { return GWT_CONSTANTS.filterDateFormat(); }
		}),
		;

		private PatternHolder iHolder;
		Pattern(PatternHolder holder) { iHolder = holder; }
		public String toPattern() { return iHolder.getPattern(); }
		protected PatternHolder holder() { return iHolder; }
	}

	public static void removeFormats() {
		sBundle.remove();
	}

	public static FormatBundle getFormats() {
		return sBundle.get();
	}

	/**
	 * Use this to create a new instance that can be accessed through multiple threads.
	 * For static reference use {@link Formats#getDateFormat(Pattern)}.
	 */
	public static Format<Date> getDateFormat(final String pattern) {
		return new Format<Date>() {
			private static final long serialVersionUID = 1L;

			@Override
			public String format(Date t) {
				return getFormats().getDateFormat(pattern).format(t);
			}

			@Override
			public Date parse(String source) throws ParseException {
				return getFormats().getDateFormat(pattern).parse(source);
			}

			@Override
			public String toPattern() {
				return pattern;
			}

			@Override
			public boolean isValid(String source) {
				try {
					return parse(source) != null;
				} catch (Throwable t) {
					return false;
				}
			}
		};
	}

	/**
	 * Use this to create a new instance that can be accessed through multiple threads.
	 * For static reference use {@link Formats#getDateFormat(Pattern)}.
	 */
	public static Format<Number> getNumberFormat(final String pattern) {
		return new Format<Number>() {
			private static final long serialVersionUID = 1L;

			@Override
			public String format(Number t) {
				return getFormats().getNumberFormat(pattern).format(t);
			}

			@Override
			public Number parse(String source) throws ParseException {
				return getFormats().getNumberFormat(pattern).parse(source);
			}

			@Override
			public String toPattern() {
				return pattern;
			}

			@Override
			public boolean isValid(String source) {
				try {
					return parse(source) != null;
				} catch (Throwable t) {
					return false;
				}
			}
		};
	}

	/**
	 * Use this to create a new instance that can be accessed through multiple threads.
	 * For static reference use {@link Formats#getDateFormat(Pattern)}.
	 */
	public static Format<Date> getDateFormat(final Pattern pattern) {
		return new Format<Date>() {
			private static final long serialVersionUID = 1L;

			@Override
			public String format(Date t) {
				return getFormats().getDateFormat(pattern).format(t);
			}

			@Override
			public Date parse(String source) throws ParseException {
				return getFormats().getDateFormat(pattern).parse(source);
			}

			@Override
			public String toPattern() {
				return pattern.toPattern();
			}

			@Override
			public boolean isValid(String source) {
				try {
					return parse(source) != null;
				} catch (Throwable t) {
					return false;
				}
			}
		};
	}

	/**
	 * Use this to create a new instance that can be accessed through multiple threads.
	 * For static reference use {@link Formats#getDateFormat(Pattern)}.
	 */
	public static Format<Number> getConcurrentNumberFormat(final Pattern pattern) {
		return new Format<Number>() {
			private static final long serialVersionUID = 1L;

			@Override
			public String format(Number t) {
				return getFormats().getNumberFormat(pattern).format(t);
			}

			@Override
			public Number parse(String source) throws ParseException {
				return getFormats().getNumberFormat(pattern).parse(source);
			}

			@Override
			public String toPattern() {
				return pattern.toPattern();
			}

			@Override
			public boolean isValid(String source) {
				try {
					return parse(source) != null;
				} catch (Throwable t) {
					return false;
				}
			}
		};
	}

	public static class FormatBundle {
		private Map<String, DateFormat> iDateFormats = new Hashtable<String, DateFormat>();
		private Map<String, NumberFormat> iNumberFormats = new Hashtable<String, NumberFormat>();

		private FormatBundle() {
		}

		public DateFormat getDateFormat(String pattern) {
			DateFormat df = iDateFormats.get(pattern);
			if (df == null) {
				df = new SimpleDateFormat(pattern, Localization.getJavaLocale());
				iDateFormats.put(pattern, df);
			}
			return df;
		}

		public DateFormat getDateFormat(Pattern pattern) {
			return getDateFormat(pattern.toPattern());
		}

		public NumberFormat getNumberFormat(String pattern) {
			NumberFormat nf = iNumberFormats.get(pattern);
			if (nf == null) {
				nf = new DecimalFormat(pattern, new DecimalFormatSymbols(Localization.getJavaLocale()));
				iNumberFormats.put(pattern, nf);
			}
			return nf;
		}

		public NumberFormat getNumberFormat(Pattern pattern) {
			return getNumberFormat(pattern.toPattern());
		}
	}

	public static interface Format<T> extends Serializable {
		public String format(T t);
		public T parse(String source) throws ParseException;
		public String toPattern();
		public boolean isValid(String source);
	}

	protected interface PatternHolder {
		String getPattern();
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <!--
    <parameters>
        <parameter key="ck_users.example.class">ck\UsersBundle\Example</parameter>
    </parameters>

    <services>
        <service id="ck_users.example" class="%ck_users.example.class%">
            <argument type="service" id="service_id" />
            <argument>plain_value</argument>
            <argument>%parameter_name%</argument>
        </service>
    </services>
    -->
</container>


text:
<?php
require_once "config/settings.php";

# confidentialsettings.php includes any settings that are not
# appropriate to store on GitHub
if (file_exists("config/confidentialsettings.php"))
  include "config/confidentialsettings.php";

# Comment out or remove this line in production enviroments to supress
# error messages being displayed to the user
define("_DEBUG_",true);

# location of the password file
# define("_PASSWD_","core/adm/blank_acc.json"); # Usernames and passwords

# If on shared hosting $allowedHost can be used to ensure that
# skymo can only be accessed from the correct URL eg setting
# $allowedHost = subdomain.mydomain.com
# prevents access from mydomain.com/subdomain
# $allowedHost = skymo.example.com
?>


text:
package org.kie.workbench.common.dmn.webapp.common.client.docks.preview;

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

import org.gwtbootstrap3.client.ui.constants.IconType;
import org.jboss.errai.ui.client.local.spi.TranslationService;
import org.kie.workbench.common.dmn.client.docks.preview.PreviewDiagramScreen;
import org.kie.workbench.common.dmn.client.resources.i18n.DMNEditorConstants;
import org.kie.workbench.common.stunner.kogito.api.docks.DiagramEditorDock;
import org.uberfire.client.workbench.docks.UberfireDock;
import org.uberfire.client.workbench.docks.UberfireDockPosition;
import org.uberfire.client.workbench.docks.UberfireDocks;
import org.uberfire.mvp.impl.DefaultPlaceRequest;

@ApplicationScoped
public class PreviewDiagramDock implements DiagramEditorDock {

    protected static final double DOCK_SIZE = 400d;

    protected UberfireDocks uberfireDocks;

    protected TranslationService translationService;

    protected UberfireDock uberfireDock;

    protected boolean isOpened = false;

    protected String owningPerspectiveId;

    public PreviewDiagramDock() {
        // CDI proxy
    }

    @Inject
    public PreviewDiagramDock(final UberfireDocks uberfireDocks,
                              final TranslationService translationService) {
        this.uberfireDocks = uberfireDocks;
        this.translationService = translationService;
    }

    @Override
    public void init(final String owningPerspectiveId) {
        this.owningPerspectiveId = owningPerspectiveId;
        this.uberfireDock = makeUberfireDock();
    }

    @Override
    public void destroy() {
        uberfireDocks.remove(getUberfireDock());
    }

    @Override
    public void open() {
        if (isOpened()) {
            return;
        }

        isOpened = true;
        uberfireDocks.add(getUberfireDock());
        uberfireDocks.show(position(), owningPerspectiveId());
        uberfireDocks.open(getUberfireDock());
    }

    @Override
    public void close() {
        if (!isOpened()) {
            return;
        }

        isOpened = false;
        uberfireDocks.close(getUberfireDock());
        destroy();
    }

    protected boolean isOpened() {
        return isOpened;
    }

    protected UberfireDock makeUberfireDock() {
        final UberfireDock uberfireDock = new UberfireDock(position(), icon(), placeRequest(), owningPerspectiveId());
        return uberfireDock.withSize(DOCK_SIZE).withLabel(dockLabel());
    }

    protected UberfireDockPosition position() {
        return UberfireDockPosition.EAST;
    }

    protected String icon() {
        return IconType.EYE.toString();
    }

    protected DefaultPlaceRequest placeRequest() {
        return new DefaultPlaceRequest(PreviewDiagramScreen.SCREEN_ID);
    }

    protected String owningPerspectiveId() {
        return owningPerspectiveId;
    }

    protected UberfireDock getUberfireDock() {
        return uberfireDock;
    }

    protected String dockLabel() {
        return translationService.getTranslation(DMNEditorConstants.DMNPreviewDiagramDock_Title);
    }
}


text:
<?php

return new class
{
    public $proxyClass;
    private $privates = [];

    public function getFooService($lazyLoad = true)
    {
        if ($lazyLoad) {
            return $this->privates['foo'] = $this->createProxy('SunnyInterface_1eff735', function () {
                return \SunnyInterface_1eff735::staticProxyConstructor(function (&$wrappedInstance, \ProxyManager\Proxy\LazyLoadingInterface $proxy) {
                    $wrappedInstance = $this->getFooService(false);

                    $proxy->setProxyInitializer(null);

                    return true;
                });
            });
        }

        return new Symfony\Bridge\ProxyManager\Tests\LazyProxy\PhpDumper\DummyClass();
    }

    protected function createProxy($class, \Closure $factory)
    {
        $this->proxyClass = $class;

        return $factory();
    }
};


text:
#ifndef TENSORFLOW_CORE_PLATFORM_TRACING_H_
#define TENSORFLOW_CORE_PLATFORM_TRACING_H_

// Tracing interface

#include <array>

#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/platform.h"
#include "tensorflow/core/platform/stringpiece.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {
namespace tracing {

// This enumeration contains the identifiers of all TensorFlow CPU profiler
// events. It must be kept in sync with the code in GetEventCategoryName().
enum struct EventCategory : unsigned {
  kScheduleClosure = 0,
  kRunClosure = 1,
  kCompute = 2,
  kNumCategories = 3  // sentinel - keep last
};
constexpr unsigned GetNumEventCategories() {
  return static_cast<unsigned>(EventCategory::kNumCategories);
}
const char* GetEventCategoryName(EventCategory);

// Interface for CPU profiler events.
class EventCollector {
 public:
  virtual ~EventCollector() {}
  virtual void RecordEvent(uint64 arg) const = 0;
  virtual void StartRegion(uint64 arg) const = 0;
  virtual void StopRegion() const = 0;

  // Annotates the current thread with a name.
  static void SetCurrentThreadName(const char* name);
  // Returns whether event collection is enabled.
  static bool IsEnabled();

 private:
  friend void SetEventCollector(EventCategory, const EventCollector*);
  friend const EventCollector* GetEventCollector(EventCategory);

  static std::array<const EventCollector*, GetNumEventCategories()> instances_;
};
// Set the callback for RecordEvent and ScopedRegion of category.
// Not thread safe. Only call while EventCollector::IsEnabled returns false.
void SetEventCollector(EventCategory category, const EventCollector* collector);

// Returns the callback for RecordEvent and ScopedRegion of category if
// EventCollector::IsEnabled(), otherwise returns null.
inline const EventCollector* GetEventCollector(EventCategory category) {
  if (EventCollector::IsEnabled()) {
    return EventCollector::instances_[static_cast<unsigned>(category)];
  }
  return nullptr;
}

// Returns a unique id to pass to RecordEvent/ScopedRegion. Never returns zero.
uint64 GetUniqueArg();

// Returns an id for name to pass to RecordEvent/ScopedRegion.
uint64 GetArgForName(StringPiece name);

// Records an atomic event through the currently registered EventCollector.
inline void RecordEvent(EventCategory category, uint64 arg) {
  if (auto collector = GetEventCollector(category)) {
    collector->RecordEvent(arg);
  }
}

// Records an event for the duration of the instance lifetime through the
// currently registered EventCollector.
class ScopedRegion {
 public:
  ScopedRegion(ScopedRegion&& other) noexcept  // Move-constructible.
      : collector_(other.collector_) {
    other.collector_ = nullptr;
  }

  ScopedRegion(EventCategory category, uint64 arg)
      : collector_(GetEventCollector(category)) {
    if (collector_) {
      collector_->StartRegion(arg);
    }
  }

  // Same as ScopedRegion(category, GetUniqueArg()), but faster if
  // EventCollector::IsEnabled() returns false.
  explicit ScopedRegion(EventCategory category)
      : collector_(GetEventCollector(category)) {
    if (collector_) {
      collector_->StartRegion(GetUniqueArg());
    }
  }

  // Same as ScopedRegion(category, GetArgForName(name)), but faster if
  // EventCollector::IsEnabled() returns false.
  ScopedRegion(EventCategory category, StringPiece name)
      : collector_(GetEventCollector(category)) {
    if (collector_) {
      collector_->StartRegion(GetArgForName(name));
    }
  }

  ~ScopedRegion() {
    if (collector_) {
      collector_->StopRegion();
    }
  }

  bool IsEnabled() const { return collector_ != nullptr; }

 private:
  TF_DISALLOW_COPY_AND_ASSIGN(ScopedRegion);

  const EventCollector* collector_;
};

// Return the pathname of the directory where we are writing log files.
const char* GetLogDir();

}  // namespace tracing
}  // namespace tensorflow

#if defined(PLATFORM_GOOGLE)
#include "tensorflow/core/platform/google/tracing_impl.h"
#else
#include "tensorflow/core/platform/default/tracing_impl.h"
#endif

#endif  // TENSORFLOW_CORE_PLATFORM_TRACING_H_


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Package edu.brown.cs.systems.tracingplane.baggage_buffers</title>
<meta name="date" content="2016-12-22">
<link rel="stylesheet" type="text/css" href="../../../../../../javadoc-stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
edu.brown.cs.systems.tracingplane.baggage_buffers

Packages that use edu.brown.cs.systems.tracingplane.baggage_buffers

Package
Description

edu.brown.cs.systems.tracingplane.baggage_buffers

Classes in edu.brown.cs.systems.tracingplane.baggage_buffers used by edu.brown.cs.systems.tracingplane.baggage_buffers

Class and Description

BaggageBuffersConfig

BaggageBuffersContents

 BaggageContents that supports multiple applications using baggage simultaneously.

Registrations

Global registration of baggage handlers to keys.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
using System;
using System.Reflection;

namespace Homeinns.Common.UI.Common
{
    public class ControlDictInfo
    {
        protected ControlGroupEnum _controlGroup;
        protected Type _controlType;
        protected string _controlTypeName;
        protected string _prefix;
        protected PropertyInfo _propertyInfo;
        protected string _propertyName;
        //protected Type _propertyUnderlyingType;

        public ControlDictInfo(ControlGroupEnum controlGroupEnum, string prefix, Type controlType, string propertyName)
        {
            _controlGroup = controlGroupEnum;
            _prefix = prefix;
            _controlTypeName = controlType.FullName;
            _controlType = controlType;
            _propertyName = propertyName;
            if (_propertyName != null)
            {
                _propertyInfo = _controlType.GetProperty(_propertyName);
                //this._propertyUnderlyingType = this._propertyInfo.PropertyType;
            }
        }

        public string Prefix
        {
            get { return _prefix; }
            set { _prefix = value; }
        }

        public string ControlTypeName
        {
            get { return _controlTypeName; }
            set { _controlTypeName = value; }
        }

        public Type ControlType
        {
            get { return _controlType; }
            set { _controlType = value; }
        }

        public string PropertyName
        {
            get { return _propertyName; }
            set { _propertyName = value; }
        }

        public PropertyInfo PropertyInfo
        {
            get { return _propertyInfo; }
            set { _propertyInfo = value; }
        }

        //public Type PropertyUnderlyingType
        //{
        //    get { return this._propertyUnderlyingType; }
        //    set { this._propertyUnderlyingType = value; }
        //}

        public ControlGroupEnum ControlGroup
        {
            get { return _controlGroup; }
            set { _controlGroup = value; }
        }
    }

    /// <summary>
    /// 控件分组
    /// </summary>
    public enum ControlGroupEnum
    {
        DataGroup = 1,
        ValidateGroup = 2,
        ContainerGroup = 3
    }
}


text:
import expect from 'expect.js';
import {validate, bool} from '../src/validate';

describe('Functions Boolean', () => {
    describe('#isTrue(value)', () => {
        it('should be true when value is true', () => {
            let result = validate(bool.isTrue);
            expect(result(true)).to.be.ok();
        });

        it('should be false when value is false', () => {
            let result = validate(bool.isTrue);
            expect(result(false)).to.not.be.ok();
        });

        it('should be false when value is null', () => {
            let result = validate(bool.isTrue);
            expect(result(null)).to.not.be.ok();
        });

        it('should be false when value is undefined', () => {
            let result = validate(bool.isTrue);
            expect(result(undefined)).to.not.be.ok();
        });
    });

    describe('#isFalse(value)', () => {
        it('should be false when value is true', () => {
            let result = validate(bool.isFalse);
            expect(result(true)).to.not.be.ok();
        });

        it('should be true when value is false', () => {
            let result = validate(bool.isFalse);
            expect(result(false)).to.be.ok();
        });

        it('should be false when value is null', () => {
            let result = validate(bool.isFalse);
            expect(result(null)).to.not.be.ok();
        });

        it('should be false when value is undefined', () => {
            let result = validate(bool.isFalse);
            expect(result(undefined)).to.not.be.ok();
        });
    });
});


text:
var es = require('elasticsearch');
var Promise = require('bluebird');

// current client
var client = null;

module.exports = {
  create: function create(port) {
    doCreateClient({ logConfig: null });
    var attemptsRemaining = 60;
    var timeout = 500;

    return (function ping() {
      return client.info({
        maxRetries: 0
      })
      .then(
        function (resp) {
          if (resp.name !== 'esjs-shield-test-runner') {
            throw new Error('Almosted wiped out another es node. Shut-down all instances of ES and try again.');
          }

          // create a new client
          doCreateClient();
          return client;
        },
        function (err) {
          if (err && --attemptsRemaining) {
            return Promise.delay(timeout).then(ping);
          }

          throw new Error('unable to establish contact with ES at ' + JSON.stringify({
            host: 'localhost',
            port: port,
            err: err
          }));
        }
      );
    }());

    function doCreateClient() {
      // close existing client
      if (client) client.close();

      client = new es.Client({
        hosts: [
          {
            host: 'localhost',
            port: 9200
          }
        ],
        plugins: [ require('../') ],
        pingTimeout: 5000,
        log: false
      });

      client.clearEs = function () {
        return Promise.all([
          client.indices.delete({ index: '*', ignore: 404 }),
          client.indices.deleteTemplate({ name: '*', ignore: 404 })
        ]);
      };
    }
  },

  get: function () {
    return client;
  }
};


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>test::basic_stream::~basic_stream</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.Beast">
<link rel="up" href="../boost__beast__test__basic_stream.html" title="test::basic_stream">
<link rel="prev" href="buffer_type.html" title="test::basic_stream::buffer_type">
<link rel="next" href="basic_stream.html" title="test::basic_stream::basic_stream">

Home
Libraries
People
FAQ
More

test::basic_stream::~basic_stream

          Destructor.

          Synopsis

~basic_stream();

          Description

          If an asynchronous read operation is pending, it will simply be discarded
          with no notification to the completion handler. If a connection is established
          while the stream is destroyed, the peer will see the error net::error::connection_reset when performing any
          reads or writes.

Copyright © 2016-2019 Vinnie
      Falco

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
#include <aws/ssm/model/DocumentMetadataResponseInfo.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SSM
{
namespace Model
{

DocumentMetadataResponseInfo::DocumentMetadataResponseInfo() :
    m_reviewerResponseHasBeenSet(false)
{
}

DocumentMetadataResponseInfo::DocumentMetadataResponseInfo(JsonView jsonValue) :
    m_reviewerResponseHasBeenSet(false)
{
  *this = jsonValue;
}

DocumentMetadataResponseInfo& DocumentMetadataResponseInfo::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("ReviewerResponse"))
  {
    Aws::Utils::Array<JsonView> reviewerResponseJsonList = jsonValue.GetArray("ReviewerResponse");
    for(unsigned reviewerResponseIndex = 0; reviewerResponseIndex < reviewerResponseJsonList.GetLength(); ++reviewerResponseIndex)
    {
      m_reviewerResponse.push_back(reviewerResponseJsonList[reviewerResponseIndex].AsObject());
    }
    m_reviewerResponseHasBeenSet = true;
  }

  return *this;
}

JsonValue DocumentMetadataResponseInfo::Jsonize() const
{
  JsonValue payload;

  if(m_reviewerResponseHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> reviewerResponseJsonList(m_reviewerResponse.size());
   for(unsigned reviewerResponseIndex = 0; reviewerResponseIndex < reviewerResponseJsonList.GetLength(); ++reviewerResponseIndex)
   {
     reviewerResponseJsonList[reviewerResponseIndex].AsObject(m_reviewerResponse[reviewerResponseIndex].Jsonize());
   }
   payload.WithArray("ReviewerResponse", std::move(reviewerResponseJsonList));

  }

  return payload;
}

} // namespace Model
} // namespace SSM
} // namespace Aws


text:
<?php

require_once dirname(__FILE__) . '/../../../../../modules/cinema/models/Ratings.php';

/**
 * Test class for Ratings.
 * Generated by PHPUnit on 2011-12-13 at 19:56:35.
 */
class RatingsTest extends PHPUnit_Framework_TestCase {

	/**
	 * @var Ratings
	 */
	protected $object;

	/**
	 * Sets up the fixture, for example, opens a network connection.
	 * This method is called before a test is executed.
	 */
	protected function setUp() {
		$this->object = new Ratings;
	}

	/**
	 * Tears down the fixture, for example, closes a network connection.
	 * This method is called after a test is executed.
	 */
	protected function tearDown() {

	}

	/**
	 * @covers {className}::{origMethodName}
	 * @todo Implement testModel().
	 */
	public function testModel() {
		// Remove the following lines when you implement this test.
		$this->markTestIncomplete(
				'This test has not been implemented yet.'
		);
	}

	/**
	 * @covers {className}::{origMethodName}
	 * @todo Implement testTableName().
	 */
	public function testTableName() {
		// Remove the following lines when you implement this test.
		$this->markTestIncomplete(
				'This test has not been implemented yet.'
		);
	}

	/**
	 * @covers {className}::{origMethodName}
	 * @todo Implement testRules().
	 */
	public function testRules() {
		// Remove the following lines when you implement this test.
		$this->markTestIncomplete(
				'This test has not been implemented yet.'
		);
	}

	/**
	 * @covers {className}::{origMethodName}
	 * @todo Implement testRelations().
	 */
	public function testRelations() {
		// Remove the following lines when you implement this test.
		$this->markTestIncomplete(
				'This test has not been implemented yet.'
		);
	}

	/**
	 * @covers {className}::{origMethodName}
	 * @todo Implement testAttributeLabels().
	 */
	public function testAttributeLabels() {
		// Remove the following lines when you implement this test.
		$this->markTestIncomplete(
				'This test has not been implemented yet.'
		);
	}

	public function testGetAllRatings() {
		// Checks to ensure that the array which is returned contains values
		$this->assertNotEmpty($this->object->getAllRatings());
	}

	public function testSearch() {
		// Checks to ensure that the correct object is being returned from the
		// search function
		$this->assertInstanceOf(
			'CActiveDataProvider',
			$this->object->search()
		);
	}

}
?>


text:
package io.machinecode.chainlink.core.jsl.fluent.task;

import io.machinecode.chainlink.core.jsl.fluent.FluentPropertyReference;
import io.machinecode.chainlink.spi.jsl.task.CheckpointAlgorithm;

/**
 * @author Brent Douglas
 * @since 1.0
 */
public class FluentCheckpointAlgorithm extends FluentPropertyReference<FluentCheckpointAlgorithm> implements CheckpointAlgorithm {
    @Override
    public FluentCheckpointAlgorithm copy() {
        return copy(new FluentCheckpointAlgorithm());
    }
}


text:
<head>
  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <!-- Enable responsiveness on mobile devices-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <!-- Adding MathJax to render Latex commnads-->
  <script type="text/javascript"
    src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
  </script>

  <title>
    {% if page.title == "Home" %}
      {{ site.title }} · {{ site.tagline }}
    {% else %}
      {{ page.title }} · {{ site.title }}
    {% endif %}
  </title>

  <!-- CSS -->
  <link rel="stylesheet" href="{{ site.baseurl }}public/css/poole.css">
  <!-- This was included in original hyde style
  <link rel="stylesheet" href="{{ site.baseurl }}public/css/syntax.css">
  -->
  <link rel="stylesheet" href="{{ site.baseurl }}public/css/hyde.css">
  <!-- Added This for Colouring-->
  <link rel="stylesheet" href="{{ site.baseurl }}public/css/rjow.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">

  <!-- Icons -->
  <link rel="SP_Logo_2014_144" sizes="144x144" href="{{ site.baseurl }}public/SP_Logo_2014_144.png">
                                 <link rel="shortcut icon" href="{{ site.baseurl }}public/favicon.ico">

  <!-- RSS -->
  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">
</head>


text:
package teambition_aliyun

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// InsertDevopsMember invokes the teambition_aliyun.InsertDevopsMember API synchronously
// api document: https://help.aliyun.com/api/teambition-aliyun/insertdevopsmember.html
func (client *Client) InsertDevopsMember(request *InsertDevopsMemberRequest) (response *InsertDevopsMemberResponse, err error) {
	response = CreateInsertDevopsMemberResponse()
	err = client.DoAction(request, response)
	return
}

// InsertDevopsMemberWithChan invokes the teambition_aliyun.InsertDevopsMember API asynchronously
// api document: https://help.aliyun.com/api/teambition-aliyun/insertdevopsmember.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) InsertDevopsMemberWithChan(request *InsertDevopsMemberRequest) (<-chan *InsertDevopsMemberResponse, <-chan error) {
	responseChan := make(chan *InsertDevopsMemberResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.InsertDevopsMember(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// InsertDevopsMemberWithCallback invokes the teambition_aliyun.InsertDevopsMember API asynchronously
// api document: https://help.aliyun.com/api/teambition-aliyun/insertdevopsmember.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) InsertDevopsMemberWithCallback(request *InsertDevopsMemberRequest, callback func(response *InsertDevopsMemberResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *InsertDevopsMemberResponse
		var err error
		defer close(result)
		response, err = client.InsertDevopsMember(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// InsertDevopsMemberRequest is the request struct for api InsertDevopsMember
type InsertDevopsMemberRequest struct {
	*requests.RpcRequest
	Phone    string `position:"Body" name:"Phone"`
	UserPk   string `position:"Body" name:"UserPk"`
	Email    string `position:"Body" name:"Email"`
	UserName string `position:"Body" name:"UserName"`
}

// InsertDevopsMemberResponse is the response struct for api InsertDevopsMember
type InsertDevopsMemberResponse struct {
	*responses.BaseResponse
	ErrorCode    string `json:"ErrorCode" xml:"ErrorCode"`
	ErrorMessage string `json:"ErrorMessage" xml:"ErrorMessage"`
	RequestId    string `json:"RequestId" xml:"RequestId"`
	Success      bool   `json:"Success" xml:"Success"`
	Object       string `json:"Object" xml:"Object"`
}

// CreateInsertDevopsMemberRequest creates a request to invoke InsertDevopsMember API
func CreateInsertDevopsMemberRequest() (request *InsertDevopsMemberRequest) {
	request = &InsertDevopsMemberRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("teambition-aliyun", "2020-02-26", "InsertDevopsMember", "", "")
	request.Method = requests.POST
	return
}

// CreateInsertDevopsMemberResponse creates a response to parse from InsertDevopsMember response
func CreateInsertDevopsMemberResponse() (response *InsertDevopsMemberResponse) {
	response = &InsertDevopsMemberResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Center align | Flexbox.website</title>
  <link rel="stylesheet" href="/css/prism.css">
  <link rel="stylesheet" href="/css/reader.css">

        Chapter 1—Introducing Flexbox

        Flexbox.website

      <root>
Center align

Center alignment is one of the most discussed topic in CSS. Flexbox provides a easy and elegant way to solve this layout issue.

The result of center-aligned item inside the container.

Example—Center aligning one item

<div class="container">
  <div class="item">Center aligned.</div>
</div>

.container {
  display: flex;
}
.item {
  margin: auto;
}

The beautify of margin: auto on the child items is that it automatically spread the items across the space with equivalent margins.

Example—Distribute multiple items in container

Multiple items are automatically distributed within container.

Thanks to the margin: auto, the browser automatically distribute all the items inside the flexbox container equally.

<div class="container">
  <div class="item">Item.</div>
  <div class="item">Item.</div>
  <div class="item">Item.</div>
</div>

Using align-items and justify-content

Alternatively, we can configure the alignment in the container by using the align-items and justify-content properties.

.container {
  display: flex;
  align-items: center;
  justify-content: center;
}
.item {
  /* No need to specify the alignment in children */
}

Example—Center aligning multiple items

Multiple items being center aligned.

By using the container's alignment options, we can center align multiple items together.

html, body {
  height: 100%
}
.container {
  display: flex;
  height: 100%;

  align-items: center;
  justify-content: center;

  flex-direction: column;
}
.box {
  height: 50px;
  width: 300px;
  margin: 0.2em;
}

You can find the live demo in the following link:

http://codepen.io/makzan/pen/dopZxX
</root>

      You can find the PDF/ePub/Mobi edition at https://leanpub.com/flexbox-website. Buy now and read the book in your favorite reader.

      ← flex-direction

      Container and items →

    ←

    →

    Flexbox.website. v1.0. © 2015 by Makzan.
Text and images are in CC BY-NC 4.0 lincense.
All code examples are in MIT license.


text:
package io.yawp.driver.appengine;

import com.google.appengine.api.datastore.*;
import com.google.appengine.api.datastore.Query.*;
import io.yawp.commons.http.HttpVerb;
import io.yawp.commons.utils.DateUtils;
import io.yawp.commons.utils.JsonUtils;
import io.yawp.commons.utils.ReflectionUtils;
import io.yawp.driver.api.QueryDriver;
import io.yawp.repository.IdRef;
import io.yawp.repository.LazyJson;
import io.yawp.repository.Repository;
import io.yawp.repository.models.FieldModel;
import io.yawp.repository.models.ObjectHolder;
import io.yawp.repository.models.ObjectModel;
import io.yawp.repository.query.QueryBuilder;
import io.yawp.repository.query.QueryOrder;
import io.yawp.repository.query.condition.*;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;

public class AppengineQueryDriver implements QueryDriver {

    // Filter for query
    private static final String NORMALIZED_FIELD_PREFIX = "__";

    private Repository r;

    public AppengineQueryDriver(Repository r) {
        this.r = r;
    }

    private DatastoreService datastore() {
        return DatastoreServiceFactory.getDatastoreService();
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> List<T> objects(QueryBuilder<?> builder) {
        try {
            QueryResultList<Entity> queryResult = generateResults(builder, false);

            List<T> objects = new ArrayList<T>();

            for (Entity entity : queryResult) {
                objects.add((T) toObject(builder.getModel(), entity));
            }

            return objects;
        } catch (FalsePredicateException e) {
            return Collections.emptyList();
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> List<IdRef<T>> ids(QueryBuilder<?> builder) {
        try {
            QueryResultList<Entity> queryResult = generateResults(builder, true);
            List<IdRef<T>> ids = new ArrayList<>();

            for (Entity entity : queryResult) {
                ids.add((IdRef<T>) IdRefToKey.toIdRef(r, entity.getKey(), builder.getModel()));
            }

            return ids;
        } catch (FalsePredicateException e) {
            return Collections.emptyList();
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T fetch(IdRef<T> id) {
        try {
            Key key = IdRefToKey.toKey(r, id);
            Entity entity = datastore().get(key);
            return (T) toObject(id.getModel(), entity);
        } catch (EntityNotFoundException e) {
            return null;
        }
    }

    // query

    private QueryResultList<Entity> generateResults(QueryBuilder<?> builder, boolean keysOnly) throws FalsePredicateException {
        QueryResultList<Entity> queryResult = prepareQuery(builder, keysOnly).asQueryResultList(configureFetchOptions(builder));
        setCursor(builder, queryResult);
        return queryResult;
    }

    private FetchOptions configureFetchOptions(QueryBuilder<?> builder) {
        FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();

        if (builder.getLimit() != null) {
            fetchOptions.limit(builder.getLimit());
        }
        if (builder.getCursor() != null) {
            fetchOptions.startCursor(Cursor.fromWebSafeString(builder.getCursor()));
        }
        return fetchOptions;
    }

    private void setCursor(QueryBuilder<?> builder, QueryResultList<Entity> queryResult) {
        if (queryResult.getCursor() != null) {
            builder.setCursor(queryResult.getCursor().toWebSafeString());
        }
    }

    private PreparedQuery prepareQuery(QueryBuilder<?> builder, boolean keysOnly) throws FalsePredicateException {
        Query q = new Query(builder.getModel().getKind());

        if (keysOnly) {
            q.setKeysOnly();
        }

        prepareQueryAncestor(builder, q);
        prepareQueryWhere(builder, q);
        prepareQueryOrder(builder, q);

        return datastore().prepare(q);
    }

    private void prepareQueryOrder(QueryBuilder<?> builder, Query q) {
        if (builder.getPreOrders().isEmpty()) {
            return;
        }

        for (QueryOrder order : builder.getPreOrders()) {
            String string = getActualFieldName(order.getProperty(), builder.getModel().getClazz());
            q.addSort(string, getSortDirection(order));
        }
    }

    private void prepareQueryWhere(QueryBuilder<?> builder, Query q) throws FalsePredicateException {
        BaseCondition condition = builder.getCondition();
        if (condition != null && condition.hasPreFilter()) {
            q.setFilter(createFilter(builder, condition));
        }
    }

    private void prepareQueryAncestor(QueryBuilder<?> builder, Query q) {
        IdRef<?> parentId = builder.getParentId();
        if (parentId == null) {
            return;
        }
        q.setAncestor(IdRefToKey.toKey(r, parentId));
    }

    public SortDirection getSortDirection(QueryOrder order) {
        if (order.isDesc()) {
            return SortDirection.DESCENDING;
        }
        if (order.isAsc()) {
            return SortDirection.ASCENDING;
        }
        throw new RuntimeException("Invalid sort direction");
    }

    // to object

    public Object toObject(ObjectModel model, Entity entity) {
        Object object = model.createInstance();

        ObjectHolder objectHolder = new ObjectHolder(object);
        objectHolder.setId(IdRefToKey.toIdRef(r, entity.getKey(), model));

        List<FieldModel> fieldModels = objectHolder.getModel().getFieldModels();

        for (FieldModel fieldModel : fieldModels) {
            if (fieldModel.isId()) {
                continue;
            }

            if (fieldModel.isTransient()) {
                continue;
            }

            safeSetObjectProperty(entity, object, fieldModel);
        }

        return object;
    }

    private <T> void safeSetObjectProperty(Entity entity, T object, FieldModel fieldModel) {
        try {
            setObjectProperty(object, entity, fieldModel, fieldModel.getField());
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private <T> void setObjectProperty(T object, Entity entity, FieldModel fieldModel, Field field) throws IllegalAccessException {
        Object value = entity.getProperty(field.getName());

        if (value == null) {
            field.set(object, null);
            return;
        }

        if (fieldModel.isEnum()) {
            setEnumProperty(object, field, value);
            return;
        }

        if (fieldModel.isSaveAsJson()) {
            setJsonProperty(r, object, field, value);
            return;
        }

        if (fieldModel.isSaveAsLazyJson()) {
            setLazyJsonProperty(object, field, value);
            return;
        }

        if (fieldModel.isInt()) {
            setIntProperty(object, field, value);
            return;
        }

        if (fieldModel.isIdRef()) {
            setIdRefProperty(r, object, field, value);
            return;
        }

        if (fieldModel.isSaveAsText()) {
            setTextProperty(object, field, value);
            return;
        }

        if (fieldModel.isListOfIds()) {
            setListOfIdsProperty(object, field, value);
        }

        field.set(object, value);
    }

    private <T> void setIdRefProperty(Repository r, T object, Field field, Object value) throws IllegalAccessException {
        field.set(object, IdRef.parse(r, HttpVerb.GET, (String) value));
    }

    private <T> void setIntProperty(T object, Field field, Object value) throws IllegalAccessException {
        field.set(object, ((Long) value).intValue());
    }

    private <T> void setTextProperty(T object, Field field, Object value) throws IllegalAccessException {
        field.set(object, ((Text) value).getValue());
    }

    private <T> void setJsonProperty(Repository r, T object, Field field, Object value) throws IllegalAccessException {
        String json = ((Text) value).getValue();
        field.set(object, JsonUtils.from(r, json, field.getGenericType()));
    }

    private <T> void setLazyJsonProperty(T object, Field field, Object value) throws IllegalAccessException {
        String json = ((Text) value).getValue();
        Type type = ((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0];
        field.set(object, LazyJson.$create(type, json));
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    private <T> void setEnumProperty(T object, Field field, Object value) throws IllegalAccessException {
        field.set(object, Enum.valueOf((Class) field.getType(), value.toString()));
    }

    private <T> void setListOfIdsProperty(T object, Field field, Object value) throws IllegalAccessException {
        List<String> uris = (List<String>) value;
        List<IdRef<?>> ids = new ArrayList<>(uris.size());
        Class<?> listGenericClazz = ReflectionUtils.getListGenericType(field.getGenericType());

        for (String uri : uris) {
            ids.add(r.parseId(listGenericClazz, uri));
        }

        field.set(object, ids);
    }

    private Filter createFilter(QueryBuilder<?> builder, BaseCondition condition) throws FalsePredicateException {
        if (condition instanceof SimpleCondition) {
            return createSimpleFilter(builder, (SimpleCondition) condition);
        }
        if (condition instanceof JoinedCondition) {
            return createJoinedFilter(builder, (JoinedCondition) condition);
        }
        throw new RuntimeException("Invalid condition class: " + condition.getClass());
    }

    private Filter createSimpleFilter(QueryBuilder<?> builder, SimpleCondition condition) throws FalsePredicateException {
        String field = condition.getField();
        Class<?> clazz = builder.getModel().getClazz();
        Object whereValue = condition.getWhereValue();
        WhereOperator whereOperator = condition.getWhereOperator();

        String actualFieldName = getActualFieldName(field, clazz);
        Object actualValue = getActualFieldValue(field, clazz, whereValue);

        if (whereOperator == WhereOperator.IN && listSize(whereValue) == 0) {
            throw new FalsePredicateException();
        }

        return new FilterPredicate(actualFieldName, getFilterOperator(whereOperator), actualValue);
    }

    private Filter createJoinedFilter(QueryBuilder<?> builder, JoinedCondition joinedCondition) throws FalsePredicateException {
        BaseCondition[] conditions = joinedCondition.getConditions();
        LogicalOperator logicalOperator = joinedCondition.getLogicalOperator();

        List<Filter> filters = new ArrayList<>();
        for (int i = 0; i < conditions.length; i++) {
            try {
                BaseCondition condition = conditions[i];
                if (!condition.hasPreFilter()) {
                    continue;
                }

                filters.add(createFilter(builder, condition));
            } catch (FalsePredicateException e) {
                if (logicalOperator == LogicalOperator.AND) {
                    throw e;
                }
            }
        }

        if (filters.isEmpty()) {
            throw new FalsePredicateException();
        }

        if (filters.size() == 1) {
            return filters.get(0);
        }

        Filter[] filtersArray = filters.toArray(new Filter[filters.size()]);

        if (logicalOperator == LogicalOperator.AND) {
            return CompositeFilterOperator.and(filtersArray);
        }
        if (logicalOperator == LogicalOperator.OR) {
            return CompositeFilterOperator.or(filtersArray);
        }

        throw new RuntimeException("Invalid logical operator: " + logicalOperator);
    }

    private <T> String getActualFieldName(String fieldName, Class<T> clazz) {
        Field field = ReflectionUtils.getFieldRecursively(clazz, fieldName);
        FieldModel fieldModel = new FieldModel(field);

        if (fieldModel.isId()) {
            return Entity.KEY_RESERVED_PROPERTY;
        }

        if (fieldModel.isIndexNormalizable()) {
            return NORMALIZED_FIELD_PREFIX + fieldName;
        }

        return fieldName;
    }

    public <T> Object getActualFieldValue(String fieldName, Class<T> clazz, Object value) {
        Field field = ReflectionUtils.getFieldRecursively(clazz, fieldName);
        FieldModel fieldModel = new FieldModel(field);

        if (fieldModel.isCollection(value)) {
            return getActualListFieldValue(fieldName, clazz, (Collection<?>) value);
        }

        if (fieldModel.isId()) {
            return getActualKeyFieldValue(value);
        }

        if (fieldModel.isEnum(value)) {
            return value.toString();
        }

        if (fieldModel.isIndexNormalizable()) {
            return normalizeValue(value);
        }

        if (value instanceof IdRef) {
            return ((IdRef<?>) value).getUri();
        }

        if (fieldModel.isDate() && value instanceof String) {
            return DateUtils.toTimestamp((String) value);
        }

        return value;
    }

    private <T> Object getActualListFieldValue(String fieldName, Class<T> clazz, Collection<?> value) {
        Collection<?> objects = value;
        List<Object> values = new ArrayList<>();
        for (Object obj : objects) {
            values.add(getActualFieldValue(fieldName, clazz, obj));
        }
        return values;
    }

    private <T> Key getActualKeyFieldValue(Object value) {
        IdRef<?> id = (IdRef<?>) value;
        return IdRefToKey.toKey(r, id);
    }

    private FilterOperator getFilterOperator(WhereOperator whereOperator) {
        switch (whereOperator) {
            case EQUAL:
                return FilterOperator.EQUAL;
            case GREATER_THAN:
                return FilterOperator.GREATER_THAN;
            case GREATER_THAN_OR_EQUAL:
                return FilterOperator.GREATER_THAN_OR_EQUAL;
            case IN:
                return FilterOperator.IN;
            case LESS_THAN:
                return FilterOperator.LESS_THAN;
            case LESS_THAN_OR_EQUAL:
                return FilterOperator.LESS_THAN_OR_EQUAL;
            case NOT_EQUAL:
                return FilterOperator.NOT_EQUAL;
            default:
                throw new RuntimeException("Invalid where operator: " + whereOperator);
        }
    }

    private Object normalizeValue(Object o) {
        if (o == null) {
            return null;
        }

        if (!o.getClass().equals(String.class)) {
            return o;
        }

        return StringUtils.stripAccents((String) o).toLowerCase();
    }

    public int listSize(Object value) {
        if (value == null) {
            return 0;
        }
        if (value.getClass().isArray()) {
            return Array.getLength(value);
        }
        if (Collection.class.isAssignableFrom(value.getClass())) {
            return Collection.class.cast(value).size();
        }
        if (Iterable.class.isAssignableFrom(value.getClass())) {
            return iterableSize(value);
        }
        throw new RuntimeException("Value used with operator 'in' is not an array or list.");
    }

    private int iterableSize(Object value) {
        Iterator<?> it = Iterable.class.cast(value).iterator();
        int i = 0;
        while (it.hasNext()) {
            it.next();
            i++;
        }
        return i;
    }

}


text:
namespace ginseng
{
	namespace util
	{
		namespace logging
		{
			namespace sink
			{
				void Sink::_sink_it(const spdlog::details::log_msg &spd_message)
				{
					(*this)(ginseng::util::logging::implementation::message(spd_message));
				}
			}
		}
	}
}


text:
"""
    KubeVirt API

    This is KubeVirt API an add-on for Kubernetes.

    OpenAPI spec version: 1.0.0
    Contact: kubevirt-dev@googlegroups.com
    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from pprint import pformat
from six import iteritems
import re

class V1Features(object):
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    """

    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {
        'acpi': 'V1FeatureState',
        'apic': 'V1FeatureAPIC',
        'hyperv': 'V1FeatureHyperv',
        'kvm': 'V1FeatureKVM',
        'pvspinlock': 'V1FeatureState',
        'smm': 'V1FeatureState'
    }

    attribute_map = {
        'acpi': 'acpi',
        'apic': 'apic',
        'hyperv': 'hyperv',
        'kvm': 'kvm',
        'pvspinlock': 'pvspinlock',
        'smm': 'smm'
    }

    def __init__(self, acpi=None, apic=None, hyperv=None, kvm=None, pvspinlock=None, smm=None):
        """
        V1Features - a model defined in Swagger
        """

        self._acpi = None
        self._apic = None
        self._hyperv = None
        self._kvm = None
        self._pvspinlock = None
        self._smm = None

        if acpi is not None:
          self.acpi = acpi
        if apic is not None:
          self.apic = apic
        if hyperv is not None:
          self.hyperv = hyperv
        if kvm is not None:
          self.kvm = kvm
        if pvspinlock is not None:
          self.pvspinlock = pvspinlock
        if smm is not None:
          self.smm = smm

    @property
    def acpi(self):
        """
        Gets the acpi of this V1Features.
        ACPI enables/disables ACPI inside the guest. Defaults to enabled.

        :return: The acpi of this V1Features.
        :rtype: V1FeatureState
        """
        return self._acpi

    @acpi.setter
    def acpi(self, acpi):
        """
        Sets the acpi of this V1Features.
        ACPI enables/disables ACPI inside the guest. Defaults to enabled.

        :param acpi: The acpi of this V1Features.
        :type: V1FeatureState
        """

        self._acpi = acpi

    @property
    def apic(self):
        """
        Gets the apic of this V1Features.
        Defaults to the machine type setting.

        :return: The apic of this V1Features.
        :rtype: V1FeatureAPIC
        """
        return self._apic

    @apic.setter
    def apic(self, apic):
        """
        Sets the apic of this V1Features.
        Defaults to the machine type setting.

        :param apic: The apic of this V1Features.
        :type: V1FeatureAPIC
        """

        self._apic = apic

    @property
    def hyperv(self):
        """
        Gets the hyperv of this V1Features.
        Defaults to the machine type setting.

        :return: The hyperv of this V1Features.
        :rtype: V1FeatureHyperv
        """
        return self._hyperv

    @hyperv.setter
    def hyperv(self, hyperv):
        """
        Sets the hyperv of this V1Features.
        Defaults to the machine type setting.

        :param hyperv: The hyperv of this V1Features.
        :type: V1FeatureHyperv
        """

        self._hyperv = hyperv

    @property
    def kvm(self):
        """
        Gets the kvm of this V1Features.
        Configure how KVM presence is exposed to the guest.

        :return: The kvm of this V1Features.
        :rtype: V1FeatureKVM
        """
        return self._kvm

    @kvm.setter
    def kvm(self, kvm):
        """
        Sets the kvm of this V1Features.
        Configure how KVM presence is exposed to the guest.

        :param kvm: The kvm of this V1Features.
        :type: V1FeatureKVM
        """

        self._kvm = kvm

    @property
    def pvspinlock(self):
        """
        Gets the pvspinlock of this V1Features.
        Notify the guest that the host supports paravirtual spinlocks. For older kernels this feature should be explicitly disabled.

        :return: The pvspinlock of this V1Features.
        :rtype: V1FeatureState
        """
        return self._pvspinlock

    @pvspinlock.setter
    def pvspinlock(self, pvspinlock):
        """
        Sets the pvspinlock of this V1Features.
        Notify the guest that the host supports paravirtual spinlocks. For older kernels this feature should be explicitly disabled.

        :param pvspinlock: The pvspinlock of this V1Features.
        :type: V1FeatureState
        """

        self._pvspinlock = pvspinlock

    @property
    def smm(self):
        """
        Gets the smm of this V1Features.
        SMM enables/disables System Management Mode. TSEG not yet implemented.

        :return: The smm of this V1Features.
        :rtype: V1FeatureState
        """
        return self._smm

    @smm.setter
    def smm(self, smm):
        """
        Sets the smm of this V1Features.
        SMM enables/disables System Management Mode. TSEG not yet implemented.

        :param smm: The smm of this V1Features.
        :type: V1FeatureState
        """

        self._smm = smm

    def to_dict(self):
        """
        Returns the model properties as a dict
        """
        result = {}

        for attr, _ in iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """
        Returns the string representation of the model
        """
        return pformat(self.to_dict())

    def __repr__(self):
        """
        For `print` and `pprint`
        """
        return self.to_str()

    def __eq__(self, other):
        """
        Returns true if both objects are equal
        """
        if not isinstance(other, V1Features):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """
        Returns true if both objects are not equal
        """
        return not self == other


text:
import { Observable } from '../Observable';
export declare function partition<T>(predicate: (x: any, i?: any, a?: any) => boolean, thisArg?: any): Observable<T>[];


text:
require 'bundler/setup'
Bundler.require :default, :development, :test

$LOAD_PATH << File.join(File.dirname(__FILE__), '..', 'lib')

require 'wopr'

Dir[File.join(File.dirname(__FILE__), "support/**/*.rb")].each { |f| require f }

RSpec.configure do |configure|
  configure.mock_with :rspec
  configure.include XMLMatchers
  configure.after(:each) do
    Wopr::Call.destroy_all
  end
end


text:
"use strict";

const remark = require("remark");
const findAllAfter = require("unist-util-find-all-after");

module.exports = function (source, opts) {
	// Skip known non-markdown files.
	if (opts.from && !/\.(?:md|markdown)(?:\?.+)?$/i.test(opts.from)) {
		return;
	}
	let isStructureMD = false;
	const ast = remark().parse(source);
	const blocks = findAllAfter(ast, 0, (node) => {
		if (node.type === "code" && node.lang) {
			isStructureMD = true;
			return /^(?:(?:[ps]?c)|le|wx|sa?|sugar)ss$/i.test(node.lang);
		}
	});

	if (!isStructureMD) {
		return;
	}

	return blocks.map((block) => {
		const startIndex = source.indexOf(block.value, block.position.start.offset);
		const content = source.slice(startIndex, block.position.end.offset).replace(/[ \t]*`*$/, "");
		return {
			startIndex: startIndex,
			lang: block.lang.toLowerCase(),
			isMarkdown: true,
			content: content,
		};
	});
};


text:
<?php

/**
 * FurryBear
 *
 * PHP Version 5.3
 *
 * @category Congress_API
 * @package  FurryBear
 * @author   lobostome <lobostome@local.dev>
 * @license  http://opensource.org/licenses/MIT MIT License
 * @link     https://github.com/lobostome/FurryBear
 */

namespace FurryBear\Iterator\SunlightPoliticalPartyTime;

use FurryBear\Resource\AbstractResource;

/**
 * An iterator over the pages of the result.
 *
 * @category Congress_API
 * @package  FurryBear
 * @author   lobostome <lobostome@local.dev>
 * @license  http://opensource.org/licenses/MIT MIT License
 * @link     http://sunlightlabs.github.com/congress/
 */
class PageIterator implements \Iterator
{
    /**
     * A reference to the resource.
     *
     * @var \FurryBear\Resource\AbstractResource
     */
    protected $resource;

    /**
     * A cache of the resource parameters.
     *
     * @var array
     */
    protected $params;

    /**
     * Are there any more items?
     *
     * @var boolean
     */
    protected $isEnd = FALSE;

    /**
     * Construct an iterator and set the resource.
     *
     * @param \FurryBear\Resource\AbstractResource $resource A reference to a resource.
     */
    public function __construct(AbstractResource $resource)
    {
        $this->resource = $resource;
        $this->params = $this->resource->getParams();

        if (!isset($this->params['limit'])) {
            $this->params['limit'] = 50;
        }

        if (!isset($this->params['offset'])) {
            $this->params['offset'] = 0;
        }
    }

    /**
     * Return the current element. Determine if end of iteration.
     *
     * @return object|array
     */
    public function current()
    {
        $result = $this->resource->get($this->params);

        switch ($this->resource->extractFormat()) {
            case 'json':
                if (is_array($result)) {
                    if (!is_string($result['meta']['next'])) {
                        $this->isEnd = TRUE;
                    }
                } else if (is_object($result)) {
                    if (!is_string($result->meta->next)) {
                        $this->isEnd = TRUE;
                    }
                }
                break;
            case 'xml':
                if (strlen((string)$result->meta->next) == 0) {
                    $this->isEnd = TRUE;
                }
                break;
        }

        return $result;
    }

    /**
     * Returns the key of the current element.
     *
     * @return scalar
     * @throws \FurryBear\Common\Exception\NotImplementedException This method does not exist.
     */
    public function key()
    {
        throw new \FurryBear\Common\Exception\NotImplementedException('Method ' . __METHOD__ . ' is not implemented');
    }

    /**
     * Move forward to next element
     *
     * @return void
     */
    public function next()
    {
        $this->params['offset'] += $this->params['limit'];
    }

    /**
     * Rewind the Iterator to the first element
     *
     * @return void
     */
    public function rewind()
    {
        $this->params['offset'] = 0;
    }

    /**
     * Checks if current position is valid
     *
     * @return boolean
     */
    public function valid()
    {
        return ($this->isEnd == FALSE);
    }
}


text:
package main

import (
	"crypto/sha256"
	"crypto/tls"
	"encoding/base32"
	"path/filepath"
	"strings"
)

func loadCert(dir string) (tls.Certificate, error) {
	return tls.LoadX509KeyPair(filepath.Join(dir, "cert.pem"), filepath.Join(dir, "key.pem"))
}

func certID(bs []byte) string {
	hf := sha256.New()
	hf.Write(bs)
	id := hf.Sum(nil)
	return strings.Trim(base32.StdEncoding.EncodeToString(id), "=")
}


text:
<?php

namespace JHWEB\UsuarioBundle\Controller;

use JHWEB\UsuarioBundle\Entity\UserLicenciaTransito;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;use Symfony\Component\HttpFoundation\Request;

/**
 * Userlicenciatransito controller.
 *
 * @Route("userlicenciatransito")
 */
class UserLicenciaTransitoController extends Controller
{
    /**
     * Lists all userLicenciaTransito entities.
     *
     * @Route("/", name="userlicenciatransito_index")
     * @Method("GET")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $userLicenciaTransitos = $em->getRepository('JHWEBUsuarioBundle:UserLicenciaTransito')->findAll();

        return $this->render('userlicenciatransito/index.html.twig', array(
            'userLicenciaTransitos' => $userLicenciaTransitos,
        ));
    }

    /**
     * Creates a new userLicenciaTransito entity.
     *
     * @Route("/new", name="userlicenciatransito_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $userLicenciaTransito = new Userlicenciatransito();
        $form = $this->createForm('JHWEB\UsuarioBundle\Form\UserLicenciaTransitoType', $userLicenciaTransito);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($userLicenciaTransito);
            $em->flush();

            return $this->redirectToRoute('userlicenciatransito_show', array('id' => $userLicenciaTransito->getId()));
        }

        return $this->render('userlicenciatransito/new.html.twig', array(
            'userLicenciaTransito' => $userLicenciaTransito,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a userLicenciaTransito entity.
     *
     * @Route("/{id}/show", name="userlicenciatransito_show")
     * @Method("GET")
     */
    public function showAction(UserLicenciaTransito $userLicenciaTransito)
    {
        $deleteForm = $this->createDeleteForm($userLicenciaTransito);

        return $this->render('userlicenciatransito/show.html.twig', array(
            'userLicenciaTransito' => $userLicenciaTransito,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing userLicenciaTransito entity.
     *
     * @Route("/{id}/edit", name="userlicenciatransito_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, UserLicenciaTransito $userLicenciaTransito)
    {
        $deleteForm = $this->createDeleteForm($userLicenciaTransito);
        $editForm = $this->createForm('JHWEB\UsuarioBundle\Form\UserLicenciaTransitoType', $userLicenciaTransito);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('userlicenciatransito_edit', array('id' => $userLicenciaTransito->getId()));
        }

        return $this->render('userlicenciatransito/edit.html.twig', array(
            'userLicenciaTransito' => $userLicenciaTransito,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a userLicenciaTransito entity.
     *
     * @Route("/{id}/delete", name="userlicenciatransito_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, UserLicenciaTransito $userLicenciaTransito)
    {
        $form = $this->createDeleteForm($userLicenciaTransito);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($userLicenciaTransito);
            $em->flush();
        }

        return $this->redirectToRoute('userlicenciatransito_index');
    }

    /**
     * Creates a form to delete a userLicenciaTransito entity.
     *
     * @param UserLicenciaTransito $userLicenciaTransito The userLicenciaTransito entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(UserLicenciaTransito $userLicenciaTransito)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('userlicenciatransito_delete', array('id' => $userLicenciaTransito->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }

    /* ================================================== */

    /**
     * Finds and displays a userCfgEmpresaTipo entity.
     *
     * @Route("/search/actual", name="userlicenciatransito_search_actual")
     * @Method("POST")
     */
    public function searchActualAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck== true) {
            $json = $request->get("data",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();

            $licenciaTransito = $em->getRepository('JHWEBUsuarioBundle:UserLicenciaTransito')->getByCiudadanoAndVehiculo(
                $params->idCiudadano, $params->idVehiculo
            );

            $response = array(
                'status' => 'success',
                'code' => 200,
                'message' => "Registro encontrado con exito",
                'data' => $licenciaTransito
            );
        }else{
            $response = array(
                'status' => 'error',
                'code' => 400,
                'message' => "Autorizacion no valida",
            );
        }

        return $helpers->json($response);
    }
}


text:
<?php

declare(strict_types=1);

namespace Inowas\ModflowModel\Model\Command;

use Inowas\Common\Command\AbstractJsonSchemaCommand;
use Inowas\Common\Id\ModflowId;
use Inowas\Common\Id\UserId;

class CloneModflowModel extends AbstractJsonSchemaCommand
{

    /** @noinspection MoreThanThreeArgumentsInspection
     * @param ModflowId $baseModelId
     * @param UserId $userId
     * @param ModflowId $newModelId
     * @param bool $isTool
     * @return CloneModflowModel
     */
    public static function byId(ModflowId $baseModelId, UserId $userId, ModflowId $newModelId, bool $isTool = false): CloneModflowModel
    {
        $self = new static([
            'id' => $baseModelId->toString(),
            'new_id' => $newModelId->toString(),
            'is_tool' => $isTool
        ]);

        /** @var CloneModflowModel $self */
        $self = $self->withAddedMetadata('user_id', $userId->toString());
        return $self;
    }

    public function schema(): string
    {
        return 'file://spec/schema/modflow/command/cloneModflowModelPayload.json';
    }

    public function userId(): UserId
    {
        return UserId::fromString($this->metadata['user_id']);
    }

    public function modelId(): ModflowId
    {
        return ModflowId::fromString($this->payload['id']);
    }

    public function newModelId(): ModflowId
    {
        return ModflowId::fromString($this->payload['new_id']);
    }

    public function isTool(): bool
    {
        if (!array_key_exists('is_tool', $this->payload()) ) {
            return false;
        }

        return $this->payload['is_tool'];
    }
}


text:
import argparse
import os
import re
import select
import serial
import signal
import subprocess
import sys
# This is where ottplib is installed
sys.path.append("/usr/local/lib/python3.6/site-packages")
sys.path.append("/usr/local/lib/python3.8/site-packages")
import time

import ottplib

VERSION = "0.1.5"
AUTHORS = "Michael Wouters"

# Time stamp formats
TS_UNIX = 0
TS_TOD  = 1

# Counter mode
TIC_MODE_TS=0 # time stamp mode
TIC_MODE_TI=1 # time interval mode

# Globals
debug = False
killed = False

# ------------------------------------------
def SignalHandler(signal,frame):
	global killed
	killed=True
	return

# ------------------------------------------
def Debug(msg):
	if (debug):
		print(msg)
	return

# ------------------------------------------
def ErrorExit(msg):
	print(msg)
	sys.exit(0)

# ------------------------------------------
def Initialise(configFile):
	cfg=ottplib.LoadConfig(configFile,{'tolower':True})
	if (cfg == None):
		ErrorExit("Error loading " + configFile)

	# Check for required arguments
	reqd = ['counter:port','paths:counter data','counter:file extension','counter:lock file']
	for k in reqd:
		if not(k in cfg):
			ErrorExit("The required configuration entry " + k + " is undefined")

	return cfg

# ------------------------------------------
# Main
# ------------------------------------------

tsformat = TS_TOD
tic_mode = TIC_MODE_TS

home =os.environ['HOME'] + os.sep
configFile = os.path.join(home,'etc','gpscv.conf')

parser = argparse.ArgumentParser(description='Log a TAPR TICC in TI mode',
	formatter_class=argparse.RawDescriptionHelpFormatter)

parser.add_argument('--config','-c',help='use an alternate configuration file',default=configFile)
parser.add_argument('--debug','-d',help='debug',action='store_true')
parser.add_argument('--settings','-s',help='show settings',action='store_true')
parser.add_argument('--version','-v',action='version',version = os.path.basename(sys.argv[0])+ ' ' + VERSION + '\n' + 'Written by ' + AUTHORS)

args = parser.parse_args()

debug = args.debug

configFile = args.config;

if (not os.path.isfile(configFile)):
	ErrorExit(configFile + " not found")

logPath = os.path.join(home,'logs')
if (not os.path.isdir(logPath)):
	ErrorExit(logPath + "not found")

cfg=Initialise(configFile)

#for key,val in cfg.items():
#	print key,"=>",val

port = cfg['counter:port']
dataPath= ottplib.MakeAbsolutePath(cfg['paths:counter data'], home)

ctrExt = cfg['counter:file extension']
if (None == re.search(r'\.$',ctrExt)):
	ctrExt = '.' + ctrExt

headerGen=''
if ('counter:header generator' in cfg):
	headerGen = ottplib.MakeAbsoluteFilePath(cfg['counter:header generator'],home,home+'/bin')

if ('counter:mode' in cfg):
	if (cfg['counter:mode'] == 'timestamp'):
		tic_mode = TIC_MODE_TS
	elif (cfg['counter:mode'] == 'time interval'):
		tic_mode = TIC_MODE_TI

if ('counter:timestamp format' in cfg):
	if (cfg['counter:timestamp format'] == 'unix'):
		tsformat = TS_UNIX
	elif (cfg['counter:timestamp format'] == 'time of day'):
		tsformat = TS_TOD

# Create the process lock
lockFile=ottplib.MakeAbsoluteFilePath(cfg['counter:lock file'],home,home + '/etc')
Debug("Creating lock " + lockFile)
if (not ottplib.CreateProcessLock(lockFile)):
	ErrorExit("Couldn't create a lock")

# Create UUCP lock for the serial port
uucpLockPath="/var/lock";
if ('paths:uucp lock' in cfg):
	uucpLockPath = cfg['paths:uucp lock']

ret = subprocess.check_output(['/usr/local/bin/lockport','-d',uucpLockPath,'-p',str(os.getpid()),port,sys.argv[0]])

if (re.match(b'1',ret)==None):
	ottplib.RemoveProcessLock(lockFile)
	ErrorExit('Could not obtain a lock on ' + port + '.Exiting.')

signal.signal(signal.SIGINT,SignalHandler)
signal.signal(signal.SIGTERM,SignalHandler)
signal.signal(signal.SIGHUP,SignalHandler) # not usually run with a controlling TTY but handle it anyway

Debug("Opening " + port)

try:
	ser = serial.Serial(port,115200,timeout=2)
except:
	print("Error on device" + port)
	ottplib.RemoveProcessLock(lockFile)
	subprocess.check_output(['/usr/local/bin/lockport','-r',port]) # but ignore return value anyway
	exit()

state = 1 # state machine for parsing the startup information
				# note that this is output when a serial connection is initiated

# Eat junk and startup information
ctrcfg=''
oldmjd=-1
while (state < 4):
	try:
		l = ser.readline()
	except select.error as err:
		print(err)
		sys.exit(0)
	if (len(l) == 0):
		print('Timeout')
		sys.exit(0)
	# If already connected then we won't see the startup bumpf
	l=l[:-2]
	if (len(l) == 0):
		continue
	# If the first character is not # then break out of this completely
	if (not (l[0] == '#')):
		state=4

	if (state == 1):
		if (l.find('TICC Configuration') != -1):
			state = 2
	elif (state == 2):
		ctrcfg=ctrcfg  + l + '\n'
		if (l.find('FUDGE0') != -1):
			state = 3
			if (args.settings): # this is here so we don't get stuck on a TICC not configured for TI yet
				print(ctrcfg)
				ottplib.RemoveProcessLock(lockFile)
				ser.close()
				subprocess.check_output(['/usr/local/bin/lockport','-r',port])
				sys.exit(0)
	elif (state == 3):
		if ((tic_mode == TIC_MODE_TI) and (l.find('time interval A->B (seconds)') != -1)):
			state = 4
		elif ((tic_mode == TIC_MODE_TS) and (l.find('Timestamp') != -1)):
			state = 4

nbad = 0

# Can get some buffered stuff at the beginning if already running so toss it
for i in range(20):
	try:
		l = ser.readline()
	except select.error as err: # CTRL-C returns code=4
		print(err)
		break;

while (not killed):

	# Check whether we need to create a new log file
	tt = time.time()
	mjd = ottplib.MJD(tt)
	if (not( mjd == oldmjd)):
		oldmjd = mjd
		if (tic_mode == TIC_MODE_TI):
			fnoutA = dataPath + str(mjd) + ctrExt
		elif (tic_mode == TIC_MODE_TS):
			fnoutA = dataPath + str(mjd) + '.A' + ctrExt
			fnoutB = dataPath + str(mjd) + '.B' + ctrExt
		if (not os.path.isfile(fnoutA)):
			foutA = open(fnoutA,'w')
			if (os.path.isfile(headerGen) and os.access(headerGen,os.X_OK)):
				header=subprocess.check_output([headerGen,'-c',configFile])
				foutA.write(header.rstrip()+'\n') # make sure there is just one linefeed
			foutA.write(ctrcfg) # Configuration after the header
		else:
			foutA = open(fnoutA,'a')

		Debug('Opened '+fnoutA)

		if (tic_mode == TIC_MODE_TS):
			if (not os.path.isfile(fnoutB)):
				foutB = open(fnoutB,'w')
				if (os.path.isfile(headerGen) and os.access(headerGen,os.X_OK)):
					header=subprocess.check_output([headerGen])
					foutB.write(header.rstrip()+'\n')
				foutB.write(ctrcfg) # Configuration after the header
			else:
				foutB = open(fnoutB,'a')
			Debug('Opened '+fnoutB)

	try:
		l = ser.readline()[:-2]
	except select.error as err: # CTRL-C returns code=4
		print(err)
		break;

	lstr = l.decode('utf-8')

	tt = time.time() # floating point!
	ttround = round(tt) # round to take care of system time being close to the epoch
											# of course, if the stop pulse is 0.5 s off, this all falls over

	Debug(lstr)
	Debug(str(tt) + ' ' + str(ttround))
	if (tic_mode == TIC_MODE_TI):
		if (lstr.find('TI(A->B)') != -1):
			if (tsformat == TS_UNIX):
				foutA.write(str(tt) + ' ' + lstr.split()[0]+'\n')
			elif (tsformat == TS_TOD):
				foutA.write(time.strftime('%H:%M:%S',time.gmtime(ttround)) + ' ' + lstr.split()[0]+'\n')
			foutA.flush()
			nbad = nbad - 1
		else:
			nbad = nbad + 1
	elif (tic_mode == TIC_MODE_TS):
		if (lstr.find('chA') != -1):
			ts = lstr.split()[0]
			if (None == re.match('^\d+\.\d{12}',ts)):
				nbad =nbad + 1
			else:
				if (tsformat == TS_UNIX):
					foutA.write(str(tt) + ' ' + ts +'\n')
				elif (tsformat == TS_TOD):
					foutA.write(time.strftime('%H:%M:%S',time.gmtime(ttround)) + ' ' + ts +'\n')
				foutA.flush()
				nbad =nbad -1
		elif (lstr.find('chB') != -1):
			ts = lstr.split()[0]
			if (None == re.match('^\d+\.\d{12}',ts)):
				nbad =nbad + 1
			else:
				if (tsformat == TS_UNIX):
					foutB.write(str(tt) + ' ' + ts + '\n')
				elif (tsformat == TS_TOD):
					foutB.write(time.strftime('%H:%M:%S',time.gmtime(ttround)) + ' ' + ts +'\n')
				foutB.flush()
				nbad =nbad -1

	if (nbad < 0):
		nbad =0

	if (nbad >= 30):
		foutA.close()
		ottplib.RemoveProcessLock(lockFile)
		ser.close()
		subprocess.check_output(['/usr/local/bin/lockport','-r',port])
		ErrorExit("Too many bad readings - no signal?")

# All done - cleanup
foutA.close()
ottplib.RemoveProcessLock(lockFile)
ser.close()
subprocess.check_output(['/usr/local/bin/lockport','-r',port])


text:
lib-byond-doc
=============

A library providing mechanisms to convert textual documentation from comments into more formal documentation, for the DM language.


text:
package leetcode;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * https://leetcode.com/problems/implement-strstr/
 */
public class LC028ImplementStrStr {
    public class Solution {
        public int strStr(String haystack, String needle) {
            if (haystack.length() < needle.length()) return -1;
            for (int i = 0; i <= haystack.length() - needle.length(); i++){
                if(haystack.substring(i, i + needle.length()).equals(needle)){
                    return i;
                }
            }
            return -1;
        }
    }

    @Test
    public void test_empty() throws Exception {
        assertEquals(0, new Solution().strStr("", ""));
    }

    @Test
    public void test_mississippi_a() throws Exception {
        assertEquals(-1, new Solution().strStr("mississippi", "a"));
    }

    @Test
    public void test_mississippi_si() throws Exception {
        assertEquals(3, new Solution().strStr("mississippi", "si"));
    }
}