text:
package com.thoughtworks.go.server.materials;

import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.materials.ScmMaterial;
import com.thoughtworks.go.config.materials.dependency.DependencyMaterial;
import com.thoughtworks.go.config.materials.svn.SvnMaterial;
import com.thoughtworks.go.config.materials.svn.SvnMaterialConfig;
import com.thoughtworks.go.domain.PipelineGroups;
import com.thoughtworks.go.domain.materials.Material;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import com.thoughtworks.go.helper.MaterialConfigsMother;
import com.thoughtworks.go.helper.MaterialsMother;
import com.thoughtworks.go.helper.PipelineConfigMother;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.materials.postcommit.PostCommitHookImplementer;
import com.thoughtworks.go.server.materials.postcommit.PostCommitHookMaterialType;
import com.thoughtworks.go.server.materials.postcommit.PostCommitHookMaterialTypeResolver;
import com.thoughtworks.go.server.perf.MDUPerformanceLogger;
import com.thoughtworks.go.server.service.GoConfigService;
import com.thoughtworks.go.server.service.MaintenanceModeService;
import com.thoughtworks.go.server.service.MaterialConfigConverter;
import com.thoughtworks.go.server.service.SecretParamResolver;
import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult;
import com.thoughtworks.go.serverhealth.HealthStateScope;
import com.thoughtworks.go.serverhealth.HealthStateType;
import com.thoughtworks.go.serverhealth.ServerHealthService;
import com.thoughtworks.go.serverhealth.ServerHealthState;
import com.thoughtworks.go.util.MaterialFingerprintTag;
import com.thoughtworks.go.util.ProcessManager;
import com.thoughtworks.go.util.ReflectionUtil;
import com.thoughtworks.go.util.SystemEnvironment;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mockito;

import java.util.*;

import static com.thoughtworks.go.helper.MaterialUpdateMessageMatcher.matchMaterialUpdateMessage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.*;

public class MaterialUpdateServiceTest {
    private MaterialUpdateService service;
    private static final SvnMaterial svnMaterial = MaterialsMother.svnMaterial();
    private static final DependencyMaterial dependencyMaterial = MaterialsMother.dependencyMaterial();
    private SCMMaterialSource scmMaterialSource;
    private DependencyMaterialUpdateNotifier dependencyMaterialUpdateNotifier;
    private MaterialUpdateQueue queue;
    private MaterialUpdateCompletedTopic completed;
    private ConfigMaterialUpdateQueue configQueue;
    private GoConfigWatchList watchList;
    private GoConfigService goConfigService;
    private static final SvnMaterialConfig MATERIAL_CONFIG = MaterialConfigsMother.svnMaterialConfig();
    private Username username;
    private HttpLocalizedOperationResult result;
    private PostCommitHookMaterialTypeResolver postCommitHookMaterialType;
    private PostCommitHookMaterialType validMaterialType;
    private PostCommitHookMaterialType invalidMaterialType;
    private ServerHealthService serverHealthService;
    private SystemEnvironment systemEnvironment;
    private MaterialConfigConverter materialConfigConverter;
    private DependencyMaterialUpdateQueue dependencyMaterialUpdateQueue;
    private MaintenanceModeService maintenanceModeService;
    private SecretParamResolver secretParamResolver;

    @BeforeEach
    void setUp() {
        queue = mock(MaterialUpdateQueue.class);
        configQueue = mock(ConfigMaterialUpdateQueue.class);
        watchList = mock(GoConfigWatchList.class);
        completed = mock(MaterialUpdateCompletedTopic.class);
        goConfigService = mock(GoConfigService.class);
        postCommitHookMaterialType = mock(PostCommitHookMaterialTypeResolver.class);
        serverHealthService = mock(ServerHealthService.class);
        systemEnvironment = new SystemEnvironment();
        scmMaterialSource = mock(SCMMaterialSource.class);
        dependencyMaterialUpdateNotifier = mock(DependencyMaterialUpdateNotifier.class);
        materialConfigConverter = mock(MaterialConfigConverter.class);
        MDUPerformanceLogger mduPerformanceLogger = mock(MDUPerformanceLogger.class);
        dependencyMaterialUpdateQueue = mock(DependencyMaterialUpdateQueue.class);
        maintenanceModeService = mock(MaintenanceModeService.class);
        secretParamResolver = mock(SecretParamResolver.class);

        service = new MaterialUpdateService(queue, configQueue, completed, watchList, goConfigService, systemEnvironment,
                serverHealthService, postCommitHookMaterialType, mduPerformanceLogger, materialConfigConverter,
                dependencyMaterialUpdateQueue, maintenanceModeService, secretParamResolver);

        service.registerMaterialSources(scmMaterialSource);
        service.registerMaterialUpdateCompleteListener(scmMaterialSource);
        service.registerMaterialUpdateCompleteListener(dependencyMaterialUpdateNotifier);

        HashSet<MaterialConfig> materialConfigs = new HashSet(Collections.singleton(MATERIAL_CONFIG));
        HashSet<Material> materials = new HashSet(Collections.singleton(svnMaterial));
        when(goConfigService.getSchedulableMaterials()).thenReturn(materialConfigs);
        when(materialConfigConverter.toMaterials(materialConfigs)).thenReturn(materials);
        username = new Username(new CaseInsensitiveString("loser"));
        result = new HttpLocalizedOperationResult();
        validMaterialType = mock(PostCommitHookMaterialType.class);
        when(validMaterialType.isKnown()).thenReturn(true);
        when(validMaterialType.isValid(anyString())).thenReturn(true);
        invalidMaterialType = mock(PostCommitHookMaterialType.class);
        when(invalidMaterialType.isKnown()).thenReturn(false);
        when(invalidMaterialType.isValid(anyString())).thenReturn(false);
    }

    @AfterEach
    void teardown() throws Exception {
        systemEnvironment.reset(SystemEnvironment.MATERIAL_UPDATE_INACTIVE_TIMEOUT);
    }

    @Test
    void shouldSendMaterialUpdateMessageForAllSchedulableMaterials_onTimer() throws Exception {
        when(scmMaterialSource.materialsForUpdate()).thenReturn(new HashSet<>(Arrays.asList(svnMaterial)));

        service.onTimer();

        Mockito.verify(queue).post(matchMaterialUpdateMessage(svnMaterial));
    }

    @Test
    void shouldNotSendMaterialUpdateMessageForAllSchedulableMaterials_onTimerWhenServerIsInMaintenanceMode() throws Exception {
        when(maintenanceModeService.isMaintenanceMode()).thenReturn(true);
        when(scmMaterialSource.materialsForUpdate()).thenReturn(new HashSet<>(Arrays.asList(svnMaterial)));

        service.onTimer();

        Mockito.verifyZeroInteractions(queue);
    }

    @Nested
    class updateMaterial {

        @Test
        void shouldPostUpdateMessageOnUpdateQueueForNonConfigMaterial() {
            assertThat(service.updateMaterial(svnMaterial)).isTrue();

            Mockito.verify(queue).post(matchMaterialUpdateMessage(svnMaterial));
            Mockito.verify(configQueue, times(0)).post(any(MaterialUpdateMessage.class));
        }

        @Test
        void shouldPostUpdateMessageOnConfigQueueForConfigMaterial() {
            when(watchList.hasConfigRepoWithFingerprint(svnMaterial.getFingerprint())).thenReturn(true);

            assertThat(service.updateMaterial(svnMaterial)).isTrue();

            Mockito.verify(configQueue).post(matchMaterialUpdateMessage(svnMaterial));
            Mockito.verify(queue, times(0)).post(any(MaterialUpdateMessage.class));
        }

        @Test
        void shouldPostUpdateMessageOnDependencyMaterialUpdateQueueForDependencyMaterial() {
            when(watchList.hasConfigRepoWithFingerprint(svnMaterial.getFingerprint())).thenReturn(false);

            assertThat(service.updateMaterial(dependencyMaterial)).isTrue();

            Mockito.verify(dependencyMaterialUpdateQueue).post(matchMaterialUpdateMessage(dependencyMaterial));
            Mockito.verify(queue, times(0)).post(any(MaterialUpdateMessage.class));
            Mockito.verify(configQueue, times(0)).post(any(MaterialUpdateMessage.class));
        }

        @Test
        void shouldAllowConcurrentUpdatesForNonAutoUpdateMaterials() throws Exception {
            ScmMaterial material = mock(ScmMaterial.class);
            when(material.isAutoUpdate()).thenReturn(false);
            MaterialUpdateMessage message = new MaterialUpdateMessage(material, 0);
            doNothing().when(queue).post(message);

            assertThat(service.updateMaterial(material)).isTrue(); //prune inprogress queue to have this material in i.isTrue()t
            assertThat(service.updateMaterial(material)).isTrue(); // immediately notify another check-i.isTrue()n

            verify(queue, times(2)).post(message);
            verify(material).isAutoUpdate();
        }

        @Test
        void shouldNotAllowConcurrentUpdatesForAutoUpdateConfigMaterials() throws Exception {
            ScmMaterial material = mock(ScmMaterial.class);
            when(material.isAutoUpdate()).thenReturn(true);
            when(material.getFingerprint()).thenReturn("fingerprint");
            when(watchList.hasConfigRepoWithFingerprint("fingerprint")).thenReturn(true);
            MaterialUpdateMessage message = new MaterialUpdateMessage(material, 0);
            doNothing().when(configQueue).post(message);

            assertThat(service.updateMaterial(material)).isTrue(); //prune inprogress queue to have this material in i.isTrue()t
            assertThat(service.updateMaterial(material)).isFalse(); // immediately notify another check-in

            verify(configQueue, times(1)).post(message);
            verify(material).isAutoUpdate();
        }

        @Test
        void shouldNotAllowConcurrentUpdatesForAutoUpdateMaterials() throws Exception {
            ScmMaterial material = mock(ScmMaterial.class);
            when(material.isAutoUpdate()).thenReturn(true);
            MaterialUpdateMessage message = new MaterialUpdateMessage(material, 0);
            doNothing().when(queue).post(message);

            assertThat(service.updateMaterial(material)).isTrue(); //prune inprogress queue to have this material in i.isTrue()t
            assertThat(service.updateMaterial(material)).isFalse(); // immediately notify another check-in

            verify(queue, times(1)).post(message);
            verify(material).isAutoUpdate();
        }

        @Test
        void shouldAllowPostCommitNotificationsToPassThroughToTheQueue_WhenTheSameMaterialIsNotCurrentlyInProgressAndMaterialIsAutoUpdateTrue() throws Exception {
            ScmMaterial material = mock(ScmMaterial.class);
            when(material.isAutoUpdate()).thenReturn(true);
            MaterialUpdateMessage message = new MaterialUpdateMessage(material, 0);
            doNothing().when(queue).post(message);

            service.updateMaterial(material); // first call to the method

            verify(queue, times(1)).post(message);
            verify(material, never()).isAutoUpdate();
        }

        @Test
        void shouldAllowPostCommitNotificationsToPassThroughToTheQueue_WhenTheSameMaterialIsNotCurrentlyInProgressAndMaterialIsAutoUpdateFalse() throws Exception {
            ScmMaterial material = mock(ScmMaterial.class);
            when(material.isAutoUpdate()).thenReturn(false);
            MaterialUpdateMessage message = new MaterialUpdateMessage(material, 0);
            doNothing().when(queue).post(message);

            service.updateMaterial(material); // first call to the method

            verify(queue, times(1)).post(message);
            verify(material, never()).isAutoUpdate();
        }
    }

    @Nested
    class notifyMaterialsForUpdate {

        @Test
        void shouldReturn401WhenUserIsNotAnAdmin_WhenInvokingPostCommitHookMaterialUpdate() {
            when(goConfigService.isUserAdmin(username)).thenReturn(false);
            service.notifyMaterialsForUpdate(username, new HashMap(), result);

            HttpLocalizedOperationResult forbiddenResult = new HttpLocalizedOperationResult();
            forbiddenResult.forbidden("Unauthorized to access this API.", HealthStateType.forbidden());

            assertThat(result).isEqualTo(forbiddenResult);

            verify(goConfigService).isUserAdmin(username);
        }

        @Test
        void shouldReturn400WhenTypeIsMissing_WhenInvokingPostCommitHookMaterialUpdate() {
            when(goConfigService.isUserAdmin(username)).thenReturn(true);
            service.notifyMaterialsForUpdate(username, new HashMap(), result);

            HttpLocalizedOperationResult badRequestResult = new HttpLocalizedOperationResult();
            badRequestResult.badRequest("The request could not be understood by Go Server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.");

            assertThat(result).isEqualTo(badRequestResult);

            verify(goConfigService).isUserAdmin(username);
        }

        @Test
        void shouldReturn400WhenTypeIsInvalid_WhenInvokingPostCommitHookMaterialUpdate() {
            when(goConfigService.isUserAdmin(username)).thenReturn(true);
            when(postCommitHookMaterialType.toType("some_invalid_type")).thenReturn(invalidMaterialType);
            final HashMap params = new HashMap();
            params.put(MaterialUpdateService.TYPE, "some_invalid_type");
            service.notifyMaterialsForUpdate(username, params, result);

            HttpLocalizedOperationResult badRequestResult = new HttpLocalizedOperationResult();
            badRequestResult.badRequest("The request could not be understood by Go Server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.");

            assertThat(result).isEqualTo(badRequestResult);

            verify(goConfigService).isUserAdmin(username);
        }

        @Test
        void shouldReturn404WhenThereAreNoMaterialsToSchedule_WhenInvokingPostCommitHookMaterialUpdate() {
            when(goConfigService.isUserAdmin(username)).thenReturn(true);

            PostCommitHookMaterialType materialType = mock(PostCommitHookMaterialType.class);
            when(postCommitHookMaterialType.toType("type")).thenReturn(materialType);

            PostCommitHookImplementer hookImplementer = mock(PostCommitHookImplementer.class);
            when(materialType.getImplementer()).thenReturn(hookImplementer);
            when(materialType.isKnown()).thenReturn(true);

            CruiseConfig config = mock(BasicCruiseConfig.class);
            when(goConfigService.currentCruiseConfig()).thenReturn(config);
            when(config.getGroups()).thenReturn(new PipelineGroups());

            when(hookImplementer.prune(anySet(), anyMap())).thenReturn(new HashSet<Material>());

            final HashMap params = new HashMap();
            params.put(MaterialUpdateService.TYPE, "type");

            service.notifyMaterialsForUpdate(username, params, result);

            HttpLocalizedOperationResult operationResult = new HttpLocalizedOperationResult();
            operationResult.notFound("Unable to find material. Materials must be configured not to poll for new changes before they can be used with the notification mechanism.", HealthStateType.general(HealthStateScope.GLOBAL));

            assertThat(result).isEqualTo(operationResult);

            verify(hookImplementer).prune(anySet(), anyMap());
        }

        @Test
        void shouldReturnImplementerOfSvnPostCommitHookAndPerformMaterialUpdate_WhenInvokingPostCommitHookMaterialUpdate() {
            final HashMap params = new HashMap();
            params.put(MaterialUpdateService.TYPE, "svn");
            when(goConfigService.isUserAdmin(username)).thenReturn(true);
            final CruiseConfig cruiseConfig = new BasicCruiseConfig(PipelineConfigMother.createGroup("groupName", "pipeline1", "pipeline2"));
            when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig);
            when(postCommitHookMaterialType.toType("svn")).thenReturn(validMaterialType);
            final PostCommitHookImplementer svnPostCommitHookImplementer = mock(PostCommitHookImplementer.class);
            final Material svnMaterial = mock(Material.class);
            when(svnPostCommitHookImplementer.prune(anySet(), eq(params))).thenReturn(new HashSet(Arrays.asList(svnMaterial)));
            when(validMaterialType.getImplementer()).thenReturn(svnPostCommitHookImplementer);

            service.notifyMaterialsForUpdate(username, params, result);

            verify(svnPostCommitHookImplementer).prune(anySet(), eq(params));
            Mockito.verify(queue, times(1)).post(matchMaterialUpdateMessage(svnMaterial));

            HttpLocalizedOperationResult acceptedResult = new HttpLocalizedOperationResult();
            acceptedResult.accepted("The material is now scheduled for an update. Please check relevant pipeline(s) for status.");

            assertThat(result).isEqualTo(acceptedResult);
        }

        @Test
        void shouldResolveSecretParamsInMaterials() {
            final HashMap params = new HashMap();
            params.put(MaterialUpdateService.TYPE, "svn");
            final PostCommitHookImplementer svnPostCommitHookImplementer = mock(PostCommitHookImplementer.class);
            final SvnMaterial svnMaterial = new SvnMaterial("http://{{SECRET:[config_id][username]}}@url.com", "bob", "badger", false);

            when(goConfigService.currentCruiseConfig()).thenReturn(mock(CruiseConfig.class));
            when(goConfigService.isUserAdmin(username)).thenReturn(true);
            when(postCommitHookMaterialType.toType("svn")).thenReturn(validMaterialType);
            when(validMaterialType.getImplementer()).thenReturn(svnPostCommitHookImplementer);
            when(materialConfigConverter.toMaterials(anySet())).thenReturn(Collections.singleton(svnMaterial));

            service.notifyMaterialsForUpdate(username, params, result);

            final ArgumentCaptor<SecretParams> secretParamsArgumentCaptor = ArgumentCaptor.forClass(SecretParams.class);
            InOrder inOrder = inOrder(secretParamResolver, svnPostCommitHookImplementer);
            inOrder.verify(secretParamResolver).resolve(secretParamsArgumentCaptor.capture());
            inOrder.verify(svnPostCommitHookImplementer).prune(Collections.singleton(svnMaterial), params);

            final SecretParams secretParams = secretParamsArgumentCaptor.getValue();
            assertThat(secretParams).hasSize(1)
                    .contains(new SecretParam("config_id", "username"));
        }
    }

    @Test
    void shouldUpdateServerHealthMessageWhenHung() {
        //given
        service = spy(service);
        systemEnvironment.set(SystemEnvironment.MATERIAL_UPDATE_INACTIVE_TIMEOUT, 1);
        ProcessManager processManager = mock(ProcessManager.class);
        Material material = mock(Material.class);
        service.updateMaterial(material);
        when(service.getProcessManager()).thenReturn(processManager);
        when(material.getFingerprint()).thenReturn("fingerprint");
        when(material.getUriForDisplay()).thenReturn("uri");
        when(material.getLongDescription()).thenReturn("details to uniquely identify a material");
        when(material.isAutoUpdate()).thenReturn(true);
        when(processManager.getIdleTimeFor(new MaterialFingerprintTag("fingerprint"))).thenReturn(60010L);

        //when
        service.updateMaterial(material);

        //then
        verify(serverHealthService).removeByScope(HealthStateScope.forMaterialUpdate(material));
        ArgumentCaptor<ServerHealthState> argumentCaptor = ArgumentCaptor.forClass(ServerHealthState.class);
        verify(serverHealthService).update(argumentCaptor.capture());
        assertThat(argumentCaptor.getValue().getMessage()).isEqualTo("Material update for uri hung:");
        assertThat(argumentCaptor.getValue().getDescription()).isEqualTo("Material update is currently running but has not shown any activity in the last 1 minute(s). This may be hung. Details - details to uniquely identify a material");
        assertThat(argumentCaptor.getValue().getType()).isEqualTo(HealthStateType.general(HealthStateScope.forMaterialUpdate(material)));
    }

    @Test
    void shouldNotUpdateServerHealthMessageWhenIdleTimeLessThanConfigured() {
        //given
        service = spy(service);
        systemEnvironment.set(SystemEnvironment.MATERIAL_UPDATE_INACTIVE_TIMEOUT, 2);
        ProcessManager processManager = mock(ProcessManager.class);
        Material material = mock(Material.class);
        service.updateMaterial(material);
        when(service.getProcessManager()).thenReturn(processManager);
        when(material.getFingerprint()).thenReturn("fingerprint");
        when(processManager.getIdleTimeFor(new MaterialFingerprintTag("fingerprint"))).thenReturn(60010L);

        //when
        service.updateMaterial(material);

        //then
        verify(serverHealthService, never()).removeByScope(HealthStateScope.forMaterialUpdate(material));
        verify(serverHealthService, never()).update(any(ServerHealthState.class));
    }

    @Test
    void shouldRemoveServerHealthMessageOnMaterialUpdateCompletion() {
        Material material = mock(Material.class);
        when(material.getFingerprint()).thenReturn("fingerprint");

        service.onMessage(new MaterialUpdateCompletedMessage(material, 0));

        verify(serverHealthService).removeByScope(HealthStateScope.forMaterialUpdate(material));
    }

    @Test
    void shouldNotifyAllMaterialUpdateCompleteListenersOnMaterialUpdate() {
        Material material = mock(Material.class);

        service.onMessage(new MaterialUpdateCompletedMessage(material, 0));

        verify(dependencyMaterialUpdateNotifier).onMaterialUpdate(material);
        verify(scmMaterialSource).onMaterialUpdate(material);
    }

    @Test
    void shouldRemoveFromInProgressOnMaterialUpdateSkippedMessage() {
        when(scmMaterialSource.materialsForUpdate()).thenReturn(new HashSet<>(Arrays.asList(svnMaterial)));
        service.onTimer();

        assertThat(service.isInProgress(svnMaterial)).isTrue();

        service.onMessage(new MaterialUpdateSkippedMessage(svnMaterial, 0));

        assertThat(service.isInProgress(svnMaterial)).isFalse();
    }

    @Test
    void shouldNotRemoveServerHealthMessageOnMaterialUpdateSkippedMessage() {
        Material material = mock(Material.class);
        when(material.getFingerprint()).thenReturn("fingerprint");

        service.onMessage(new MaterialUpdateSkippedMessage(material, 0));

        verifyZeroInteractions(serverHealthService);
    }

    @Test
    void shouldNotNotifyAllMaterialUpdateCompleteListenersOnMaterialUpdateSkippedMessage() {
        Material material = mock(Material.class);

        service.onMessage(new MaterialUpdateSkippedMessage(material, 0));

        verifyZeroInteractions(dependencyMaterialUpdateNotifier);
        verifyZeroInteractions(scmMaterialSource);
    }

    @Test
    void shouldMaterialUpdateShouldNotBeInProgressIfUpdateMaterialMessagePostFails() {
        doThrow(new RuntimeException("failed")).when(queue).post(matchMaterialUpdateMessage(svnMaterial));
        try {
            service.updateMaterial(svnMaterial);
            fail("Should have failed");
        } catch (RuntimeException e) {
            // should re-throw exception
        }
        Map<Material, Date> inProgress = (Map<Material, Date>) ReflectionUtil.getField(service, "inProgress");
        assertThat(inProgress.containsKey(svnMaterial)).isFalse();
    }
}


text:
require 'spec_helper'

describe "schools/edit" do
  before(:each) do
    @school = assign(:school, stub_model(School))
  end

  it "renders the edit school form" do
    render

    # Run the generator again with the --webrat flag if you want to use webrat matchers
    assert_select "form[action=?][method=?]", school_path(@school), "post" do
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.tinkerrocks.structure;

import com.tinkerrocks.storage.StorageConstants;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.io.FileUtils;
import org.apache.tinkerpop.gremlin.AbstractGraphProvider;
import org.apache.tinkerpop.gremlin.LoadGraphWith;
import org.apache.tinkerpop.gremlin.structure.Graph;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class RocksGraphProvider extends AbstractGraphProvider {
    HashMap<String, RocksGraph> paths = new HashMap<>();

    @Override
    public Graph openTestGraph(Configuration config) {
        String path = StorageConstants.TEST_DATABASE_PREFIX + "/" + UUID.randomUUID().toString();
        try {
            FileUtils.forceMkdir(new File(path));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        Configuration configuration = new BaseConfiguration();
        configuration.addProperty(StorageConstants.STORAGE_DIR_PROPERTY, path);

        try {
            RocksGraph graph = RocksGraph.open(configuration);
            paths.put(path, graph);
            return graph;

        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, Object> getBaseConfiguration(String s, Class<?> aClass, String s1, LoadGraphWith.GraphData graphData) {

        return new HashMap<String, Object>() {{
            put(Graph.GRAPH, RocksGraph.class.getName());
        }};
        //return new HashMap<String, Object>();
    }

    @Override
    public void clear(Graph graph, Configuration configuration) throws Exception {
        for (Map.Entry<String, RocksGraph> path : paths.entrySet()) {
            //System.out.println("cleaning up dir:" + path);
            FileUtils.deleteDirectory(new File(path.getKey()));
            path.getValue().close();
        }
    }

    @Override
    public Set<Class> getImplementations() {

        return new HashSet<Class>() {{
            add(RocksEdge.class);
            add(RocksElement.class);
            //add(RocksGraph.class);
            add(RocksProperty.class);
            add(RocksVertex.class);
            add(RocksVertexProperty.class);
        }};
    }
}


text:
package dydeve.db.strategy;

import java.util.List;
import java.util.function.Supplier;

/**
 * Created by dy on 2017/8/31.
 */
public class LoadBalanceStrategyFactory<S, T extends LoadBalanceStrategy<S>> {

    public T generate(List<S> sources, Supplier<T> supplier) {
        if (sources == null || sources.isEmpty()) {
            throw new IllegalArgumentException("source can't be empty");
        }
        if (sources.size() == 1) {
            return (T) new SingleLoadBalanceStrategy(sources);
        }
        return supplier.get();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Runtime.Serialization;

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MyAccessStatistics.Model
{

    /// <summary>
    /// 访问汇总.
    /// </summary>
    [Serializable]
    [DataContract(Namespace = "")]
    [Table("mas_access_type_summary")]
    public class AccessTypeSummary
    {

        #region 一对多.

        /// <summary>
        /// 访问类型代码.
        /// </summary>
        [DataMember]
        [Column("access_type_code")]
        [Display(Name = "访问类型代码")]
        [StringLength(32)]
        public string AccessTypeCode { set; get; }

        /// <summary>
        /// 访问类型数据.
        /// </summary>
        public virtual AccessType AccessTypeData { set; get; }

        #endregion 一对多.

        /// <summary>
        /// 访问日期.
        /// </summary>
        [DataMember]
        [Column("access_date")]
        [Display(Name = "访问日期")]
        public DateTime AccessDate { set; get; }

        /// <summary>
        /// 访问次数
        /// </summary>
        [DataMember]
        [Column("access_count")]
        [Display(Name = "访问次数")]
        public int AccessCount { set; get; }

    }

}


text:
using LoT.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LoT.IDal
{
    /// <summary>
    /// 管理员权限表
    /// </summary>
    public interface IActionInfoDal : IBaseDal<ActionInfo>
    {
    }
}


text:
import logging
import threading
from concurrent import futures
from multiprocessing import pool

from opencensus.trace import execution_context, tracer
from opencensus.trace.propagation import binary_format

log = logging.getLogger(__name__)

MODULE_NAME = "threading"

def trace_integration(tracer=None):
    """Wrap threading functions to trace."""
    log.info("Integrated module: {}".format(MODULE_NAME))
    # Wrap the threading start function
    start_func = getattr(threading.Thread, "start")
    setattr(
        threading.Thread, start_func.__name__, wrap_threading_start(start_func)
    )

    # Wrap the threading run function
    run_func = getattr(threading.Thread, "run")
    setattr(threading.Thread, run_func.__name__, wrap_threading_run(run_func))

    # Wrap the threading run function
    apply_async_func = getattr(pool.Pool, "apply_async")
    setattr(
        pool.Pool,
        apply_async_func.__name__,
        wrap_apply_async(apply_async_func),
    )

    # Wrap the threading run function
    submit_func = getattr(futures.ThreadPoolExecutor, "submit")
    setattr(
        futures.ThreadPoolExecutor,
        submit_func.__name__,
        wrap_submit(submit_func),
    )

def wrap_threading_start(start_func):
    """Wrap the start function from thread. Put the tracer informations in the
    threading object.
    """

    def call(self):
        self._opencensus_context = (
            execution_context.get_opencensus_full_context()
        )
        return start_func(self)

    return call

def wrap_threading_run(run_func):
    """Wrap the run function from thread. Get the tracer informations from the
    threading object and set it as current tracer.
    """

    def call(self):
        execution_context.set_opencensus_full_context(
            *self._opencensus_context
        )
        return run_func(self)

    return call

def wrap_apply_async(apply_async_func):
    """Wrap the apply_async function of multiprocessing.pools. Get the function
    that will be called and wrap it then add the opencensus context."""

    def call(self, func, args=(), kwds={}, **kwargs):
        wrapped_func = wrap_task_func(func)
        _tracer = execution_context.get_opencensus_tracer()
        propagator = binary_format.BinaryFormatPropagator()

        wrapped_kwargs = {}
        wrapped_kwargs["span_context_binary"] = propagator.to_header(
            _tracer.span_context
        )
        wrapped_kwargs["kwds"] = kwds
        wrapped_kwargs["sampler"] = _tracer.sampler
        wrapped_kwargs["exporter"] = _tracer.exporter
        wrapped_kwargs["propagator"] = _tracer.propagator

        return apply_async_func(
            self, wrapped_func, args=args, kwds=wrapped_kwargs, **kwargs
        )

    return call

def wrap_submit(submit_func):
    """Wrap the apply_async function of multiprocessing.pools. Get the function
    that will be called and wrap it then add the opencensus context."""

    def call(self, func, *args, **kwargs):
        wrapped_func = wrap_task_func(func)
        _tracer = execution_context.get_opencensus_tracer()
        propagator = binary_format.BinaryFormatPropagator()

        wrapped_kwargs = {}
        wrapped_kwargs["span_context_binary"] = propagator.to_header(
            _tracer.span_context
        )
        wrapped_kwargs["kwds"] = kwargs
        wrapped_kwargs["sampler"] = _tracer.sampler
        wrapped_kwargs["exporter"] = _tracer.exporter
        wrapped_kwargs["propagator"] = _tracer.propagator

        return submit_func(self, wrapped_func, *args, **wrapped_kwargs)

    return call

class wrap_task_func(object):
    """Wrap the function given to apply_async to get the tracer from context,
    execute the function then clear the context."""

    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        kwds = kwargs.pop("kwds")

        span_context_binary = kwargs.pop("span_context_binary")
        propagator = binary_format.BinaryFormatPropagator()
        kwargs["span_context"] = propagator.from_header(span_context_binary)

        _tracer = tracer.Tracer(**kwargs)
        execution_context.set_opencensus_tracer(_tracer)
        with _tracer.span(name=threading.current_thread().name):
            result = self.func(*args, **kwds)
        execution_context.clean()
        return result


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="feedback_screenshot">Screenshot</string>
    <string name="feedback_content_hint">Hier Feedback hinterlassen</string>
    <string name="feedback_include_system_info_title">Screenshot und Protokolle hinzufügen</string>
    <string name="feedback_touch_to_preview">Inhalt markieren und verbergen</string>
    <string name="feedback_send_feedback">Senden</string>
    <string name="feedback_validate_must_not_be_blank">Darf nicht leer sein</string>
    <string name="feedback_highlight">Markieren</string>
    <string name="feedback_blackout">Schwärzen</string>
    <string name="feedback_undo">Zurück</string>
    <string name="feedback_save">Speichern</string>
    <string name="feedback_screenshot_informational_text">Ihre Systeminformationen werden gesendet.</string>
    <string name="feedback_screenshot_preview">Vorschau</string>
  <string name="feedback_action_feedback">Feedback</string>
</resources>


text:
var Game = require('../schemas/gameSchema');
var User = require('../schemas/userSchema');
var Deferred = require('promised-io').Deferred;
var serverConstants = require('../constants/application');
var _ = require('underscore');
var mongoose = require('mongoose');

var _getGame = function(gameId) {
    'use strict';
    var deferred = new Deferred();
    Game.findById(gameId, function (error, game) {
        if (error || !game) {
            deferred.reject(serverConstants.CODE['500']);
        } else {
            deferred.resolve(game);
        }
    });
    return deferred.promise;
};

var _createGame = function (userId, _game) {
    'use strict';
    var deferred = new Deferred();
    var game = new Game({
        houseName: _game.houseName
    });
    User.findById(userId, function (error, user) {
        if(error) {
            deferred.reject(serverConstants.CODE['500']);
        } else if (!user) {
            deferred.reject(serverConstants.CODE['500']);
        } else {
            game.save(function (error, game) {
                if (error) {
                    deferred.reject(serverConstants.CODE['500']);
                } else {
                    user.update({ $set: {gameId: game._id}}, function (error) {
                        if (error) {
                            deferred.reject(serverConstants.CODE['500']);
                        } else {
                            deferred.resolve();
                        }
                    });
                }
            });
        }
    });
    return deferred.promise;
};

var _modifyGame = function (gameId, _game) {
    'use strict';
    var deferred = new Deferred();
    Game.findById(gameId, function (error, game) {
        if(error) {
            deferred.reject(serverConstants.CODE['500']);
        } else if(game === null) {
            deferred.reject(serverConstants.CODE['500']);
        } else  {
            var keyUser = Object.keys(_game),
                gameUpdate = {$set:{}};
            _.each(keyUser, function (key) {
                gameUpdate['$set'][key] = _game[key];
            });
            game.update(gameUpdate, function (error, gameUpdated) {
                if (error) {
                    deferred.reject(serverConstants.CODE['500']);
                } else {
                    deferred.resolve(gameUpdated._id);
                }
            });
        }
    });
    return deferred.promise;
};

var _removeGame = function (gameId) {
    'use strict';
    var deferred = new Deferred();
    Game.findById(gameId, function (error, game) {
        if(error) {
            deferred.reject(serverConstants.CODE['500']);
        } else if(game === null) {
            deferred.reject(serverConstants.CODE['500']);
        } else  {
            Game.remove({_id: mongoose.Types.ObjectId(gameId)}, function (error) {
                if (error) {
                    deferred.reject(serverConstants.CODE['500']);
                } else {
                    deferred.resolve();
                }
            });
        }
    });
    return deferred.promise;
};

module.exports = {
    getGame: _getGame,
    createGame: _createGame,
    modifyGame: _modifyGame,
    removeGame: _removeGame
};


text:
ACCEPTED

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

#### Published in
Proc. Amer. Acad. Arts & Sci. 160 (1893)

#### Original name
Haplomyces texanus Thaxt., 1893

### Remarks
null


text:
<?php

namespace Oro\Bundle\GridBundle\Action;

class RedirectAction extends AbstractAction
{
    /**
     * @var string
     */
    protected $type = self::TYPE_REDIRECT;

    /**
     * @var array
     */
    protected $requiredOptions = array('link');
}


text:
ERR WriteContainerPre(
    PKImageEncode* pIE);

ERR WriteContainerPost(
    PKImageEncode* pIE);

ERR PKImageEncode_Transcode_WMP(
    PKImageEncode* pIE,
    PKImageDecode* pID,
    CWMTranscodingParam* pParam)
{
    ERR err = WMP_errSuccess;
    Float fResX = 0, fResY = 0;
    PKPixelFormatGUID pixGUID = {0};
    CWMTranscodingParam tcParamAlpha;
    size_t offPos = 0;
    Bool fPlanarAlpha;
    PKPixelInfo PI;

    struct WMPStream* pWSDec = NULL;
    struct WMPStream* pWSEnc= pIE->pStream;

    // pass through metadata
    Call(pID->GetPixelFormat(pID, &pixGUID));
    Call(pIE->SetPixelFormat(pIE, pixGUID));

    Call(pIE->SetSize(pIE, (I32)pParam->cWidth, (I32)pParam->cHeight));

    Call(pID->GetResolution(pID, &fResX, &fResY));
    Call(pIE->SetResolution(pIE, fResX, fResY));

    PI.pGUIDPixFmt = &pIE->guidPixFormat;
    PixelFormatLookup(&PI, LOOKUP_FORWARD);
    pIE->WMP.bHasAlpha = !!(PI.grBit & PK_pixfmtHasAlpha) && (2 == pParam->uAlphaMode);
    assert(0 == pIE->WMP.bHasAlpha || (pParam->uAlphaMode == 2)); // Decode alpha mode does not match encode alpha mode!

    // Check for any situations where transcoder is being asked to convert alpha - we can't do this
    // NOTE: Decoder's bHasAlpha parameter really means, "has PLANAR alpha"
    PI.pGUIDPixFmt = &pixGUID;
    PixelFormatLookup(&PI, LOOKUP_FORWARD);
    FailIf(0 == (PI.grBit & PK_pixfmtHasAlpha) && pParam->uAlphaMode != 0,
        WMP_errAlphaModeCannotBeTranscoded); // Destination is planar/interleaved, src has no alpha
    FailIf(!!(PI.grBit & PK_pixfmtHasAlpha) && 2 == pParam->uAlphaMode &&
        FALSE == pID->WMP.bHasAlpha, WMP_errAlphaModeCannotBeTranscoded);  // Destination is planar, src is interleaved
    FailIf(!!(PI.grBit & PK_pixfmtHasAlpha) && 3 == pParam->uAlphaMode &&
        pID->WMP.bHasAlpha, WMP_errAlphaModeCannotBeTranscoded);  // Destination is interleaved, src is planar
    assert(//pParam->uAlphaMode >= 0 &&
        pParam->uAlphaMode <= 3); // All the above statements make this assumption

    fPlanarAlpha = pIE->WMP.bHasAlpha && (2 == pParam->uAlphaMode);

    // write matadata
    Call(WriteContainerPre(pIE));

    // Copy transcoding params for alpha (codec changes the struct)
    if (fPlanarAlpha)
        tcParamAlpha = *pParam;

    // write compressed bitstream
    Call(pID->GetRawStream(pID, &pWSDec));

    /////////////////////
    pParam->uImageOffset = pID->WMP.wmiDEMisc.uImageOffset;
    pParam->uImageByteCount = pID->WMP.wmiDEMisc.uImageByteCount;
    ////////////

    FailIf(ICERR_OK != WMPhotoTranscode(pWSDec, pWSEnc, pParam), WMP_errFail);
    Call(pIE->pStream->GetPos(pIE->pStream, &offPos));
    pIE->WMP.nCbImage = (Long)offPos - pIE->WMP.nOffImage;

    if (fPlanarAlpha)
    {
        /////////////////////
        pParam->uImageOffset = pID->WMP.wmiDEMisc.uAlphaOffset;
        pParam->uImageByteCount = pID->WMP.wmiDEMisc.uAlphaByteCount;
        ////////////

        pIE->WMP.nOffAlpha = (Long)offPos;

        // Cue the stream to alpha block
        assert(pID->WMP.wmiDEMisc.uAlphaOffset > 0);
        Call(pWSDec->SetPos(pWSDec, pID->WMP.wmiDEMisc.uAlphaOffset));

        FailIf(ICERR_OK != WMPhotoTranscode(pWSDec, pWSEnc, &tcParamAlpha), WMP_errFail);
        Call(pIE->pStream->GetPos(pIE->pStream, &offPos));
        pIE->WMP.nCbAlpha = (Long)offPos - pIE->WMP.nOffAlpha;
    }

    // fixup matadata
    Call(WriteContainerPost(pIE));

Cleanup:
    return err;
}


text:
/* eslint-disable import/no-unresolved */

import renderPDF from '~/blob/pdf';
import testPDF from '../../fixtures/blob/pdf/test.pdf';

describe('PDF renderer', () => {
  let viewer;
  let app;

  const checkLoaded = (done) => {
    if (app.loading) {
      setTimeout(() => {
        checkLoaded(done);
      }, 100);
    } else {
      done();
    }
  };

  preloadFixtures('static/pdf_viewer.html.raw');

  beforeEach(() => {
    loadFixtures('static/pdf_viewer.html.raw');
    viewer = document.getElementById('js-pdf-viewer');
    viewer.dataset.endpoint = testPDF;
  });

  it('shows loading icon', () => {
    renderPDF();

    expect(
      document.querySelector('.loading'),
    ).not.toBeNull();
  });

  describe('successful response', () => {
    beforeEach((done) => {
      app = renderPDF();

      checkLoaded(done);
    });

    it('does not show loading icon', () => {
      expect(
        document.querySelector('.loading'),
      ).toBeNull();
    });

    it('renders the PDF', () => {
      expect(
        document.querySelector('.pdf-viewer'),
      ).not.toBeNull();
    });

    it('renders the PDF page', () => {
      expect(
        document.querySelector('.pdf-page'),
      ).not.toBeNull();
    });
  });

  describe('error getting file', () => {
    beforeEach((done) => {
      viewer.dataset.endpoint = 'invalid/path/to/file.pdf';
      app = renderPDF();

      checkLoaded(done);
    });

    it('does not show loading icon', () => {
      expect(
        document.querySelector('.loading'),
      ).toBeNull();
    });

    it('shows error message', () => {
      expect(
        document.querySelector('.md').textContent.trim(),
      ).toBe('An error occured whilst loading the file. Please try again later.');
    });
  });
});


text:
package stroom.widget.tickbox.client.view;

import stroom.cell.tickbox.shared.TickBoxState;
import stroom.util.shared.HasBooleanValue;
import stroom.widget.util.client.MouseUtil;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Focus;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

public class TickBox extends Composite
        implements HasValue<TickBoxState>, HasValueChangeHandlers<TickBoxState>, HasBooleanValue, Focus {

    private static volatile Binder binder;
    @UiField
    FlowPanel layout;
    @UiField
    Button image;
    Label lblText;
    private TickBoxState state = TickBoxState.TICK;
    private boolean enabled = true;

    public TickBox() {
        this(TickBoxState.UNTICK, null);
    }

    public TickBox(final String text) {
        this(TickBoxState.UNTICK, text);
    }

    public TickBox(final TickBoxState state, final String text) {
        if (binder == null) {
            synchronized (TickBox.class) {
                if (binder == null) {
                    binder = GWT.create(Binder.class);
                }
            }
        }

        initWidget(binder.createAndBindUi(this));
        sinkEvents(Event.MOUSEEVENTS);

        setValue(state);

        if (text != null) {
            lblText = new Label(text, false);
            lblText.setStyleName("tickBox-text");
            layout.add(lblText);
        }

        image.getElement().setAttribute("role", "tickbox");
    }

    @Override
    public void focus() {
        image.setFocus(true);
    }

    @Override
    public HandlerRegistration addValueChangeHandler(final ValueChangeHandler<TickBoxState> handler) {
        return addHandler(handler, ValueChangeEvent.getType());
    }

    @Override
    public Boolean getBooleanValue() {
        if (TickBoxState.TICK.equals(state)) {
            return true;
        }
        if (TickBoxState.UNTICK.equals(state)) {
            return false;
        }
        return null;
    }

    @Override
    public void setBooleanValue(final Boolean value) {
        if (value != null) {
            setBooleanValue(value, false);
        }
    }

    public void setBooleanValue(final boolean value, final boolean fireEvents) {
        if (value) {
            setValue(TickBoxState.TICK, fireEvents);
        } else {
            setValue(TickBoxState.UNTICK, fireEvents);
        }
    }

    @Override
    public TickBoxState getValue() {
        return state;
    }

    @Override
    public void setValue(final TickBoxState value) {
        setValue(value, false);
    }

    @Override
    public void setValue(final TickBoxState value, final boolean fireEvents) {
        if (this.state != value) {
            this.state = value;

            updateImage();

            if (fireEvents) {
                ValueChangeEvent.fire(this, state);
            }
        }
    }

    private void updateImage() {
        switch (state) {
            case TICK:
                if (enabled) {
                    image.getElement().setClassName("form-check-input flatButton tickBox-tick");
                } else {
                    image.getElement().setClassName("form-check-input flatButton tickBox-tick tickBox-disabled");
                }
                break;
            case HALF_TICK:
                if (enabled) {
                    image.getElement().setClassName("form-check-input flatButton tickBox-halfTick");
                } else {
                    image.getElement().setClassName("form-check-input flatButton tickBox-halfTick tickBox-dDisabled");
                }
                break;
            case UNTICK:
                if (enabled) {
                    image.getElement().setClassName("form-check-input flatButton tickBox-untick");
                } else {
                    image.getElement().setClassName("form-check-input flatButton tickBox-untick tickBox-disabled");
                }
                break;
        }
    }

    @Override
    public void onBrowserEvent(final Event event) {
        final Element target = DOM.eventGetTarget(event);

        if (enabled && event.getTypeInt() == Event.ONMOUSEDOWN
                && MouseUtil.isPrimary(event)
                && getElement().isOrHasChild(target)) {
            if (state == TickBoxState.TICK) {
                setValue(TickBoxState.UNTICK, true);
            } else {
                setValue(TickBoxState.TICK, true);
            }
        }
    }

    public String getText() {
        if (lblText == null) {
            return null;
        }

        return lblText.getText();
    }

    public void setText(final String text) {
        if (text != null) {
            if (lblText == null) {
                lblText = new Label(text, false);
                lblText.setStyleName("tickBox-text");
                layout.add(lblText);
            } else {
                lblText.setText(text);
            }
        }
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(final boolean enabled) {
        this.enabled = enabled;
        updateImage();
    }

    public interface Binder extends UiBinder<Widget, TickBox> {

    }
}


text:
package com.krishagni.catissueplus.core.biospecimen.events;

import java.util.List;

public class UpdateFolderCartsOp {
	public enum Operation {
		ADD,
		REMOVE
	};

	private Long folderId;

	private List<Long> cartIds;

	private Operation op;

	public Long getFolderId() {
		return folderId;
	}

	public void setFolderId(Long folderId) {
		this.folderId = folderId;
	}

	public List<Long> getCartIds() {
		return cartIds;
	}

	public void setCartIds(List<Long> cartIds) {
		this.cartIds = cartIds;
	}

	public Operation getOp() {
		return op;
	}

	public void setOp(Operation op) {
		this.op = op;
	}
}


text:
<?php

require_once('include/plugin.php');

head_add_css('library/fancybox/jquery.fancybox-1.3.4.css');
head_add_css('library/tiptip/tipTip.css');
head_add_css('library/jgrowl/jquery.jgrowl.css');
head_add_css('library/jslider/css/jslider.css');
head_add_css('library/prettyphoto/css/prettyPhoto.css');
head_add_css('library/colorbox/colorbox.css');

head_add_js('js/jquery.js');
head_add_js('js/jquery-migrate-1.1.1.js');
head_add_js('js/spin.js');
head_add_js('js/jquery.spin.js');
head_add_js('js/jquery.textinputs.js');
head_add_js('js/fk.autocomplete.js');
head_add_js('library/fancybox/jquery.fancybox-1.3.4.js');
head_add_js('library/jquery.timeago.js');
head_add_js('library/jquery.divgrow/jquery.divgrow-1.3.1.js');
head_add_js('library/jquery_ac/friendica.complete.js');
head_add_js('library/tiptip/jquery.tipTip.minified.js');
head_add_js('library/jgrowl/jquery.jgrowl_minimized.js');
head_add_js('library/tinymce/jscripts/tiny_mce/tiny_mce_src.js');
head_add_js('js/acl.js');
head_add_js('js/webtoolkit.base64.js');
head_add_js('js/main.js');
head_add_js('library/jslider/bin/jquery.slider.min.js');
head_add_js('docready.js');
head_add_js('library/prettyphoto/js/jquery.prettyPhoto.js');
head_add_js('library/colorbox/jquery.colorbox-min.js');


text:
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300,800,700,400,600' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="/loginPortalAssets/css/loginPortalStyle.css">
    <title>College Profile | OASIS 2014 | That 90s Show</title>

CLOSE

ADD A NEW PARTICIPANT !

			        <form id="addParticipantForm" class="addParticipantForm" >
                        <input id="glid" name="gl_id" hidden value="{{gl_profile.id}}">

			                        Participant Name :

<input type="text" name="name" id="a_name" style="width:270px" class="inp_neo">

			                        Phone No :

<input type="text" name="contact" id="a_contact" style="margin-bottom:3px;width:300px" class="inp_neo">

			                        Email ID :

<input type="text" name="email" id="a_email" style="width:300px" class="inp_neo">

			                        Gender :

<input type="radio" id="a_gender" name="gender" value="male">    Male        <input type="radio" id="a_gender" name="gender" value="female">    Female

                                    Events :

                                        {% for c in category_name_list %}

{{c}}

                                        {% for z in event_list %}{% if z.category.name == c %}<input type="checkbox" id="eventList" name="eventList" value="{{z.id}}">{{z.name}}

                                        {% endif %}{% endfor %}{% endfor %}

			        </form>
			        <button id="newParticipantSubmit">Submit</button>

ADD A NEW COACH !

                    <form id="addCoachForm" class="addParticipantForm" >
                        <input id="glid" name="gl_id" hidden value="{{gl_profile.id}}">

                                    Coach Name :

<input type="text" name="name" id="c_name" style="width:270px" class="inp_neo">

                                    Phone No :

<input type="text" name="contact" id="c_contact" style="margin-bottom:3px;width:300px" class="inp_neo">

                                    Email ID :

<input type="text" name="email" id="c_email" style="width:300px" class="inp_neo">

                                    Gender :

<input type="radio" id="c_gender" name="gender" value="male">    Male        <input type="radio" id="c_gender" name="gender" value="female">    Female

                    </form>
                    <button id="newCoachSubmit">Submit</button>

EDIT SUNBURN TICKETS !

                    <form id="addSunburnForm" class="addParticipantForm" >
                        <input id="glid" name="gl_id" hidden value="{{gl_profile.id}}">

                                    No. of Sunburn Tickets :

<input type="text" name="sticket" id="sticket" style="margin-bottom:3px;width:300px" class="inp_neo">

                    </form>
                    <button id="newSunburnSubmit">Submit</button>

 OASIS 2014
REGISTRATION PORTAL

        LOGOUT

GROUP LEADER
{{ gl_profile.name }}

COLLEGE
{{ gl_profile.college }}

CITY
{{ gl_profile.city }}

NO. OF SUNBURN TICKETS SIGNED
{{gl_profile.stickets}}

Click to Edit Sunburn Tickets

	<button id="addParticipant" >ADD PARTICIPANT</button>
    <button id="addCoach" >ADD COACH</button>


text:
package com.itachi1706.cheesecakeutilities.modules.vehicleMileageTracker;

import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.LongSparseArray;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.Query;
import com.itachi1706.helperlib.helpers.PrefHelper;
import com.itachi1706.cheesecakeutilities.modules.vehicleMileageTracker.objects.Record;
import com.itachi1706.cheesecakeutilities.R;
import com.itachi1706.cheesecakeutilities.util.FirebaseValueEventListener;
import com.itachi1706.helperlib.helpers.LogHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static com.itachi1706.cheesecakeutilities.modules.vehicleMileageTracker.VehMileageFirebaseUtils.MILEAGE_DEC;
import static com.itachi1706.cheesecakeutilities.util.FirebaseUtils.Companion;

public class GenerateMileageRecordActivity extends AppCompatActivity {

    private TableLayout layout;
    private Spinner monthSel;
    private HorizontalScrollView hScroll;
    private ScrollView vScroll;

    private String user_id;
    private int maxPerRecord;
    private boolean decimal;
    private LongSparseArray<String> monthData = null;

    private static final String TAG = "GenerateMileageRec";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_generate_mileage_record);

        layout = findViewById(R.id.veh_mileage_table);
        hScroll = findViewById(R.id.hscroll);
        vScroll = findViewById(R.id.vscroll);

        SharedPreferences sp = PrefHelper.getDefaultSharedPreferences(this);
        maxPerRecord = Integer.parseInt(sp.getString("veh_mileage_report_rows", "38"));
        user_id = VehMileageFirebaseUtils.getFirebaseUIDFromSharedPref(sp);
        decimal = sp.getBoolean(MILEAGE_DEC, true);
        if (user_id.equalsIgnoreCase("nien")) {
            // Fail, return to login activity
            Toast.makeText(this, "Invalid Login Token, please re-login", Toast.LENGTH_SHORT).show();
        }
    }

    private float mx, my;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float curX, curY;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mx = event.getX();
                my = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                curX = event.getX();
                curY = event.getY();
                vScroll.scrollBy((int) (mx - curX), (int) (my - curY));
                hScroll.scrollBy((int) (mx - curX), (int) (my - curY));
                mx = curX;
                my = curY;
                break;
            case MotionEvent.ACTION_UP:
                curX = event.getX();
                curY = event.getY();
                vScroll.scrollBy((int) (mx - curX), (int) (my - curY));
                hScroll.scrollBy((int) (mx - curX), (int) (my - curY));
                break;
            default:
                LogHelper.e(TAG, "Invalid case");
                break;
        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.modules_veh_mileage_generate_report, menu);
        MenuItem menuItem = menu.findItem(R.id.menuMonth);
        monthSel = (Spinner) menuItem.getActionView();

        VehMileageFirebaseUtils.getVehicleMileageDatabase().child("users").child(user_id).child("statistics")
                .child("timeRecords").child("perMonth").addListenerForSingleValueEvent(new FirebaseValueEventListener(TAG, "loadMileageRecords") {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                monthData = new LongSparseArray<>();
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    long key = Long.parseLong(ds.getKey());
                    Date d = new Date(key);
                    SimpleDateFormat sd = new SimpleDateFormat("MMMM yyyy", Locale.US);
                    monthData.put(key, sd.format(d));
                }
                LogHelper.d(TAG, "Month Data Size: " + monthData.size());
                List<String> tmp = new ArrayList<>();
                for (int i = 0; i < monthData.size(); i++) {
                    tmp.add(monthData.valueAt(i));
                }

                ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.simple_spinner_item_white, tmp);
                spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                monthSel.setAdapter(spinnerAdapter);
                monthSel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view1, int position, long id) {
                        if (position >= monthData.size()) {
                            // Error
                            LogHelper.e(TAG, "Position #" + position + " exceeds dataset size of " + monthData.size());
                            return;
                        }
                        long date = monthData.keyAt(position);
                        processDate(date);
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        // Unused
                    }
                });
            }
        });
        return true;
    }

    private void processDate(long date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(date));
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY));
        cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
        cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
        cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
        long startDate = cal.getTimeInMillis();
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
        cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
        cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
        cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
        long endDate = cal.getTimeInMillis();

        Query specificMonth = VehMileageFirebaseUtils.getVehicleMileageDatabase().child("users").child(user_id).child("records")
                .orderByChild("datetimeFrom").startAt(startDate).endAt(endDate);
        specificMonth.addListenerForSingleValueEvent(new FirebaseValueEventListener(TAG, "getRecords") {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                final List<Record> records = new ArrayList<>();
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    Record recList = ds.getValue(Record.class);
                    // Update records
                    if (recList == null || recList.getTrainingMileage()) continue;
                    records.add(recList);
                }
                LogHelper.i(TAG, "Records: " + records.size());
                processRecordsGeneral(records);
            }
        });
    }

    private double totalC3 = 0, totalC4 = 0;

    private void processRecordsGeneral(List<Record> records) {
        layout.removeAllViews();
        List<List<Record>> tmp = new ArrayList<>();
        List<Record> tmpRec = records;
        LogHelper.d(TAG, "Size check, Size: " + tmpRec.size() + " | Max: " + maxPerRecord);
        if (tmpRec.size() > maxPerRecord) {
            while (tmpRec.size() > maxPerRecord) {
                // Split records
                tmp.add(tmpRec.subList(0, maxPerRecord));
                tmpRec = tmpRec.subList(maxPerRecord, tmpRec.size());
            }
            tmp.add(tmpRec);
            LogHelper.d(TAG, "Total count of reports: " + tmp.size());
            int offsetMax = maxPerRecord + 2;
            for (int i = 0; i < tmp.size(); i++) {
                processRecords(tmp.get(i), i * offsetMax);
            }
        } else {
            processRecords(records, 0);
        }
    }

    private void processRecords(List<Record> records, int offset) {
        totalC4 = 0;
        totalC3 = 0;
        generateHeaders();
        int row = 1;
        for (Record r : records) {
            if (generateData(r, row, offset + row)) row++;
        }
        generateFooter(row);
        generateBlankRow(row + 1);
    }

    private void generateHeaders() {
        TableRow tr = new TableRow(this);
        tr.addView(getTextView(0, "S/N", true));
        tr.addView(getTextView(0, "DATE", true));
        tr.addView(getTextView(0, "VEHICLE NO", true));
        tr.addView(getTextView(0, "START", true));
        tr.addView(getTextView(0, "END", true));
        tr.addView(getTextView(0, "CLASS 3", true));
        tr.addView(getTextView(0, "CLASS 4", true));
        layout.addView(tr, getTblLayoutParams());
    }

    private boolean generateData(Record record, int sn, int col) {
        TableRow tr = new TableRow(this);
        tr.addView(getTextView(col, Integer.toString(sn)));
        // Process Date
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy", Locale.US);
        Date dt = new Date();
        dt.setTime(record.getDatetimeFrom());
        tr.addView(getTextView(col, sdf.format(dt)));
        tr.addView(getTextView(col, record.getVehicleNumber()));
        tr.addView(getTextView(col, Companion.parseData(record.getMileageFrom(), decimal)));
        tr.addView(getTextView(col, Companion.parseData(record.getMileageTo(), decimal)));
        if (record.getVehicleClass().equalsIgnoreCase("class3")) {
            tr.addView(getTextView(col, Companion.parseData(record.getTotalMileage(), decimal)));
            tr.addView(getTextView(col, "-"));
            totalC3 += record.getTotalMileage();
        } else if (record.getVehicleClass().equalsIgnoreCase("class4")) {
            tr.addView(getTextView(col, "-"));
            tr.addView(getTextView(col, Companion.parseData(record.getTotalMileage(), decimal)));
            totalC4 += record.getTotalMileage();
        } else return false;
        layout.addView(tr, getTblLayoutParams());
        return true;
    }

    private void generateFooter(int col) {
        TableRow tr = new TableRow(this);
        tr.addView(getTextView(col, ""));
        tr.addView(getTextView(col, ""));
        tr.addView(getTextView(col, ""));
        tr.addView(getTextView(col, ""));
        tr.addView(getTextView(col, "TOTAL", true));
        tr.addView(getTextView(col, Companion.parseData(totalC3, decimal)));
        tr.addView(getTextView(col, Companion.parseData(totalC4, decimal)));
        layout.addView(tr, getTblLayoutParams());
    }

    private void generateBlankRow(int col) {
        TableRow tr = new TableRow(this);
        tr.addView(getTextView(col, ""));
        tr.addView(getTextView(col, ""));
        tr.addView(getTextView(col, ""));
        tr.addView(getTextView(col, ""));
        tr.addView(getTextView(col, ""));
        tr.addView(getTextView(col, ""));
        tr.addView(getTextView(col, ""));
        layout.addView(tr, getTblLayoutParams());
    }

    private TextView getTextView(int id, String title) {
        return getTextView(id, title, false);
    }

    private TextView getTextView(int id, String title, boolean bold) {
        TextView tv = new TextView(this);
        tv.setId(id);
        tv.setText(title);
        if (bold) tv.setTypeface(null, Typeface.BOLD);
        tv.setTextColor(ContextCompat.getColor(getApplicationContext(), (PrefHelper.isNightModeEnabled(this)) ? R.color.white : R.color.black));
        tv.setPadding(40, 5, 40, 5);
        tv.setLayoutParams(getLayoutParams());
        return tv;
    }

    @NonNull
    private TableRow.LayoutParams getLayoutParams() {
        TableRow.LayoutParams params = new TableRow.LayoutParams(
                TableRow.LayoutParams.MATCH_PARENT,
                TableRow.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER_HORIZONTAL;
        params.setMargins(2, 0, 0, 2);
        return params;
    }

    @NonNull
    private TableLayout.LayoutParams getTblLayoutParams() {
        return new TableLayout.LayoutParams(
                TableLayout.LayoutParams.MATCH_PARENT,
                TableLayout.LayoutParams.WRAP_CONTENT);
    }
}


text:
<!DOCTYPE HTML>

<title>com.github.hypfvieh.dbus.examples.struct Class Hierarchy (dbus-java-examples 4.2.0 API)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-09-05">
<meta name="description" content="tree: package: com.github.hypfvieh.dbus.examples.struct">
<meta name="generator" content="javadoc/PackageTreeWriter">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../script-dir/jquery-ui.min.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../jquery-ui.overrides.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Index

Help

SEARCH:
<input type="text" id="search-input" value="search" disabled="disabled">
<input type="reset" id="reset-button" value="reset" disabled="disabled">

Hierarchy For Package com.github.hypfvieh.dbus.examples.struct

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.freedesktop.dbus.Container

org.freedesktop.dbus.Struct

com.github.hypfvieh.dbus.examples.struct.SampleStruct

com.github.hypfvieh.dbus.examples.struct.StructClient

com.github.hypfvieh.dbus.examples.struct.StructServer (implements com.github.hypfvieh.dbus.examples.struct.IStructServer)

Interface Hierarchy

org.freedesktop.dbus.interfaces.DBusInterface

com.github.hypfvieh.dbus.examples.struct.IStructServer

Copyright © 2022. All rights reserved.


text:
using System;
using System.Runtime.Serialization;

namespace Microsoft.PowerShell.CrossCompatibility.Data
{
    /// <summary>
    /// Describes a PowerShell runtime,
    /// as reported by $PSVersionTable.
    /// </summary>
    [Serializable]
    [DataContract]
    public class PowerShellData : ICloneable
    {
        /// <summary>
        /// The self-reported version of PowerShell.
        /// From $PSVersionTable.PSVersion.
        /// </summary>
        [DataMember]
        public PowerShellVersion Version { get; set; }

        /// <summary>
        /// The edition of PowerShell, from
        /// $PSVersionTable.PSEdition.
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string Edition { get; set; }

        /// <summary>
        /// The compatible downlevel versions
        /// of PowerShell, from $PSVersionTable.PSCompatibleVersions.
        /// </summary>
        [DataMember]
        public Version[] CompatibleVersions { get; set; }

        /// <summary>
        /// The PowerShell remoting protocol version supported,
        /// from $PSVersionTable.PSRemotingProtocolVersion.
        /// </summary>
        [DataMember]
        public Version RemotingProtocolVersion { get; set; }

        /// <summary>
        /// The PowerShell serialization protocol version
        /// supported, from $PSVersionTable.SerializationVersion.
        /// </summary>
        [DataMember]
        public Version SerializationVersion { get; set; }

        /// <summary>
        /// The supported WSMan stack version, from
        /// $PSVersionTable.WSManStackVersion.
        /// </summary>
        [DataMember]
        public Version WSManStackVersion { get; set; }

        /// <summary>
        /// The git commit ID of the PowerShell runtime
        /// if it differs from the reported PowerShell version.
        /// From $PSVersionTable.GitCommitId.
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string GitCommitId { get; set; }

        /// <summary>
        /// The machine architecture of the
        /// PowerShell runtime process.
        /// From System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture
        /// in .NET Core. Either X64 or X86 in .NET Framework.
        /// </summary>
        [DataMember]
        public Architecture ProcessArchitecture { get; set; }

        /// <summary>
        /// Create a deep clone of the PowerShell data object.
        /// </summary>
        public object Clone()
        {
            return new PowerShellData()
            {
                Edition = Edition,
                GitCommitId = GitCommitId,
                ProcessArchitecture = ProcessArchitecture,
                RemotingProtocolVersion = RemotingProtocolVersion,
                SerializationVersion = SerializationVersion,
                Version = Version,
                WSManStackVersion = WSManStackVersion,
                CompatibleVersions = (Version[])CompatibleVersions.Clone()
            };
        }
    }
}


text:
module Aerospike

  class Bin

    attr_accessor :name

    def initialize(bin_name, bin_value)
      @name = bin_name
      @value = Value.of(bin_value)
    end

    def value=(val)
      @value = Value.of(val)
    end

    def value
      @value.get if @value
    end

    def value_object
      @value
    end

    def type
      @value.type if @value
    end

    def to_s
      "#{@name}:#{@value.to_s}"
    end

  end # class

end # module


text:
import CUSTOMER_RETURN from './customer_return'

export default {
  customer_returns: [CUSTOMER_RETURN],
  count: 25,
  current_page: 1,
  pages: 5
}


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

/**
 * LineItemTemplate.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.admanager.axis.v202211;

/**
 * Represents the template that populates the fields of a new line
 * item being created.
 */
public class LineItemTemplate  implements java.io.Serializable {
    /* Uniquely identifies the {@code LineItemTemplate}. This attribute
     * is
     *                 read-only and is assigned by Google when a template
     * is created. */
    private java.lang.Long id;

    /* The name of the {@code LineItemTemplate}. This attribute is
     * required. */
    private java.lang.String name;

    /* Whether or not the {@code LineItemTemplate} represents the
     * default choices
     *                 for creating a {@code LineItem}. Only one default
     * {@code LineItemTemplate}
     *                 is allowed per {@code Network}. This attribute is
     * readonly. */
    private java.lang.Boolean isDefault;

    /* The default {@link LineItem#name name} of a new {@code LineItem}.
     * This
     *                 attribute is optional and has a maximum length of
     * 127 characters. */
    private java.lang.String lineItemName;

    /* The default value for the
     *                 {@link LineItem#enabledForSameAdvertiserException}
     * field of a new
     *                 {@code LineItem}. This attribute is required. */
    private java.lang.Boolean enabledForSameAdvertiserException;

    /* The default {@link LineItem#notes notes} for a new {@code LineItem}.
     * This
     *                 attribute is optional and has a maximum length of
     * 65,535 characters. */
    private java.lang.String notes;

    /* The default {@link LineItem#lineItemType type} of a new {@code
     * LineItem}.
     *                 This attribute is required. */
    private com.google.api.ads.admanager.axis.v202211.LineItemType lineItemType;

    /* The default {@link LineItem#deliveryRateType delivery strategy}
     * for a new
     *                 {@code LineItem}. This attribute is required. */
    private com.google.api.ads.admanager.axis.v202211.DeliveryRateType deliveryRateType;

    /* The default {@link LineItem#roadblockingType roadblocking strategy}
     * for a
     *                 new {@code LineItem}. This attribute is required. */
    private com.google.api.ads.admanager.axis.v202211.RoadblockingType roadblockingType;

    /* The default {@link LineItem#creativeRotationType creative rotation
     * strategy}
     *                 for a new {@code LineItem}. This attribute is required. */
    private com.google.api.ads.admanager.axis.v202211.CreativeRotationType creativeRotationType;

    public LineItemTemplate() {
    }

    public LineItemTemplate(
           java.lang.Long id,
           java.lang.String name,
           java.lang.Boolean isDefault,
           java.lang.String lineItemName,
           java.lang.Boolean enabledForSameAdvertiserException,
           java.lang.String notes,
           com.google.api.ads.admanager.axis.v202211.LineItemType lineItemType,
           com.google.api.ads.admanager.axis.v202211.DeliveryRateType deliveryRateType,
           com.google.api.ads.admanager.axis.v202211.RoadblockingType roadblockingType,
           com.google.api.ads.admanager.axis.v202211.CreativeRotationType creativeRotationType) {
           this.id = id;
           this.name = name;
           this.isDefault = isDefault;
           this.lineItemName = lineItemName;
           this.enabledForSameAdvertiserException = enabledForSameAdvertiserException;
           this.notes = notes;
           this.lineItemType = lineItemType;
           this.deliveryRateType = deliveryRateType;
           this.roadblockingType = roadblockingType;
           this.creativeRotationType = creativeRotationType;
    }

    @Override
    public String toString() {
        return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
            .omitNullValues()
            .add("creativeRotationType", getCreativeRotationType())
            .add("deliveryRateType", getDeliveryRateType())
            .add("enabledForSameAdvertiserException", getEnabledForSameAdvertiserException())
            .add("id", getId())
            .add("isDefault", getIsDefault())
            .add("lineItemName", getLineItemName())
            .add("lineItemType", getLineItemType())
            .add("name", getName())
            .add("notes", getNotes())
            .add("roadblockingType", getRoadblockingType())
            .toString();
    }

    /**
     * Gets the id value for this LineItemTemplate.
     *
     * @return id   * Uniquely identifies the {@code LineItemTemplate}. This attribute
     * is
     *                 read-only and is assigned by Google when a template
     * is created.
     */
    public java.lang.Long getId() {
        return id;
    }

    /**
     * Sets the id value for this LineItemTemplate.
     *
     * @param id   * Uniquely identifies the {@code LineItemTemplate}. This attribute
     * is
     *                 read-only and is assigned by Google when a template
     * is created.
     */
    public void setId(java.lang.Long id) {
        this.id = id;
    }

    /**
     * Gets the name value for this LineItemTemplate.
     *
     * @return name   * The name of the {@code LineItemTemplate}. This attribute is
     * required.
     */
    public java.lang.String getName() {
        return name;
    }

    /**
     * Sets the name value for this LineItemTemplate.
     *
     * @param name   * The name of the {@code LineItemTemplate}. This attribute is
     * required.
     */
    public void setName(java.lang.String name) {
        this.name = name;
    }

    /**
     * Gets the isDefault value for this LineItemTemplate.
     *
     * @return isDefault   * Whether or not the {@code LineItemTemplate} represents the
     * default choices
     *                 for creating a {@code LineItem}. Only one default
     * {@code LineItemTemplate}
     *                 is allowed per {@code Network}. This attribute is
     * readonly.
     */
    public java.lang.Boolean getIsDefault() {
        return isDefault;
    }

    /**
     * Sets the isDefault value for this LineItemTemplate.
     *
     * @param isDefault   * Whether or not the {@code LineItemTemplate} represents the
     * default choices
     *                 for creating a {@code LineItem}. Only one default
     * {@code LineItemTemplate}
     *                 is allowed per {@code Network}. This attribute is
     * readonly.
     */
    public void setIsDefault(java.lang.Boolean isDefault) {
        this.isDefault = isDefault;
    }

    /**
     * Gets the lineItemName value for this LineItemTemplate.
     *
     * @return lineItemName   * The default {@link LineItem#name name} of a new {@code LineItem}.
     * This
     *                 attribute is optional and has a maximum length of
     * 127 characters.
     */
    public java.lang.String getLineItemName() {
        return lineItemName;
    }

    /**
     * Sets the lineItemName value for this LineItemTemplate.
     *
     * @param lineItemName   * The default {@link LineItem#name name} of a new {@code LineItem}.
     * This
     *                 attribute is optional and has a maximum length of
     * 127 characters.
     */
    public void setLineItemName(java.lang.String lineItemName) {
        this.lineItemName = lineItemName;
    }

    /**
     * Gets the enabledForSameAdvertiserException value for this LineItemTemplate.
     *
     * @return enabledForSameAdvertiserException   * The default value for the
     *                 {@link LineItem#enabledForSameAdvertiserException}
     * field of a new
     *                 {@code LineItem}. This attribute is required.
     */
    public java.lang.Boolean getEnabledForSameAdvertiserException() {
        return enabledForSameAdvertiserException;
    }

    /**
     * Sets the enabledForSameAdvertiserException value for this LineItemTemplate.
     *
     * @param enabledForSameAdvertiserException   * The default value for the
     *                 {@link LineItem#enabledForSameAdvertiserException}
     * field of a new
     *                 {@code LineItem}. This attribute is required.
     */
    public void setEnabledForSameAdvertiserException(java.lang.Boolean enabledForSameAdvertiserException) {
        this.enabledForSameAdvertiserException = enabledForSameAdvertiserException;
    }

    /**
     * Gets the notes value for this LineItemTemplate.
     *
     * @return notes   * The default {@link LineItem#notes notes} for a new {@code LineItem}.
     * This
     *                 attribute is optional and has a maximum length of
     * 65,535 characters.
     */
    public java.lang.String getNotes() {
        return notes;
    }

    /**
     * Sets the notes value for this LineItemTemplate.
     *
     * @param notes   * The default {@link LineItem#notes notes} for a new {@code LineItem}.
     * This
     *                 attribute is optional and has a maximum length of
     * 65,535 characters.
     */
    public void setNotes(java.lang.String notes) {
        this.notes = notes;
    }

    /**
     * Gets the lineItemType value for this LineItemTemplate.
     *
     * @return lineItemType   * The default {@link LineItem#lineItemType type} of a new {@code
     * LineItem}.
     *                 This attribute is required.
     */
    public com.google.api.ads.admanager.axis.v202211.LineItemType getLineItemType() {
        return lineItemType;
    }

    /**
     * Sets the lineItemType value for this LineItemTemplate.
     *
     * @param lineItemType   * The default {@link LineItem#lineItemType type} of a new {@code
     * LineItem}.
     *                 This attribute is required.
     */
    public void setLineItemType(com.google.api.ads.admanager.axis.v202211.LineItemType lineItemType) {
        this.lineItemType = lineItemType;
    }

    /**
     * Gets the deliveryRateType value for this LineItemTemplate.
     *
     * @return deliveryRateType   * The default {@link LineItem#deliveryRateType delivery strategy}
     * for a new
     *                 {@code LineItem}. This attribute is required.
     */
    public com.google.api.ads.admanager.axis.v202211.DeliveryRateType getDeliveryRateType() {
        return deliveryRateType;
    }

    /**
     * Sets the deliveryRateType value for this LineItemTemplate.
     *
     * @param deliveryRateType   * The default {@link LineItem#deliveryRateType delivery strategy}
     * for a new
     *                 {@code LineItem}. This attribute is required.
     */
    public void setDeliveryRateType(com.google.api.ads.admanager.axis.v202211.DeliveryRateType deliveryRateType) {
        this.deliveryRateType = deliveryRateType;
    }

    /**
     * Gets the roadblockingType value for this LineItemTemplate.
     *
     * @return roadblockingType   * The default {@link LineItem#roadblockingType roadblocking strategy}
     * for a
     *                 new {@code LineItem}. This attribute is required.
     */
    public com.google.api.ads.admanager.axis.v202211.RoadblockingType getRoadblockingType() {
        return roadblockingType;
    }

    /**
     * Sets the roadblockingType value for this LineItemTemplate.
     *
     * @param roadblockingType   * The default {@link LineItem#roadblockingType roadblocking strategy}
     * for a
     *                 new {@code LineItem}. This attribute is required.
     */
    public void setRoadblockingType(com.google.api.ads.admanager.axis.v202211.RoadblockingType roadblockingType) {
        this.roadblockingType = roadblockingType;
    }

    /**
     * Gets the creativeRotationType value for this LineItemTemplate.
     *
     * @return creativeRotationType   * The default {@link LineItem#creativeRotationType creative rotation
     * strategy}
     *                 for a new {@code LineItem}. This attribute is required.
     */
    public com.google.api.ads.admanager.axis.v202211.CreativeRotationType getCreativeRotationType() {
        return creativeRotationType;
    }

    /**
     * Sets the creativeRotationType value for this LineItemTemplate.
     *
     * @param creativeRotationType   * The default {@link LineItem#creativeRotationType creative rotation
     * strategy}
     *                 for a new {@code LineItem}. This attribute is required.
     */
    public void setCreativeRotationType(com.google.api.ads.admanager.axis.v202211.CreativeRotationType creativeRotationType) {
        this.creativeRotationType = creativeRotationType;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof LineItemTemplate)) return false;
        LineItemTemplate other = (LineItemTemplate) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.id==null && other.getId()==null) ||
             (this.id!=null &&
              this.id.equals(other.getId()))) &&
            ((this.name==null && other.getName()==null) ||
             (this.name!=null &&
              this.name.equals(other.getName()))) &&
            ((this.isDefault==null && other.getIsDefault()==null) ||
             (this.isDefault!=null &&
              this.isDefault.equals(other.getIsDefault()))) &&
            ((this.lineItemName==null && other.getLineItemName()==null) ||
             (this.lineItemName!=null &&
              this.lineItemName.equals(other.getLineItemName()))) &&
            ((this.enabledForSameAdvertiserException==null && other.getEnabledForSameAdvertiserException()==null) ||
             (this.enabledForSameAdvertiserException!=null &&
              this.enabledForSameAdvertiserException.equals(other.getEnabledForSameAdvertiserException()))) &&
            ((this.notes==null && other.getNotes()==null) ||
             (this.notes!=null &&
              this.notes.equals(other.getNotes()))) &&
            ((this.lineItemType==null && other.getLineItemType()==null) ||
             (this.lineItemType!=null &&
              this.lineItemType.equals(other.getLineItemType()))) &&
            ((this.deliveryRateType==null && other.getDeliveryRateType()==null) ||
             (this.deliveryRateType!=null &&
              this.deliveryRateType.equals(other.getDeliveryRateType()))) &&
            ((this.roadblockingType==null && other.getRoadblockingType()==null) ||
             (this.roadblockingType!=null &&
              this.roadblockingType.equals(other.getRoadblockingType()))) &&
            ((this.creativeRotationType==null && other.getCreativeRotationType()==null) ||
             (this.creativeRotationType!=null &&
              this.creativeRotationType.equals(other.getCreativeRotationType())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getId() != null) {
            _hashCode += getId().hashCode();
        }
        if (getName() != null) {
            _hashCode += getName().hashCode();
        }
        if (getIsDefault() != null) {
            _hashCode += getIsDefault().hashCode();
        }
        if (getLineItemName() != null) {
            _hashCode += getLineItemName().hashCode();
        }
        if (getEnabledForSameAdvertiserException() != null) {
            _hashCode += getEnabledForSameAdvertiserException().hashCode();
        }
        if (getNotes() != null) {
            _hashCode += getNotes().hashCode();
        }
        if (getLineItemType() != null) {
            _hashCode += getLineItemType().hashCode();
        }
        if (getDeliveryRateType() != null) {
            _hashCode += getDeliveryRateType().hashCode();
        }
        if (getRoadblockingType() != null) {
            _hashCode += getRoadblockingType().hashCode();
        }
        if (getCreativeRotationType() != null) {
            _hashCode += getCreativeRotationType().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(LineItemTemplate.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202211", "LineItemTemplate"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("id");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202211", "id"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("name");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202211", "name"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("isDefault");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202211", "isDefault"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("lineItemName");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202211", "lineItemName"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("enabledForSameAdvertiserException");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202211", "enabledForSameAdvertiserException"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("notes");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202211", "notes"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("lineItemType");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202211", "lineItemType"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202211", "LineItemType"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("deliveryRateType");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202211", "deliveryRateType"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202211", "DeliveryRateType"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("roadblockingType");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202211", "roadblockingType"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202211", "RoadblockingType"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("creativeRotationType");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202211", "creativeRotationType"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202211", "CreativeRotationType"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
using namespace luabind;

#pragma optimize("s", on)
void CTorch::script_register(lua_State* L) {
    module(L)[class_<CTorch, CGameObject>("CTorch").def(constructor<>()),
              class_<CPda, CGameObject>("CPda").def(constructor<>()),
              class_<CScientificDetector, CGameObject>("CScientificDetector").def(constructor<>()),
              class_<CEliteDetector, CGameObject>("CEliteDetector").def(constructor<>()),
              class_<CAdvancedDetector, CGameObject>("CAdvancedDetector").def(constructor<>()),
              class_<CSimpleDetector, CGameObject>("CSimpleDetector").def(constructor<>())];
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;

namespace MaterialDesignThemes.Wpf.Converters
{
    public class CardClipConverter : IMultiValueConverter
    {
        /// <summary>
        /// 1 - Content presenter render size,
        /// 2 - Clipping border padding (main control padding)
        /// </summary>
        /// <param name="values"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values.Length != 2 || !(values[0] is Size) || !(values[1] is Thickness))
                return Binding.DoNothing;

            var size = (Size)values[0];
            var farPoint = new Point(
                Math.Max(0, size.Width),
                Math.Max(0, size.Height));
            var padding = (Thickness)values[1];
            farPoint.Offset(padding.Left + padding.Right, padding.Top + padding.Bottom);

            return new Rect(
                new Point(),
                new Point(farPoint.X, farPoint.Y));
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}


text:
package org.ayo.ui.sample.view_learn;

import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.ViewGroup;

/**
 * 默认行为的ViewGroup
 */

public class MeasureViewGroup1 extends ViewGroup {
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public MeasureViewGroup1(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public MeasureViewGroup1(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MeasureViewGroup1(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
    }

}