text:
package ca.uhn.fhir.jpa.searchparam.registry;

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.RuntimeSearchParam;
import ca.uhn.fhir.interceptor.api.IInterceptorService;
import ca.uhn.fhir.jpa.cache.IResourceChangeListenerRegistry;
import ca.uhn.fhir.jpa.cache.IResourceVersionSvc;
import ca.uhn.fhir.jpa.cache.ResourceChangeListenerCacheRefresherImpl;
import ca.uhn.fhir.jpa.cache.ResourceChangeListenerRegistryImpl;
import ca.uhn.fhir.jpa.cache.ResourceChangeResult;
import ca.uhn.fhir.jpa.cache.ResourceVersionMap;
import ca.uhn.fhir.jpa.cache.config.RegisteredResourceListenerFactoryConfig;
import ca.uhn.fhir.jpa.model.entity.ModelConfig;
import ca.uhn.fhir.jpa.model.entity.ResourceTable;
import ca.uhn.fhir.jpa.model.sched.ISchedulerService;
import ca.uhn.fhir.jpa.searchparam.MatchUrlService;
import ca.uhn.fhir.jpa.searchparam.matcher.InMemoryMatchResult;
import ca.uhn.fhir.jpa.searchparam.matcher.InMemoryResourceMatcher;
import ca.uhn.fhir.jpa.searchparam.matcher.SearchParamMatcher;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.rest.server.SimpleBundleProvider;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException;
import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.instance.model.api.IPrimitiveType;
import org.hl7.fhir.r4.model.Enumerations;
import org.hl7.fhir.r4.model.SearchParameter;
import org.hl7.fhir.r4.model.StringType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(SpringExtension.class)
public class SearchParamRegistryImplTest {
	private static final FhirContext ourFhirContext = FhirContext.forR4();
	private static final ReadOnlySearchParamCache ourBuiltInSearchParams = ReadOnlySearchParamCache.fromFhirContext(ourFhirContext);

	public static final int TEST_SEARCH_PARAMS = 3;
	private static final List<ResourceTable> ourEntities;
	private static final ResourceVersionMap ourResourceVersionMap;
	private static int ourLastId;
	private static final int ourBuiltinPatientSearchParamCount;

	static {
		ourEntities = new ArrayList<>();
		for (ourLastId = 0; ourLastId < TEST_SEARCH_PARAMS; ++ourLastId) {
			ourEntities.add(createEntity(ourLastId, 1));
		}
		ourResourceVersionMap = ResourceVersionMap.fromResourceTableEntities(ourEntities);
		ourBuiltinPatientSearchParamCount = ReadOnlySearchParamCache.fromFhirContext(ourFhirContext).getSearchParamMap("Patient").size();
	}

	@Autowired
	SearchParamRegistryImpl mySearchParamRegistry;
	@Autowired
	private ResourceChangeListenerRegistryImpl myResourceChangeListenerRegistry;
	@Autowired
	private ResourceChangeListenerCacheRefresherImpl myChangeListenerCacheRefresher;

	@MockBean
	private IResourceVersionSvc myResourceVersionSvc;
	@MockBean
	private ISchedulerService mySchedulerService;
	@MockBean
	private ISearchParamProvider mySearchParamProvider;
	@MockBean
	private IInterceptorService myInterceptorBroadcaster;
	@MockBean
	private SearchParamMatcher mySearchParamMatcher;
	@MockBean
	private MatchUrlService myMatchUrlService;

	@Configuration
	@Import(RegisteredResourceListenerFactoryConfig.class)
	static class SpringConfig {
		@Bean
		FhirContext fhirContext() {
			return ourFhirContext;
		}

		@Bean
		ModelConfig modelConfig() {
			ModelConfig modelConfig = new ModelConfig();
			modelConfig.setDefaultSearchParamsCanBeOverridden(true);
			return modelConfig;
		}

		@Bean
		ISearchParamRegistry searchParamRegistry() {
			return new SearchParamRegistryImpl();
		}

		@Bean
		SearchParameterCanonicalizer searchParameterCanonicalizer(FhirContext theFhirContext) {
			return new SearchParameterCanonicalizer(theFhirContext);
		}

		@Bean
		IResourceChangeListenerRegistry resourceChangeListenerRegistry() {
			return new ResourceChangeListenerRegistryImpl();
		}

		@Bean
		ResourceChangeListenerCacheRefresherImpl resourceChangeListenerCacheRefresher() {
			return new ResourceChangeListenerCacheRefresherImpl();
		}

		@Bean
		InMemoryResourceMatcher inMemoryResourceMatcher() {
			InMemoryResourceMatcher retval = mock(InMemoryResourceMatcher.class);
			when(retval.canBeEvaluatedInMemory(any(), any())).thenReturn(InMemoryMatchResult.successfulMatch());
			return retval;
		}

	}

	@Nonnull
	private static ResourceTable createEntity(long theId, int theVersion) {
		ResourceTable searchParamEntity = new ResourceTable();
		searchParamEntity.setResourceType("SearchParameter");
		searchParamEntity.setId(theId);
		searchParamEntity.setVersion(theVersion);
		return searchParamEntity;
	}

	private int myAnswerCount = 0;

	@BeforeEach
	public void before() {
		myAnswerCount = 0;
		when(myResourceVersionSvc.getVersionMap(anyString(), any())).thenReturn(ourResourceVersionMap);
		when(mySearchParamProvider.search(any())).thenReturn(new SimpleBundleProvider());

		// Our first refresh adds our test searchparams to the registry
		assertResult(mySearchParamRegistry.refreshCacheIfNecessary(), TEST_SEARCH_PARAMS, 0, 0);
		assertEquals(TEST_SEARCH_PARAMS, myResourceChangeListenerRegistry.getResourceVersionCacheSizeForUnitTest());
		assertDbCalled();
		assertEquals(ourBuiltInSearchParams.size(), mySearchParamRegistry.getActiveSearchParams().size());
		assertPatientSearchParamSize(ourBuiltinPatientSearchParamCount);
	}

	@AfterEach
	public void after() {
		myResourceChangeListenerRegistry.clearCachesForUnitTest();
		// Empty out the searchparam registry
		mySearchParamRegistry.resetForUnitTest();
	}

	@Test
	void handleInit() {
		assertEquals(25, mySearchParamRegistry.getActiveSearchParams("Patient").size());

		IdDt idBad = new IdDt("SearchParameter/bad");
		when(mySearchParamProvider.read(idBad)).thenThrow(new ResourceNotFoundException("id bad"));

		IdDt idGood = new IdDt("SearchParameter/good");
		SearchParameter goodSearchParam = buildSearchParameter(Enumerations.PublicationStatus.ACTIVE);
		when(mySearchParamProvider.read(idGood)).thenReturn(goodSearchParam);

		List<IIdType> idList = new ArrayList<>();
		idList.add(idBad);
		idList.add(idGood);
		mySearchParamRegistry.handleInit(idList);
		assertEquals(26, mySearchParamRegistry.getActiveSearchParams("Patient").size());
	}

	@Test
	public void testRefreshAfterExpiry() {
		mySearchParamRegistry.requestRefresh();
		// Second time we don't need to run because we ran recently
		assertEmptyResult(mySearchParamRegistry.refreshCacheIfNecessary());
	}

	@Test
	public void testRefreshCacheIfNecessary() {
		// Second refresh does not call the database
		assertEmptyResult(mySearchParamRegistry.refreshCacheIfNecessary());
		assertEquals(TEST_SEARCH_PARAMS, myResourceChangeListenerRegistry.getResourceVersionCacheSizeForUnitTest());
		assertDbNotCalled();
		assertPatientSearchParamSize(ourBuiltinPatientSearchParamCount);

		// Requesting a refresh calls the database and adds nothing
		mySearchParamRegistry.requestRefresh();
		assertEmptyResult(mySearchParamRegistry.refreshCacheIfNecessary());
		assertEquals(TEST_SEARCH_PARAMS, myResourceChangeListenerRegistry.getResourceVersionCacheSizeForUnitTest());
		assertDbCalled();
		assertPatientSearchParamSize(ourBuiltinPatientSearchParamCount);

		// Requesting a refresh after adding a new search parameter calls the database and adds one
		resetDatabaseToOrigSearchParamsPlusNewOneWithStatus(Enumerations.PublicationStatus.ACTIVE);
		mySearchParamRegistry.requestRefresh();
		assertResult(mySearchParamRegistry.refreshCacheIfNecessary(), 1, 0, 0);
		assertEquals(TEST_SEARCH_PARAMS + 1, myResourceChangeListenerRegistry.getResourceVersionCacheSizeForUnitTest());
		assertDbCalled();
		assertPatientSearchParamSize(ourBuiltinPatientSearchParamCount + 1);

		// Requesting a refresh after adding a new search parameter calls the database and
		// removes the one added above and adds this new one
		resetDatabaseToOrigSearchParamsPlusNewOneWithStatus(Enumerations.PublicationStatus.ACTIVE);
		mySearchParamRegistry.requestRefresh();
		assertResult(mySearchParamRegistry.refreshCacheIfNecessary(), 1, 0, 1);
		assertEquals(TEST_SEARCH_PARAMS + 1, myResourceChangeListenerRegistry.getResourceVersionCacheSizeForUnitTest());
		assertDbCalled();
		assertPatientSearchParamSize(ourBuiltinPatientSearchParamCount + 1);

		// Requesting a refresh after adding a new search parameter calls the database,
		// removes the ACTIVE one and adds the new one because this is a mock test
		resetDatabaseToOrigSearchParamsPlusNewOneWithStatus(Enumerations.PublicationStatus.DRAFT);
		mySearchParamRegistry.requestRefresh();
		assertEquals(TEST_SEARCH_PARAMS + 1, myResourceChangeListenerRegistry.getResourceVersionCacheSizeForUnitTest());
		assertResult(mySearchParamRegistry.refreshCacheIfNecessary(), 1, 0, 1);
		assertDbCalled();
		// the new one does not appear in our patient search params because it's DRAFT
		assertPatientSearchParamSize(ourBuiltinPatientSearchParamCount);
	}

	@Test
	public void testSearchParamUpdate() {
		// Requesting a refresh after adding a new search parameter calls the database and adds one
		List<ResourceTable> newEntities = resetDatabaseToOrigSearchParamsPlusNewOneWithStatus(Enumerations.PublicationStatus.ACTIVE);
		mySearchParamRegistry.requestRefresh();
		assertResult(mySearchParamRegistry.refreshCacheIfNecessary(), 1, 0, 0);
		assertEquals(TEST_SEARCH_PARAMS + 1, myResourceChangeListenerRegistry.getResourceVersionCacheSizeForUnitTest());
		assertDbCalled();
		assertPatientSearchParamSize(ourBuiltinPatientSearchParamCount + 1);

		// Update the resource without changing anything that would affect our cache
		ResourceTable lastEntity = newEntities.get(newEntities.size() - 1);
		lastEntity.setVersion(2);
		resetMock(Enumerations.PublicationStatus.ACTIVE, newEntities);
		mySearchParamRegistry.requestRefresh();
		assertResult(mySearchParamRegistry.refreshCacheIfNecessary(), 0, 1, 0);
		assertEquals(TEST_SEARCH_PARAMS + 1, myResourceChangeListenerRegistry.getResourceVersionCacheSizeForUnitTest());
		assertDbCalled();
		assertPatientSearchParamSize(ourBuiltinPatientSearchParamCount + 1);
	}

	private void assertPatientSearchParamSize(int theExpectedSize) {
		assertEquals(theExpectedSize, mySearchParamRegistry.getActiveSearchParams("Patient").size());
	}

	private void assertResult(ResourceChangeResult theResult, long theExpectedAdded, long theExpectedUpdated, long theExpectedRemoved) {
		assertEquals(theExpectedAdded, theResult.created, "added results");
		assertEquals(theExpectedUpdated, theResult.updated, "updated results");
		assertEquals(theExpectedRemoved, theResult.deleted, "removed results");
	}

	private void assertEmptyResult(ResourceChangeResult theResult) {
		assertResult(theResult, 0, 0, 0);
	}

	private void assertDbCalled() {
		verify(myResourceVersionSvc, times(1)).getVersionMap(anyString(), any());
		reset(myResourceVersionSvc);
		when(myResourceVersionSvc.getVersionMap(anyString(), any())).thenReturn(ourResourceVersionMap);
	}

	private void assertDbNotCalled() {
		verify(myResourceVersionSvc, never()).getVersionMap(anyString(), any());
		reset(myResourceVersionSvc);
		when(myResourceVersionSvc.getVersionMap(anyString(), any())).thenReturn(ourResourceVersionMap);
	}

	@Test
	public void testGetActiveUniqueSearchParams_Empty() {
		assertThat(mySearchParamRegistry.getActiveUniqueSearchParams("Patient"), is(empty()));
	}

	@Test
	public void testGetActiveSearchParamsRetries() {
		AtomicBoolean retried = new AtomicBoolean(false);
		when(myResourceVersionSvc.getVersionMap(anyString(), any())).thenAnswer(t -> {
			if (myAnswerCount == 0) {
				myAnswerCount++;
				retried.set(true);
				throw new InternalErrorException("this is an error!");
			}

			return ourResourceVersionMap;
		});

		assertFalse(retried.get());
		mySearchParamRegistry.forceRefresh();
		Map<String, RuntimeSearchParam> activeSearchParams = mySearchParamRegistry.getActiveSearchParams("Patient");
		assertTrue(retried.get());
		assertEquals(ourBuiltInSearchParams.getSearchParamMap("Patient").size(), activeSearchParams.size());
	}

	@Test
	public void testAddActiveSearchparam() {
		// Initialize the registry
		mySearchParamRegistry.forceRefresh();

		resetDatabaseToOrigSearchParamsPlusNewOneWithStatus(Enumerations.PublicationStatus.ACTIVE);

		mySearchParamRegistry.forceRefresh();
		Map<String, RuntimeSearchParam> outcome = mySearchParamRegistry.getActiveSearchParams("Patient");

		RuntimeSearchParam converted = outcome.get("foo");
		assertNotNull(converted);

		assertEquals(1, converted.getExtensions("http://foo").size());
		IPrimitiveType<?> value = (IPrimitiveType<?>) converted.getExtensions("http://foo").get(0).getValue();
		assertEquals("FOO", value.getValueAsString());
	}

	private List<ResourceTable> resetDatabaseToOrigSearchParamsPlusNewOneWithStatus(Enumerations.PublicationStatus theStatus) {
		// Add a new search parameter entity
		List<ResourceTable> newEntities = new ArrayList(ourEntities);
		newEntities.add(createEntity(++ourLastId, 1));
		resetMock(theStatus, newEntities);
		return newEntities;
	}

	private void resetMock(Enumerations.PublicationStatus theStatus, List<ResourceTable> theNewEntities) {
		ResourceVersionMap resourceVersionMap = ResourceVersionMap.fromResourceTableEntities(theNewEntities);
		when(myResourceVersionSvc.getVersionMap(anyString(), any())).thenReturn(resourceVersionMap);

		// When we ask for the new entity, return our foo search parameter
		when(mySearchParamProvider.search(any())).thenReturn(new SimpleBundleProvider(buildSearchParameter(theStatus)));
	}

	@Nonnull
	private SearchParameter buildSearchParameter(Enumerations.PublicationStatus theStatus) {
		SearchParameter searchParameter = new SearchParameter();
		searchParameter.setCode("foo");
		searchParameter.setStatus(theStatus);
		searchParameter.setType(Enumerations.SearchParamType.TOKEN);
		searchParameter.setExpression("Patient.name");
		searchParameter.addBase("Patient");
		searchParameter.addExtension("http://foo", new StringType("FOO"));
		searchParameter.addExtension("http://bar", new StringType("BAR"));

		// Invalid entries
		searchParameter.addExtension("http://bar", null);
		searchParameter.addExtension(null, new StringType("BAR"));
		return searchParameter;
	}

}


text:
generate_pkg()
{
  # generate temporary directory
  mkdir -p tmp
  rm -rf tmp/*

  # generate ccu1 package
  cp -a common/* tmp/
  cp -a ${1}/* tmp/
  mv tmp/cuxd/cuxd_addon.cfg tmp/
  ln -s cuxd/update_addon tmp/
  cd tmp
  tar --owner=root --group=root --exclude=.DS_Store -czvf ../cuxd_$(cat ../VERSION)_${1}.tar.gz *
  cd ..
  rm -rf tmp
}

# generate packages now. If specified on
# command-line generate this specific package
# only. If not specified at all, generate all
# packages.
if [ -n "$1" ]; then
  generate_pkg $1
else
  generate_pkg ccu1
  generate_pkg ccu2
  generate_pkg ccu3
  generate_pkg ccux86
fi

redpajama_set_name: RedPajamaGithub


text:
/*
 * @Author: jjj201200@gmail.com
 * @Date: 2017-08-18 13:21:28
 * @Last Modified by: jjj201200@gmail.com
 * @Last Modified time: 2017-08-20 01:06:05
 */

import $ from 'jquery';
import {Texture} from './texture';

export class TextureManager {
	constructor() {
		this.init();
	}
	init() {
		/* initialize basic data */
		this.textureDataList = {};
		this.textureObejcts = {};
		this.currentTexture = null;
		/* create texture canvas & context */
		this.canvas = document.createElement('canvas');
		this.context = this.canvas.getContext('2d');
	}
	getTextureData(textureName) {
		let _t = this;
		if (_t.dtd === null) {
			_t.dfd = $.Deferred();
		}
		let textureData = this.textureDataList[textureName];
		if (texture) {
			return _t.dfd.resolve();
		} else {
			return $.get('textures/', { textureName: textureName }).then(
				textureData => {
					_t.textureDataList[textureName] = textureData;
					_t.dfd.resolve();
				},
				() => {
					_t.dfd.reject(`Failed to get texture ${textureName}.`);
				}
			);
		}
	}
	setTexture(textureName) {
		let _t = this,
			dtd = false;
		if (_t.dtd === null) {
			_t.dfd = $.Deferred();
			dtd = true;
		}
		let texture = _t.textureObjects[textureName];
		if (texture) {
			return _t.dfd.resolve();
		} else {
			return _t.getTextureData(textureName).then(
				() => {
					let textureData = _t.textureDataList[textureName];
					let texture = new Texture(textureName, textureData);
					_t.textureObjects[textureName] = texture;
					_t.currentTexture = texture;
					_t.dfd.resolve();
				},
				() => {
					_t.dfd.reject(`Failed to set texture ${textureName}.`);
				}
			);
		}
	}
	/**
	 * add textureObject to renderer's scene
	 * @param  {string} textureName the texture's name
	 * @param  {} renderer
	 */
	loadTexture(textureName) {
		let _t = this;
		_t.dfd = $.Deferred();
		return _t.setTexture(textureName).then(() => {
            let textureObject = _t.textureObjects[textureName];
            this.context2D.drawImage(textureObject.img, 0, 0);
			_t.dfd = null;
		});
	}
}


text:
<!DOCTYPE html>
getLocale() }}">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Dashi') }}</title>

    <link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet">
    <link href="{{ asset('css/pages.min.css') }}" rel="stylesheet">
    <link href="{{ asset('css/styles.css') }}" rel="stylesheet">

implode('-') }}">

                        @if (Auth::guest())

Login

Register

                        @else

                                <button class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="z-index:3;background-color: transparent;border: 0;color: white;">
                                    {{ Auth::user()->name }}
                                </button>

                                        Logout

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                        {{ csrf_field() }}
                                    </form>

                        @endif

        @yield('content')


text:
help:
	@echo "    all"
	@echo "    simulator - x86 OR1K simulator"
	@echo "    inline - Simple bare metal program that calls IIE handler"
	@echo "    interrupt - Build just the IIE handler to run at address 0x08000000"
	@echo "    mmu - Build just the IIE handler to run at address 0x08000000 with MMU support"

all: simulator inline interrupt mmu

simulator:
	make -f Makefile.sim

inline:
	or32-elf-gcc -g -mboard=ml505 -O0 -o simple.or32 cpu.c mmu_support.c simulator.c runSim.c iieHandler.S simple.c
	or32-elf-objdump -d simple.or32 > simple.asm

interrupt:
	or32-elf-gcc -nostdlib -O0 -Ttext=0x08000000 -DSTANDALONE -o iieHandler.or32 iieHandler.S cpu.c mmu_support.c simulator.c runSim.c
	or32-elf-objdump -d iieHandler.or32 > iieHandler.asm
	or32-elf-gcc -mboard=ml505 -g -O0 -o loop.or32 loop.c
	or32-elf-objdump -d loop.or32 > loop.asm

mmu:
	or32-elf-gcc -nostdlib -O3 -Ttext=0x08000000 -DSTANDALONE -DMMU_SUPPORT -o iieHandler.or32 iieHandler.S cpu.c mmu_support.c simulator.c runSim.c
	or32-elf-objdump -d iieHandler.or32 > iieHandler.asm
	or32-elf-gcc -mboard=ml505 -g -O0 -o loopMMU.or32 loopMMU.c
	or32-elf-objdump -d loopMMU.or32 > loopMMU.asm
	or32-linux-gcc -DLINUX -I/opt/or32-linux/include -L/opt/or32-linux/lib -o loopMMU.linux loopMMU.c
	or32-linux-objdump -d loopMMU.linux > loopMMU.linux.asm

sim: mmu
	or32-elf-gcc -mboard=ml505 -g -O0 -DSIMNO -o loopMMU.or32 loopMMU.c
	or32-elf-objdump -d loopMMU.or32 > loopMMU.asm
	or32-elf-objcopy -O binary loopMMU.or32 loopMMU.bin
	../utils/bin2vmem loopMMU.bin > loopMMU.vmem
	echo  "" >> loopMMU.vmem
	or32-elf-objcopy -O binary iieHandler.or32 iieHandler.bin
	../utils/bin2vmem iieHandler.bin | sed s/@000/@020/ >> loopMMU.vmem
	rm -rf *.bin
bare:
	or32-elf-gcc -nostdlib -O3 -Ttext=0x08000000 -DSTANDALONE -DMMU_SUPPORT -o iieHandler.or32 iieHandler.S cpu.c mmu_support.c simulator.c runSim.c
	or32-elf-objdump -d iieHandler.or32 > iieHandler.asm
	or32-elf-objcopy -O binary iieHandler.or32 iieHandler.bin
	../utils/bin2vmem iieHandler.bin | sed s/@000/@020/ > iieHandler.vmem
	rm -rf *.bin
clean:
	rm -rf *.{o,or32,asm,d,bin,vmem,linux} simulator


text:
using NtPhotoInfoEditor.DataModel;
using NtPhotoInfoEditor.PhotoUtil;
using NtPhotoInfoEditor.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.FileProperties;
using Windows.UI.Core;
using Windows.UI.Xaml.Media.Imaging;

namespace NtPhotoInfoEditor.IOHelper
{
    public static class StorageAccessHelper
    {

        public static async Task<FolderInfo> ReadAllFoldersAsync(StorageFolder ParentFolder)
        {
            var folder = new FolderInfo();
            folder.Self = ParentFolder;
            folder.Contents = new List<ContentViewData>();
            var folders = new List<StorageFolder>(await ParentFolder.GetFoldersAsync());
            foreach (var f in folders)
            {
                folder.Contents.Add(await ReadFolderViewData(f));
            }
            return folder;
        }

        public static async Task<FolderInfo> ReadAllContentsAsync(StorageFolder ParentFolder)
        {
            var items = new List<StorageFile>(await ParentFolder.GetFilesAsync());
            items.Reverse();
            var folder = await ReadAllFoldersAsync(ParentFolder).ConfigureAwait(false);

            foreach (var item in items)
            {
                if (Definitions.PhotoFileExtensions.Contains(item.FileType))
                {
                    // add contents if supported photo file type
                    var viewData = new ContentViewData() { Name = item.Name, Type = ContentType.Jpeg, File = item, Created = new DateTime(0) };
                    folder.Contents.Add(viewData);

                    SequentialPhotoLoader.INSTANCE.Enqueue(new PhotoLoadTask()
                    {
                        Path = item.Path,
                        Loaded = async (file) =>
                            {
                                await SystemUtil.GetCurrentDispatcher().RunAsync(CoreDispatcherPriority.Normal, async () =>
                                {
                                    viewData.Created = file.DateCreated.DateTime;
                                    viewData.Image = await ReadThumbnailAsync(file);
                                    Logger.Log("Image set: " + file.Name);
                                });
                            }
                    });
                }
            }
            return folder;
        }

        static async Task<ContentViewData> ReadFolderViewData(StorageFolder folder)
        {
            var data = new List<ContentViewData>();
            var property = await folder.GetBasicPropertiesAsync();
            var items = await folder.GetItemsAsync();
            var folders = await folder.GetFoldersAsync();

            var viewData = new ContentViewData() { Name = folder.DisplayName, NumberOfFolders = folders.Count, NumberOfPhotos = await CountPhotoFile(folder), Type = ContentType.Folder, Folder = folder };

            if (items.Count > 0)
            {
                try
                {
                    viewData.Image = await ReadThumbnailAsync(await folder.GetFileAsync(items[0].Name));
                }
                catch (Exception e) { Logger.Log(e.StackTrace); }
            }
            return viewData;
        }

        static async Task<BitmapImage> ReadThumbnailAsync(StorageFile file)
        {
            Logger.Log("Getting thumbnail: " + file.Name);
            var thumbnail = new BitmapImage();
            try
            {
                using (var thumb = await file.GetThumbnailAsync(ThumbnailMode.ListView, 150))
                {
                    thumbnail.SetSource(thumb);
                    thumb.Dispose();
                }
            }
            catch (Exception e) { Logger.Log(e.StackTrace); }
            Logger.Log("Return thumbnail: " + file.Name);
            return thumbnail;
        }

        static async Task<int> CountPhotoFile(StorageFolder folder)
        {
            IReadOnlyList<StorageFile> items = new List<StorageFile>();
            int itemCount = 0;

            try
            {
                items = await folder.GetFilesAsync();
                foreach (var item in items)
                {
                    if (Definitions.PhotoFileExtensions.Contains(item.FileType)) { itemCount++; }
                }
            }
            catch (IOException ex)
            {
                Logger.Log(ex.StackTrace);
                return 0;
            }
            return itemCount;
        }
    }

}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of TipoUsuario
 *
 * @author joao
 */
include_once 'Conexao.php';

class TipoUsuario extends Conexao{
    private $id_tipo;
    private $descricao;
    private $id_pai;
    private $data_cadastro;
    private $data_modificacao;
    private $modificado_por;
    private $status;

    function getId_tipo() {
        return $this->id_tipo;
    }

    function getDescricao() {
        return $this->descricao;
    }

    function getId_pai() {
        return $this->id_pai;
    }

    function getData_cadastro() {
        return $this->data_cadastro;
    }

    function getData_modificacao() {
        return $this->data_modificacao;
    }

    function getModificado_por() {
        return $this->modificado_por;
    }

    function getStatus() {
        return $this->status;
    }

    function setId_tipo($id_tipo) {
        $this->id_tipo = $id_tipo;
    }

    function setDescricao($descricao) {
        $this->descricao = $descricao;
    }

    function setId_pai($id_pai) {
        $this->id_pai = $id_pai;
    }

    function setData_cadastro($data_cadastro) {
        $this->data_cadastro = $data_cadastro;
    }

    function setData_modificacao($data_modificacao) {
        $this->data_modificacao = $data_modificacao;
    }

    function setModificado_por($modificado_por) {
        $this->modificado_por = $modificado_por;
    }

    function setStatus($status) {
        $this->status = $status;
    }

    public static function getOpcoesSelecao($idTipo){
        try{
             $pdo = parent::getDB();

                $query = $pdo->prepare("SELECT `id_tipo`, `descricao` "
                        . "FROM `tipo_usuario` WHERE `status` = ? AND id_tipo != '1'" );

                $query->bindValue(1, "1");

                $query->execute();

                $option = "";

               while($row = $query->fetch(PDO::FETCH_OBJ)){
                   $selecionado = "";

                    if($idTipo == $row->id_tipo){
                        $selecionado = "selected='selected'";
                    }

                    $option = $option . "<option value='".$row->id_tipo."' $selecionado>".$row->descricao."</option>";
               }

                return $option;
        } catch (Exception $ex) {
            return "";
        }
    }

    public static function getLinhasTabela(){
        try{
            $pdo = parent::getDB();

            $query = $pdo->prepare("SELECT * FROM `tipo_usuario` WHERE `status` = ?" );

            $query->bindValue(1, "1");
            $query->execute();

            $linhas = "";
            while($row = $query->fetch(PDO::FETCH_OBJ)){
                $linhas = $linhas . "
"
                        . "".$row->id_tipo."	"
                        . "".$row->descricao."	"
                        . "
 ";
            }

            return $linhas;
        } catch (Exception $ex) {
            return "";
        }
    }

    public static function getDescricaoPorID($id){
        try{
            $pdo = parent::getDB();

            $query = $pdo->prepare("SELECT descricao FROM `tipo_usuario` WHERE `id_tipo` = ? AND `status` = ?" );

            $query->bindValue(1, $id);
            $query->bindValue(2, "1");
            $query->execute();

            while($row = $query->fetch(PDO::FETCH_OBJ)){
                return $row->descricao;
            }

            return "";
        } catch (Exception $ex) {
            return "";
        }
    }

}


text:
package org.apache.spark.sql.catalyst.expressions

import scala.reflect.ClassTag

import org.scalacheck.Gen
import org.scalactic.TripleEqualsSupport.Spread
import org.scalatest.exceptions.TestFailedException
import org.scalatest.prop.GeneratorDrivenPropertyChecks

import org.apache.spark.{SparkConf, SparkFunSuite}
import org.apache.spark.serializer.JavaSerializer
import org.apache.spark.sql.Row
import org.apache.spark.sql.catalyst.{CatalystTypeConverters, InternalRow}
import org.apache.spark.sql.catalyst.analysis.{ResolveTimeZone, SimpleAnalyzer}
import org.apache.spark.sql.catalyst.expressions.codegen._
import org.apache.spark.sql.catalyst.optimizer.SimpleTestOptimizer
import org.apache.spark.sql.catalyst.plans.logical.{OneRowRelation, Project}
import org.apache.spark.sql.catalyst.util.{ArrayData, MapData}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._
import org.apache.spark.util.Utils

/**
 * A few helper functions for expression evaluation testing. Mixin this trait to use them.
 */
trait ExpressionEvalHelper extends GeneratorDrivenPropertyChecks {
  self: SparkFunSuite =>

  protected def create_row(values: Any*): InternalRow = {
    InternalRow.fromSeq(values.map(CatalystTypeConverters.convertToCatalyst))
  }

  private def prepareEvaluation(expression: Expression): Expression = {
    val serializer = new JavaSerializer(new SparkConf()).newInstance
    val resolver = ResolveTimeZone(new SQLConf)
    resolver.resolveTimeZones(serializer.deserialize(serializer.serialize(expression)))
  }

  protected def checkEvaluation(
      expression: => Expression, expected: Any, inputRow: InternalRow = EmptyRow): Unit = {
    // Make it as method to obtain fresh expression everytime.
    def expr = prepareEvaluation(expression)
    val catalystValue = CatalystTypeConverters.convertToCatalyst(expected)
    checkEvaluationWithoutCodegen(expr, catalystValue, inputRow)
    checkEvaluationWithGeneratedMutableProjection(expr, catalystValue, inputRow)
    if (GenerateUnsafeProjection.canSupport(expr.dataType)) {
      checkEvaluationWithUnsafeProjection(expr, catalystValue, inputRow)
    }
    checkEvaluationWithOptimization(expr, catalystValue, inputRow)
  }

  /**
   * Check the equality between result of expression and expected value, it will handle
   * Array[Byte], Spread[Double], MapData and Row.
   */
  protected def checkResult(result: Any, expected: Any, exprDataType: DataType): Boolean = {
    val dataType = UserDefinedType.sqlType(exprDataType)

    (result, expected) match {
      case (result: Array[Byte], expected: Array[Byte]) =>
        java.util.Arrays.equals(result, expected)
      case (result: Double, expected: Spread[Double @unchecked]) =>
        expected.asInstanceOf[Spread[Double]].isWithin(result)
      case (result: ArrayData, expected: ArrayData) =>
        result.numElements == expected.numElements && {
          val et = dataType.asInstanceOf[ArrayType].elementType
          var isSame = true
          var i = 0
          while (isSame && i < result.numElements) {
            isSame = checkResult(result.get(i, et), expected.get(i, et), et)
            i += 1
          }
          isSame
        }
      case (result: MapData, expected: MapData) =>
        val kt = dataType.asInstanceOf[MapType].keyType
        val vt = dataType.asInstanceOf[MapType].valueType
        checkResult(result.keyArray, expected.keyArray, ArrayType(kt)) &&
          checkResult(result.valueArray, expected.valueArray, ArrayType(vt))
      case (result: Double, expected: Double) =>
        if (expected.isNaN) result.isNaN else expected == result
      case (result: Float, expected: Float) =>
        if (expected.isNaN) result.isNaN else expected == result
      case (result: Row, expected: InternalRow) => result.toSeq == expected.toSeq(result.schema)
      case _ =>
        result == expected
    }
  }

  protected def checkExceptionInExpression[T <: Throwable : ClassTag](
      expression: => Expression,
      inputRow: InternalRow,
      expectedErrMsg: String): Unit = {

    def checkException(eval: => Unit, testMode: String): Unit = {
      withClue(s"($testMode)") {
        val errMsg = intercept[T] {
          eval
        }.getMessage
        if (!errMsg.contains(expectedErrMsg)) {
          fail(s"Expected error message is `$expectedErrMsg`, but `$errMsg` found")
        }
      }
    }

    // Make it as method to obtain fresh expression everytime.
    def expr = prepareEvaluation(expression)
    checkException(evaluateWithoutCodegen(expr, inputRow), "non-codegen mode")
    checkException(evaluateWithGeneratedMutableProjection(expr, inputRow), "codegen mode")
    if (GenerateUnsafeProjection.canSupport(expr.dataType)) {
      checkException(evaluateWithUnsafeProjection(expr, inputRow), "unsafe mode")
    }
  }

  protected def evaluateWithoutCodegen(
      expression: Expression, inputRow: InternalRow = EmptyRow): Any = {
    expression.foreach {
      case n: Nondeterministic => n.initialize(0)
      case _ =>
    }
    expression.eval(inputRow)
  }

  protected def generateProject(
      generator: => Projection,
      expression: Expression): Projection = {
    try {
      generator
    } catch {
      case e: Throwable =>
        fail(
          s"""
            |Code generation of $expression failed:
            |$e
            |${Utils.exceptionString(e)}
          """.stripMargin)
    }
  }

  protected def checkEvaluationWithoutCodegen(
      expression: Expression,
      expected: Any,
      inputRow: InternalRow = EmptyRow): Unit = {

    val actual = try evaluateWithoutCodegen(expression, inputRow) catch {
      case e: Exception => fail(s"Exception evaluating $expression", e)
    }
    if (!checkResult(actual, expected, expression.dataType)) {
      val input = if (inputRow == EmptyRow) "" else s", input: $inputRow"
      fail(s"Incorrect evaluation (codegen off): $expression, " +
        s"actual: $actual, " +
        s"expected: $expected$input")
    }
  }

  protected def checkEvaluationWithGeneratedMutableProjection(
      expression: Expression,
      expected: Any,
      inputRow: InternalRow = EmptyRow): Unit = {
    val actual = evaluateWithGeneratedMutableProjection(expression, inputRow)
    if (!checkResult(actual, expected, expression.dataType)) {
      val input = if (inputRow == EmptyRow) "" else s", input: $inputRow"
      fail(s"Incorrect evaluation: $expression, actual: $actual, expected: $expected$input")
    }
  }

  protected def evaluateWithGeneratedMutableProjection(
      expression: Expression,
      inputRow: InternalRow = EmptyRow): Any = {
    val plan = generateProject(
      GenerateMutableProjection.generate(Alias(expression, s"Optimized($expression)")() :: Nil),
      expression)
    plan.initialize(0)

    plan(inputRow).get(0, expression.dataType)
  }

  protected def checkEvaluationWithUnsafeProjection(
      expression: Expression,
      expected: Any,
      inputRow: InternalRow = EmptyRow): Unit = {
    checkEvaluationWithUnsafeProjection(expression, expected, inputRow, UnsafeProjection)
    checkEvaluationWithUnsafeProjection(expression, expected, inputRow, InterpretedUnsafeProjection)
  }

  protected def checkEvaluationWithUnsafeProjection(
      expression: Expression,
      expected: Any,
      inputRow: InternalRow,
      factory: UnsafeProjectionCreator): Unit = {
    val unsafeRow = evaluateWithUnsafeProjection(expression, inputRow, factory)
    val input = if (inputRow == EmptyRow) "" else s", input: $inputRow"

    if (expected == null) {
      if (!unsafeRow.isNullAt(0)) {
        val expectedRow = InternalRow(expected, expected)
        fail("Incorrect evaluation in unsafe mode: " +
          s"$expression, actual: $unsafeRow, expected: $expectedRow$input")
      }
    } else {
      val lit = InternalRow(expected, expected)
      val expectedRow =
        factory.create(Array(expression.dataType, expression.dataType)).apply(lit)
      if (unsafeRow != expectedRow) {
        fail("Incorrect evaluation in unsafe mode: " +
          s"$expression, actual: $unsafeRow, expected: $expectedRow$input")
      }
    }
  }

  protected def evaluateWithUnsafeProjection(
      expression: Expression,
      inputRow: InternalRow = EmptyRow,
      factory: UnsafeProjectionCreator = UnsafeProjection): InternalRow = {
    // SPARK-16489 Explicitly doing code generation twice so code gen will fail if
    // some expression is reusing variable names across different instances.
    // This behavior is tested in ExpressionEvalHelperSuite.
    val plan = generateProject(
      UnsafeProjection.create(
        Alias(expression, s"Optimized($expression)1")() ::
          Alias(expression, s"Optimized($expression)2")() :: Nil),
      expression)

    plan.initialize(0)
    plan(inputRow)
  }

  protected def checkEvaluationWithOptimization(
      expression: Expression,
      expected: Any,
      inputRow: InternalRow = EmptyRow): Unit = {
    val plan = Project(Alias(expression, s"Optimized($expression)")() :: Nil, OneRowRelation())
    // We should analyze the plan first, otherwise we possibly optimize an unresolved plan.
    val analyzedPlan = SimpleAnalyzer.execute(plan)
    val optimizedPlan = SimpleTestOptimizer.execute(analyzedPlan)
    checkEvaluationWithoutCodegen(optimizedPlan.expressions.head, expected, inputRow)
  }

  protected def checkDoubleEvaluation(
      expression: => Expression,
      expected: Spread[Double],
      inputRow: InternalRow = EmptyRow): Unit = {
    checkEvaluationWithoutCodegen(expression, expected)
    checkEvaluationWithGeneratedMutableProjection(expression, expected)
    checkEvaluationWithOptimization(expression, expected)

    var plan = generateProject(
      GenerateMutableProjection.generate(Alias(expression, s"Optimized($expression)")() :: Nil),
      expression)
    plan.initialize(0)
    var actual = plan(inputRow).get(0, expression.dataType)
    assert(checkResult(actual, expected, expression.dataType))

    plan = generateProject(
      GenerateUnsafeProjection.generate(Alias(expression, s"Optimized($expression)")() :: Nil),
      expression)
    plan.initialize(0)
    actual = FromUnsafeProjection(expression.dataType :: Nil)(
      plan(inputRow)).get(0, expression.dataType)
    assert(checkResult(actual, expected, expression.dataType))
  }

  /**
   * Test evaluation results between Interpreted mode and Codegen mode, making sure we have
   * consistent result regardless of the evaluation method we use.
   *
   * This method test against unary expressions by feeding them arbitrary literals of `dataType`.
   */
  def checkConsistencyBetweenInterpretedAndCodegen(
      c: Expression => Expression,
      dataType: DataType): Unit = {
    forAll (LiteralGenerator.randomGen(dataType)) { (l: Literal) =>
      cmpInterpretWithCodegen(EmptyRow, c(l))
    }
  }

  /**
   * Test evaluation results between Interpreted mode and Codegen mode, making sure we have
   * consistent result regardless of the evaluation method we use.
   *
   * This method test against binary expressions by feeding them arbitrary literals of `dataType1`
   * and `dataType2`.
   */
  def checkConsistencyBetweenInterpretedAndCodegen(
      c: (Expression, Expression) => Expression,
      dataType1: DataType,
      dataType2: DataType): Unit = {
    forAll (
      LiteralGenerator.randomGen(dataType1),
      LiteralGenerator.randomGen(dataType2)
    ) { (l1: Literal, l2: Literal) =>
      cmpInterpretWithCodegen(EmptyRow, c(l1, l2))
    }
  }

  /**
   * Test evaluation results between Interpreted mode and Codegen mode, making sure we have
   * consistent result regardless of the evaluation method we use.
   *
   * This method test against ternary expressions by feeding them arbitrary literals of `dataType1`,
   * `dataType2` and `dataType3`.
   */
  def checkConsistencyBetweenInterpretedAndCodegen(
      c: (Expression, Expression, Expression) => Expression,
      dataType1: DataType,
      dataType2: DataType,
      dataType3: DataType): Unit = {
    forAll (
      LiteralGenerator.randomGen(dataType1),
      LiteralGenerator.randomGen(dataType2),
      LiteralGenerator.randomGen(dataType3)
    ) { (l1: Literal, l2: Literal, l3: Literal) =>
      cmpInterpretWithCodegen(EmptyRow, c(l1, l2, l3))
    }
  }

  /**
   * Test evaluation results between Interpreted mode and Codegen mode, making sure we have
   * consistent result regardless of the evaluation method we use.
   *
   * This method test against expressions take Seq[Expression] as input by feeding them
   * arbitrary length Seq of arbitrary literal of `dataType`.
   */
  def checkConsistencyBetweenInterpretedAndCodegen(
      c: Seq[Expression] => Expression,
      dataType: DataType,
      minNumElements: Int = 0): Unit = {
    forAll (Gen.listOf(LiteralGenerator.randomGen(dataType))) { (literals: Seq[Literal]) =>
      whenever(literals.size >= minNumElements) {
        cmpInterpretWithCodegen(EmptyRow, c(literals))
      }
    }
  }

  private def cmpInterpretWithCodegen(inputRow: InternalRow, expr: Expression): Unit = {
    val interpret = try {
      evaluateWithoutCodegen(expr, inputRow)
    } catch {
      case e: Exception => fail(s"Exception evaluating $expr", e)
    }

    val plan = generateProject(
      GenerateMutableProjection.generate(Alias(expr, s"Optimized($expr)")() :: Nil),
      expr)
    val codegen = plan(inputRow).get(0, expr.dataType)

    if (!compareResults(interpret, codegen)) {
      fail(s"Incorrect evaluation: $expr, interpret: $interpret, codegen: $codegen")
    }
  }

  /**
   * Check the equality between result of expression and expected value, it will handle
   * Array[Byte] and Spread[Double].
   */
  private[this] def compareResults(result: Any, expected: Any): Boolean = {
    (result, expected) match {
      case (result: Array[Byte], expected: Array[Byte]) =>
        java.util.Arrays.equals(result, expected)
      case (result: Double, expected: Double) if result.isNaN && expected.isNaN =>
        true
      case (result: Double, expected: Double) =>
        relativeErrorComparison(result, expected)
      case (result: Float, expected: Float) if result.isNaN && expected.isNaN =>
        true
      case _ => result == expected
    }
  }

  /**
   * Private helper function for comparing two values using relative tolerance.
   * Note that if x or y is extremely close to zero, i.e., smaller than Double.MinPositiveValue,
   * the relative tolerance is meaningless, so the exception will be raised to warn users.
   *
   * TODO: this duplicates functions in spark.ml.util.TestingUtils.relTol and
   * spark.mllib.util.TestingUtils.relTol, they could be moved to common utils sub module for the
   * whole spark project which does not depend on other modules. See more detail in discussion:
   * https://github.com/apache/spark/pull/15059#issuecomment-246940444
   */
  private def relativeErrorComparison(x: Double, y: Double, eps: Double = 1E-8): Boolean = {
    val absX = math.abs(x)
    val absY = math.abs(y)
    val diff = math.abs(x - y)
    if (x == y) {
      true
    } else if (absX < Double.MinPositiveValue || absY < Double.MinPositiveValue) {
      throw new TestFailedException(
        s"$x or $y is extremely close to zero, so the relative tolerance is meaningless.", 0)
    } else {
      diff < eps * math.min(absX, absY)
    }
  }
}


text:
package it.unibz.inf.ontop.rdf4j.repository.impl;

import com.google.common.collect.ImmutableMultimap;
import it.unibz.inf.ontop.answering.connection.OntopConnection;
import it.unibz.inf.ontop.answering.reformulation.input.RDF4JInputQueryFactory;
import it.unibz.inf.ontop.answering.reformulation.input.SPARQLQuery;
import it.unibz.inf.ontop.exception.OntopConnectionException;
import it.unibz.inf.ontop.exception.OntopReformulationException;
import it.unibz.inf.ontop.injection.OntopSystemSettings;
import it.unibz.inf.ontop.rdf4j.query.impl.*;
import it.unibz.inf.ontop.rdf4j.repository.OntopRepository;
import it.unibz.inf.ontop.rdf4j.repository.OntopRepositoryConnection;
import org.eclipse.rdf4j.IsolationLevel;
import org.eclipse.rdf4j.IsolationLevels;
import org.eclipse.rdf4j.common.iteration.CloseableIteratorIteration;
import org.eclipse.rdf4j.model.*;
import org.eclipse.rdf4j.model.impl.NamespaceImpl;
import org.eclipse.rdf4j.model.impl.ValueFactoryImpl;
import org.eclipse.rdf4j.query.*;
import org.eclipse.rdf4j.query.parser.*;
import org.eclipse.rdf4j.queryrender.RenderUtils;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.RepositoryException;
import org.eclipse.rdf4j.repository.RepositoryResult;
import org.eclipse.rdf4j.rio.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.net.URL;
import java.util.*;

public class OntopRepositoryConnectionImpl implements OntopRepositoryConnection {

    private static final String READ_ONLY_MESSAGE = "Ontop is a read-only system";
    private static Logger LOGGER = LoggerFactory.getLogger(OntopRepositoryConnectionImpl.class);
    private OntopRepository repository;
    private OntopConnection ontopConnection;
    private final RDF4JInputQueryFactory inputQueryFactory;
    private final OntopSystemSettings settings;
    private boolean isOpen;
    private boolean isActive;
    private RDFParser rdfParser;
    private Map<String, String> namespaces;

    OntopRepositoryConnectionImpl(OntopRepository rep, OntopConnection connection,
                                  RDF4JInputQueryFactory inputQueryFactory, OntopSystemSettings settings) {
        this.repository = rep;
        this.ontopConnection = connection;
        this.inputQueryFactory = inputQueryFactory;
        this.settings = settings;
        this.isOpen = true;
        this.isActive = false;
        this.rdfParser = Rio.createParser(RDFFormat.RDFXML, this.repository.getValueFactory());
        this.namespaces = new HashMap<>();
    }

    @Override
    public void add(Statement st, Resource... contexts) throws RepositoryException {
        throw new RepositoryException(READ_ONLY_MESSAGE);
    }

    @Override
    public void add(Iterable<? extends Statement> statements, Resource... contexts)
            throws RepositoryException {
        throw new RepositoryException(READ_ONLY_MESSAGE);
    }

    @Override
    public void add(File file, String baseIRI, RDFFormat dataFormat, Resource... contexts)
            throws IOException, RDFParseException, RepositoryException {
        throw new RepositoryException(READ_ONLY_MESSAGE);
    }

    @Override
    public void add(URL url, String baseIRI, RDFFormat dataFormat,
                    Resource... contexts) throws IOException,
            RDFParseException, RepositoryException {
        throw new RepositoryException(READ_ONLY_MESSAGE);
    }

    @Override
    public void add(InputStream in, String baseIRI,
                    RDFFormat dataFormat, Resource... contexts)
            throws IOException, RDFParseException, RepositoryException {
        throw new RepositoryException(READ_ONLY_MESSAGE);
    }

    @Override
    public void add(Reader reader, String baseIRI,
                    RDFFormat dataFormat, Resource... contexts)
            throws IOException, RDFParseException, RepositoryException {
        throw new RepositoryException(READ_ONLY_MESSAGE);
    }

    @Override
    public void add(Resource subject, org.eclipse.rdf4j.model.IRI predicate, Value object, Resource... contexts)
            throws RepositoryException {
        throw new RepositoryException(READ_ONLY_MESSAGE);
    }

    @Override
    public void clear(Resource... contexts) throws RepositoryException {
        throw new RepositoryException(READ_ONLY_MESSAGE);
    }

    @Override
    public void clearNamespaces() throws RepositoryException {
        //Removes all namespace declarations from the repository.
        remove(null, null, null, (Resource[]) null);

    }

    @Override
    public void close() throws RepositoryException {
        //Closes the connection, freeing resources.
        //If the connection is not in autoCommit mode,
        //all non-committed operations will be lost.
        isOpen = false;
        try {
            ontopConnection.close();
        } catch (Exception e) {
            throw new RepositoryException(e);
        }
    }

    @Override
    public void commit() throws RepositoryException {
        // Commits all updates that have been performed as part of this
        // connection sofar.
        if (isActive()) {
            try {
                // System.out.println("QuestConn commit..");
                ontopConnection.commit();
                this.isActive = false;
            } catch (OntopConnectionException e) {
                throw new RepositoryException(e);
            }
        } else {
            throw new RepositoryException(
                    "Connection does not have an active transaction.");
        }
    }

    @Override
    public void export(RDFHandler handler, Resource... contexts)
            throws RepositoryException, RDFHandlerException {
        //Exports all explicit statements in the specified contexts to the supplied RDFHandler.
        exportStatements(null, null, null, false, handler, contexts);
    }

    @Override
    public void exportStatements(Resource subj, IRI pred, Value obj,
                                 boolean includeInferred, RDFHandler handler, Resource... contexts)
            throws RepositoryException, RDFHandlerException {
        //Exports all statements with a specific subject, predicate
        //and/or object from the repository, optionally from the specified contexts.
        RepositoryResult<Statement> stms = getStatements(subj, pred, obj, includeInferred, contexts);

        handler.startRDF();
        // handle
        if (stms != null) {
            while (stms.hasNext()) {
                Statement st = stms.next();
                if (st != null)
                    handler.handleStatement(st);
            }
        }
        handler.endRDF();

    }

    @Override
    public RepositoryResult<Resource> getContextIDs()
            throws RepositoryException {
        //Gets all resources that are used as content identifiers.
        //Care should be taken that the returned RepositoryResult
        //is closed to free any resources that it keeps hold of.
        List<Resource> contexts = new LinkedList<Resource>();
        return new RepositoryResult<Resource>(new CloseableIteratorIteration<Resource, RepositoryException>(contexts.iterator()));
    }

    @Override
    public String getNamespace(String prefix) throws RepositoryException {
        //Gets the namespace that is associated with the specified prefix, if any.
        return namespaces.get(prefix);
    }

    @Override
    public RepositoryResult<Namespace> getNamespaces()
            throws RepositoryException {
        //Gets all declared namespaces as a RepositoryResult of Namespace objects.
        //Each Namespace object consists of a prefix and a namespace name.
        Set<Namespace> namespSet = new HashSet<Namespace>();
        Map<String, String> namesp = namespaces;
        Set<String> keys = namesp.keySet();
        for (String key : keys) {
            //convert into namespace objects
            namespSet.add(new NamespaceImpl(key, namesp.get(key)));
        }
        return new RepositoryResult<Namespace>(new CloseableIteratorIteration<Namespace, RepositoryException>(
                namespSet.iterator()));
    }

    @Override
    public ParserConfig getParserConfig() {
        //Returns the parser configuration this connection uses for Rio-based operations.
        return rdfParser.getParserConfig();
    }

    @Override
    public Repository getRepository() {
        //Returns the Repository object to which this connection belongs.
        return this.repository;
    }

    @Override
    public RepositoryResult<Statement> getStatements(Resource subj, org.eclipse.rdf4j.model.IRI pred,
                                                     Value obj, boolean includeInferred, Resource... contexts)
            throws RepositoryException {
        //Gets all statements with a specific subject,
        //predicate and/or object from the repository.
        //The result is optionally restricted to the specified set of named contexts.

        //construct query for it
        StringBuilder queryString = new StringBuilder("CONSTRUCT {");

        StringBuilder spo = subj == null ? new StringBuilder("?s ") : RenderUtils.toSPARQL(subj, new StringBuilder());

        spo = pred == null ? spo.append(" ?p ") : RenderUtils.toSPARQL(pred, spo);

        spo = obj == null ? spo.append(" ?o ") : RenderUtils.toSPARQL(obj, spo);

        queryString.append(spo).append("} WHERE {").append(spo).append("}");

        //execute construct query
        try {
            if (contexts.length == 0 || (contexts.length > 0 && contexts[0] == null)) {
                GraphQuery query = prepareGraphQuery(QueryLanguage.SPARQL,
                        queryString.toString());
                GraphQueryResult result = query.evaluate();
                return new RepositoryResult<>(new CloseableIteratorIteration<>(result.iterator()));
            }
            return new RepositoryResult<>(new CloseableIteratorIteration<>());
        } catch (MalformedQueryException | QueryEvaluationException e) {
            throw new RepositoryException(e);
        }
    }

    @Override
    public ValueFactory getValueFactory() {
        //Gets a ValueFactory for this OntopRepositoryConnection.
        return new ValueFactoryImpl();
    }

    @Override
    public boolean hasStatement(Statement st, boolean includeInferred, Resource... contexts)
            throws RepositoryException {
        //Checks whether the repository contains the specified statement,
        //optionally in the specified contexts.
        return hasStatement(st.getSubject(), st.getPredicate(), st
                .getObject(), includeInferred, contexts);
    }

    @Override
    public boolean hasStatement(Resource subj, org.eclipse.rdf4j.model.IRI pred, Value obj,
                                boolean includeInferred, Resource... contexts) throws RepositoryException {
        //Checks whether the repository contains statements with a specific subject,
        //predicate and/or object, optionally in the specified contexts.
        RepositoryResult<Statement> stIter = getStatements(subj, pred,
                obj, includeInferred, contexts);
        try {
            return stIter.hasNext();
        } finally {
            stIter.close();
        }
    }

    @Override
    public boolean isAutoCommit() throws RepositoryException {
        //Checks whether the connection is in auto-commit mode.
        try {
            return ontopConnection.getAutoCommit();
        } catch (OntopConnectionException e) {
            throw new RepositoryException(e);
        }
    }

    @Override
    public boolean isEmpty() throws RepositoryException {
        //Returns true if this repository does not contain any (explicit) statements.
        return size() == 0;
    }

    @Override
    public boolean isOpen() throws RepositoryException {
        //Checks whether this connection is open.
        //A connection is open from the moment it is created until it is closed.
        return this.isOpen;
    }

    @Override
    public BooleanQuery prepareBooleanQuery(QueryLanguage ql, String query)
            throws RepositoryException, MalformedQueryException {
        //Prepares true/false queries. In case the query contains
        //relative IRIs that need to be resolved against an external base IRI,
        //one should use prepareBooleanQuery(QueryLanguage, String, String) instead.
        return prepareBooleanQuery(ql, query, null);
    }

    @Override
    public BooleanQuery prepareBooleanQuery(QueryLanguage ql, String queryString,
                                            String baseIRI) throws RepositoryException, MalformedQueryException {
        return prepareBooleanQuery(ql, queryString, baseIRI, ImmutableMultimap.of());
    }

    @Override
    public BooleanQuery prepareBooleanQuery(QueryLanguage ql, String queryString,
                String baseIRI, ImmutableMultimap<String, String> httpHeaders) throws RepositoryException, MalformedQueryException {
        //Prepares true/false queries.
        if (ql != QueryLanguage.SPARQL)
            throw new MalformedQueryException("SPARQL query expected!");

        String safeBaseIRI = baseIRI == null
                ? null
                : baseIRI.isEmpty() ? null : baseIRI;

        ParsedQuery q = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, queryString, safeBaseIRI);
        return new OntopBooleanQuery(queryString, q, safeBaseIRI, ontopConnection, httpHeaders, inputQueryFactory, settings);
    }

    @Override
    public GraphQuery prepareGraphQuery(QueryLanguage ql, String queryString)
            throws RepositoryException, MalformedQueryException {
        //Prepares queries that produce RDF graphs. In case the query
        //contains relative IRIs that need to be resolved against an
        //external base IRI, one should use prepareGraphQuery(QueryLanguage, String, String) instead.
        return prepareGraphQuery(ql, queryString, null);
    }

    @Override
    public GraphQuery prepareGraphQuery(QueryLanguage ql, String queryString, String baseIRI)
            throws RepositoryException, MalformedQueryException {
        return prepareGraphQuery(ql, queryString, baseIRI, ImmutableMultimap.of());
    }

    @Override
    public GraphQuery prepareGraphQuery(QueryLanguage ql, String queryString,
                                        String baseIRI, ImmutableMultimap<String, String> httpHeaders)
            throws RepositoryException, MalformedQueryException {
        //Prepares queries that produce RDF graphs.
        if (ql != QueryLanguage.SPARQL)
            throw new MalformedQueryException("SPARQL query expected!");

        String safeBaseIRI = baseIRI == null
                ? null
                : baseIRI.isEmpty() ? null : baseIRI;

        ParsedQuery q = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, queryString, safeBaseIRI);
        return new OntopGraphQuery(queryString, q, safeBaseIRI, ontopConnection, httpHeaders, inputQueryFactory, settings);

    }

    @Override
    public Query prepareQuery(QueryLanguage ql, String query)
            throws RepositoryException, MalformedQueryException {
        //Prepares a query for evaluation on this repository (optional operation).
        //In case the query contains relative IRIs that need to be resolved against
        //an external base IRI, one should use prepareQuery(QueryLanguage, String, String) instead.
        return prepareTupleQuery(ql, query, null, ImmutableMultimap.of());
    }

    @Override
    public Query prepareQuery(QueryLanguage ql, String query, ImmutableMultimap<String, String> httpHeaders)
            throws RepositoryException, MalformedQueryException {
        //Prepares a query for evaluation on this repository (optional operation).
        //In case the query contains relative IRIs that need to be resolved against
        //an external base IRI, one should use prepareQuery(QueryLanguage, String, String) instead.
        return prepareQuery(ql, query, null, httpHeaders);
    }

    @Override
    public Query prepareQuery(QueryLanguage ql, String queryString, String baseIRI)
            throws RepositoryException, MalformedQueryException {
        return prepareQuery(ql, queryString, baseIRI, ImmutableMultimap.of());
    }

    @Override
    public Query prepareQuery(QueryLanguage ql, String queryString, String baseIRI,
                              ImmutableMultimap<String, String> httpHeaders)
            throws RepositoryException, MalformedQueryException {
        if (ql != QueryLanguage.SPARQL)
            throw new MalformedQueryException("SPARQL query expected! ");

        long beforeParsing = System.currentTimeMillis();
        ParsedQuery q = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, queryString, baseIRI);
        LOGGER.debug(String.format("Parsing time: %d ms", System.currentTimeMillis() - beforeParsing));

        if (q instanceof ParsedTupleQuery)
            return new OntopTupleQuery(queryString, q, baseIRI, ontopConnection, httpHeaders, inputQueryFactory, settings);
        else if (q instanceof ParsedBooleanQuery)
            return new OntopBooleanQuery(queryString, q, baseIRI, ontopConnection, httpHeaders, inputQueryFactory, settings);
        else if (q instanceof ParsedGraphQuery)
            return new OntopGraphQuery(queryString, q, baseIRI, ontopConnection, httpHeaders, inputQueryFactory, settings);
        else
            throw new MalformedQueryException("Unrecognized query type. " + queryString);
    }

    @Override
    public TupleQuery prepareTupleQuery(QueryLanguage ql, String query)
            throws RepositoryException, MalformedQueryException {
        //Prepares a query that produces sets of value tuples.
        //In case the query contains relative IRIs that need to be
        //resolved against an external base IRI, one should use
        //prepareTupleQuery(QueryLanguage, String, String) instead.
        return this.prepareTupleQuery(ql, query, "");
    }

    @Override
    public TupleQuery prepareTupleQuery(QueryLanguage ql, String queryString, String baseIRI)
            throws RepositoryException, MalformedQueryException {
        return prepareTupleQuery(ql, queryString, baseIRI, ImmutableMultimap.of());
    }

    @Override
    public TupleQuery prepareTupleQuery(QueryLanguage ql, String queryString, String baseIRI,
                                        ImmutableMultimap<String, String> httpHeaders)
            throws RepositoryException, MalformedQueryException {
        //Prepares a query that produces sets of value tuples.
        if (ql != QueryLanguage.SPARQL)
            throw new MalformedQueryException("SPARQL query expected!");

        String safeBaseIRI = baseIRI == null
                ? null
                : baseIRI.isEmpty() ? null : baseIRI;
        ParsedQuery q = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, queryString, safeBaseIRI);

        return new OntopTupleQuery(queryString, q, safeBaseIRI, ontopConnection, httpHeaders, inputQueryFactory, settings);
    }

    @Override
    public Update prepareUpdate(QueryLanguage arg0, String arg1)
            throws RepositoryException, MalformedQueryException {
        throw new RepositoryException(READ_ONLY_MESSAGE);
    }

    @Override
    public Update prepareUpdate(QueryLanguage arg0, String arg1, String arg2)
            throws RepositoryException, MalformedQueryException {
        throw new RepositoryException(READ_ONLY_MESSAGE);
    }

    @Override
    public void remove(Statement st, Resource... contexts)
            throws RepositoryException {
        throw new RepositoryException(READ_ONLY_MESSAGE);
    }

    @Override
    public void remove(Iterable<? extends Statement> statements, Resource... contexts)
            throws RepositoryException {
        throw new RepositoryException(READ_ONLY_MESSAGE);
    }

    @Override
    public void remove(Resource subject, org.eclipse.rdf4j.model.IRI predicate, Value object, Resource... contexts)
            throws RepositoryException {
        throw new RepositoryException(READ_ONLY_MESSAGE);
    }

    @Override
    public void removeNamespace(String key) throws RepositoryException {
        //Removes a namespace declaration by removing the association between a prefix and a namespace name.
        namespaces.remove(key);
    }

    @Override
    public void rollback() throws RepositoryException {
        // Rolls back all updates that have been performed as part of this
        // connection sofar.
        if (isActive()) {
            try {
                this.ontopConnection.rollBack();
                this.isActive = false;
            } catch (OntopConnectionException e) {
                throw new RepositoryException(e);
            }
        } else {
            throw new RepositoryException(
                    "Connection does not have an active transaction.");
        }
    }

    @Override
    public void setAutoCommit(boolean autoCommit) throws RepositoryException {
        //Enables or disables auto-commit mode for the connection.
        //If a connection is in auto-commit mode, then all updates
        //will be executed and committed as individual transactions.
        //Otherwise, the updates are grouped into transactions that are
        // terminated by a call to either commit() or rollback().
        // By default, new connections are in auto-commit mode.
        try {
            if (autoCommit == this.ontopConnection.getAutoCommit()) {
                return;
            }
        } catch (OntopConnectionException e) {
            throw new RepositoryException(e);
        }
        if (isActive()) {
            try {
                this.ontopConnection.setAutoCommit(autoCommit);
            } catch (OntopConnectionException e) {
                throw new RepositoryException(e);

            }

            // if we are switching from non-autoCommit to autoCommit mode,
            // commit any
            // pending updates
            if (autoCommit) {
                commit();
            }
        } else if (!autoCommit) {
            // begin a transaction
            begin();
        }

    }

    @Override
    public void setNamespace(String key, String value)
            throws RepositoryException {
        //Sets the prefix for a namespace.
        namespaces.put(key, value);

    }

    @Override
    public void setParserConfig(ParserConfig config) {
        //Set the parser configuration this connection should use for RDFParser-based operations.
        rdfParser.setParserConfig(config);
    }

    @Override
    public long size(Resource... contexts) throws RepositoryException {
        //Returns the number of (explicit) statements that are in the specified contexts in this repository.
        return 0;
    }

    /**
     * Call this method to start a transaction. Have to call commit() or
     * rollback() to mark end of transaction.
     */
    @Override
    public void begin() throws RepositoryException {
        // TODO Auto-generated method stub
        if (!isOpen()) {
            throw new RepositoryException("Connection was closed.");
        }
        isActive = true;
    }

    /**
     * A boolean flag signaling when a transaction is active.
     */
    @Override
    public boolean isActive() {
        return this.isActive;
    }

    @Override
    public void setIsolationLevel(IsolationLevel level) throws IllegalStateException {
        if (level != IsolationLevels.NONE)
            throw new UnsupportedOperationException();
    }

    @Override
    public IsolationLevel getIsolationLevel() {
        return IsolationLevels.NONE;
    }

    @Override
    public void begin(IsolationLevel level) throws RepositoryException {
        // do nothing
    }

    @Override
    public <E extends Exception> void add(
            org.eclipse.rdf4j.common.iteration.Iteration<? extends Statement, E> statements, Resource... contexts)
            throws RepositoryException, E {
        throw new UnsupportedOperationException(READ_ONLY_MESSAGE);
    }

    @Override
    public <E extends Exception> void remove(
            org.eclipse.rdf4j.common.iteration.Iteration<? extends Statement, E> statements, Resource... contexts)
            throws RepositoryException, E {
        throw new UnsupportedOperationException(READ_ONLY_MESSAGE);
    }

    @Override
    public String reformulate(String sparql)
            throws RepositoryException {
        try {
            SPARQLQuery sparqlQuery = ontopConnection.getInputQueryFactory().createSPARQLQuery(sparql);
            return ontopConnection.createStatement().getExecutableQuery(sparqlQuery).toString();
        } catch (OntopReformulationException | OntopConnectionException e) {
            throw new RepositoryException(e);
        }
    }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

angular.module('eappApp').component("resultFilter",
{
    templateUrl : "templates/components/resultFilter.html",
    controller : ResultFilterController,
    bindings :
    {
        resultSet : '<',
        distance : '<',
        onSettingsChanged : '&',
        ready : '=',
        type : '@',
        onRefresh : '&',
        onDistanceChanged : '&',
        isUserLogged : '<'
    }
});

function ResultFilterController($scope, profileData, appService)
{
    var ctrl = this;

    $scope.trueVal = true;

    $scope.falseVal = false;

    $scope.viewConfig = {};

    ctrl.$onInit = function()
    {
        ctrl.settings = ctrl.resultSet;
        $scope.settings = ctrl.resultSet;
        $scope.viewConfig = profileData.instance;
        $scope.distance = ctrl.distance;
        $scope.isUserLogged = appService.isUserLogged;

        if(ctrl.type === 'CART')
        {
            $scope.viewConfig.viewAll = !$scope.viewConfig.optimizedCart;
            $scope.showAllResultsCaption = "Voir liste originale";
            $scope.showOptimizedResultsCaption = "Voir liste optimisée";
            $scope.isCart = true;
        }
        else
        {
            $scope.showAllResultsCaption = "Voir tous les produits";
            $scope.showOptimizedResultsCaption = "Voir produits optimisés";
        }
    };

    $scope.$watch("settings", function()
    {
        // Get selected items
        $scope.selectedItems = {};

        for(var x in $scope.settings)
        {
            for(var y in $scope.settings[x].values)
            {
                var type = $scope.settings[x].values[y].type;

                if($scope.settings[x].values[y].selected)
                {
                    if(angular.isNullOrUndefined($scope.selectedItems[$scope.settings[x].values[y].type]))
                    {
                        $scope.selectedItems[$scope.settings[x].values[y].type] = { name : $scope.settings[x].setting.caption, items : [] };
                    }

                    $scope.selectedItems[$scope.settings[x].values[y].type].items.push($scope.settings[x].values[y]);
                }
            }
        }
    });

    $scope.getDisplayName = function(name)
    {
        if(name == "0" || name == "1")
        {
            if(name == "0")
            {
                return "Non";
            }
            else
            {
                return "Oui";
            }
        }
        else
        {
            return name;
        }
    };

    ctrl.$onChanges = function(changesObj)
    {
        if(!angular.isNullOrUndefined(changesObj.resultSet))
        {
            $scope.settings = changesObj.resultSet.currentValue;
        }

        if(!angular.isNullOrUndefined(changesObj.distance))
        {
            $scope.distance = changesObj.distance.currentValue;
        }

        if(!angular.isNullOrUndefined(changesObj.isUserLogged))
        {
            $scope.isUserLogged = changesObj.isUserLogged.currentValue;
        }
    };

    $scope.distanceChanged = function()
    {
        ctrl.onDistanceChanged({distance : $scope.distance});
    };

    ctrl.change = function(item)
    {
        ctrl.onSettingsChanged({ item : item});
    };

    ctrl.refresh = function()
    {
        $scope.viewConfig.optimizedCart = !$scope.viewConfig.viewAll;

        ctrl.onRefresh({ userProfileData : $scope.viewConfig });
    };

    ctrl.changeView = function()
    {
        $scope.viewConfig.viewAll = !$scope.viewConfig.viewAll;
        ctrl.refresh();
    };

    $scope.removeFromFilter = function(item)
    {
        item.selected = false;
        ctrl.onSettingsChanged({ item : item});
    };
};


text:
class Chef
  class Provider::FirewallIptablesUbuntu < Chef::Provider::LWRPBase
    include FirewallCookbook::Helpers
    include FirewallCookbook::Helpers::Iptables

    provides :firewall, os: 'linux', platform_family: ['debian'] do |node|
      node['firewall'] && node['firewall']['ubuntu_iptables']
    end

    def whyrun_supported?
      false
    end

    action :install do
      next if disabled?(new_resource)

      converge_by('install iptables and enable/start services') do
        # Can't pass an array without breaking chef 11 support
        %w(iptables-persistent).each do |p|
          package p do
            action :install
          end
        end

        %w(rules.v4 rules.v6).each do |svc|
          # must create empty file for service to start
          file "create empty /etc/iptables/#{svc}" do
            path "/etc/iptables/#{svc}"
            content '# created by chef to allow service to start'
            not_if { ::File.exist?("/etc/iptables/#{svc}") }
          end
        end

        service 'iptables-persistent' do
          action [:enable, :start]
        end
      end
    end

    action :restart do
      next if disabled?(new_resource)

      # prints all the firewall rules
      log_iptables(new_resource)

      # ensure it's initialized
      new_resource.rules({}) unless new_resource.rules
      ensure_default_rules_exist(node, new_resource)

      %w(iptables ip6tables).each do |iptables_type|
        if iptables_type == 'ip6tables'
          iptables_filename = '/etc/iptables/rules.v6'
        else
          iptables_filename = '/etc/iptables/rules.v4'
        end

        # ensure a file resource exists with the current iptables rules
        begin
          iptables_file = run_context.resource_collection.find(file: iptables_filename)
        rescue
          iptables_file = file iptables_filename do
            action :nothing
          end
        end
        iptables_file.content build_rule_file(new_resource.rules[iptables_type])
        iptables_file.run_action(:create)

        # if the file was changed, restart iptables
        next unless iptables_file.updated_by_last_action?
        service_affected = service 'iptables-persistent' do
          action :nothing
        end

        new_resource.notifies(:restart, service_affected, :delayed)
        new_resource.updated_by_last_action(true)
      end
    end

    action :disable do
      next if disabled?(new_resource)

      iptables_flush!(new_resource)
      iptables_default_allow!(new_resource)
      new_resource.updated_by_last_action(true)

      service 'iptables-persistent' do
        action [:disable, :stop]
      end

      %w(rules.v4 rules.v6).each do |svc|
        # must create empty file for service to start
        file "create empty /etc/iptables/#{svc}" do
          path "/etc/iptables/#{svc}"
          content '# created by chef to allow service to start'
          action :create
        end
      end
    end

    action :flush do
      next if disabled?(new_resource)

      iptables_flush!(new_resource)
      new_resource.updated_by_last_action(true)

      %w(rules.v4 rules.v6).each do |svc|
        # must create empty file for service to start
        file "create empty /etc/iptables/#{svc}" do
          path "/etc/iptables/#{svc}"
          content '# created by chef to allow service to start'
        end
      end
    end
  end
end


text:
package greendroid.widget;
import com.cyrilmottier.android.greendroid.R;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

public class ActionBarHost extends LinearLayout {

    private ActionBar mActionBar;
    private FrameLayout mContentView;

    public ActionBarHost(Context context) {
        this(context, null);
    }

    public ActionBarHost(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOrientation(LinearLayout.VERTICAL);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        mActionBar = (ActionBar) findViewById(R.id.gd_action_bar);
        if (mActionBar == null || !(mActionBar instanceof ActionBar)) {
            throw new IllegalArgumentException("No ActionBar with the id R.id.gd_action_bar found in the layout.");
        }

        mContentView = (FrameLayout) findViewById(R.id.gd_action_bar_content_view);
        if (mContentView == null || !(mContentView instanceof FrameLayout)) {
            throw new IllegalArgumentException("No FrameLayout with the id R.id.gd_action_bar_content_view found in the layout.");
        }
    }

    public ActionBar getActionBar() {
        return mActionBar;
    }

    public FrameLayout getContentView() {
        return mContentView;
    }

}


text:
package gobblin.ingestion.google.webmaster;

import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.apache.commons.lang3.tuple.Pair;

import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.repackaged.com.google.common.base.Preconditions;
import com.google.api.services.webmasters.model.ApiDimensionFilter;
import com.google.api.services.webmasters.model.SearchAnalyticsQueryResponse;
import com.google.common.base.Optional;

import lombok.extern.slf4j.Slf4j;

import gobblin.configuration.State;
import gobblin.util.ExecutorsUtils;
import gobblin.util.limiter.RateBasedLimiter;

import static gobblin.ingestion.google.webmaster.GoogleWebmasterFilter.Dimension;
import static gobblin.ingestion.google.webmaster.GoogleWebmasterFilter.FilterOperator;
import static gobblin.ingestion.google.webmaster.GoogleWebmasterFilter.countryFilterToString;

@Slf4j
public class GoogleWebmasterDataFetcherImpl extends GoogleWebmasterDataFetcher {
  private final double API_REQUESTS_PER_SECOND;
  private final RateBasedLimiter LIMITER;
  private final int GET_PAGE_SIZE_TIME_OUT;
  private final int RETRY;

  private final String _siteProperty;
  private final GoogleWebmasterClient _client;
  private final List<ProducerJob> _jobs;

  GoogleWebmasterDataFetcherImpl(String siteProperty, GoogleWebmasterClient client, State wuState)
      throws IOException {
    _siteProperty = siteProperty;
    Preconditions.checkArgument(_siteProperty.endsWith("/"), "The site property must end in \"/\"");
    _client = client;
    _jobs = getHotStartJobs(wuState);
    API_REQUESTS_PER_SECOND = wuState.getPropAsDouble(GoogleWebMasterSource.KEY_PAGES_TUNING_REQUESTS_PER_SECOND, 5.0);
    GET_PAGE_SIZE_TIME_OUT = wuState.getPropAsInt(GoogleWebMasterSource.KEY_PAGES_TUNING_TIME_OUT, 2);
    LIMITER = new RateBasedLimiter(API_REQUESTS_PER_SECOND, TimeUnit.SECONDS);
    RETRY = wuState.getPropAsInt(GoogleWebMasterSource.KEY_PAGES_TUNING_MAX_RETRIES, 120);
  }

  private static List<ProducerJob> getHotStartJobs(State wuState) {
    String hotStartString = wuState.getProp(GoogleWebMasterSource.KEY_REQUEST_HOT_START, "");
    if (!hotStartString.isEmpty()) {
      return SimpleProducerJob.deserialize(hotStartString);
    }
    return new ArrayList<>();
  }

  /**
   * Due to the limitation of the API, we can get a maximum of 5000 rows at a time. Another limitation is that, results are sorted by click count descending. If two rows have the same click count, they are sorted in an arbitrary way. (Read more at https://developers.google.com/webmaster-tools/v3/searchanalytics). So we try to get all pages by partitions, if a partition has 5000 rows returned. We try partition current partition into more granular levels.
   *
   */
  @Override
  public Collection<ProducerJob> getAllPages(String startDate, String endDate, String country, int rowLimit)
      throws IOException {
    if (!_jobs.isEmpty()) {
      log.info("Service got hot started.");
      return _jobs;
    }

    ApiDimensionFilter countryFilter = GoogleWebmasterFilter.countryEqFilter(country);

    List<GoogleWebmasterFilter.Dimension> requestedDimensions = new ArrayList<>();
    requestedDimensions.add(GoogleWebmasterFilter.Dimension.PAGE);

    Collection<String> allPages = _client
        .getPages(_siteProperty, startDate, endDate, country, rowLimit, requestedDimensions,
            Arrays.asList(countryFilter), 0);
    int actualSize = allPages.size();

    if (rowLimit < GoogleWebmasterClient.API_ROW_LIMIT || actualSize < GoogleWebmasterClient.API_ROW_LIMIT) {
      log.info(String
          .format("A total of %d pages fetched for property %s at country-%s from %s to %s", actualSize, _siteProperty,
              country, startDate, endDate));
    } else {
      int expectedSize = getPagesSize(startDate, endDate, country, requestedDimensions, Arrays.asList(countryFilter));
      log.info(String.format("Total number of pages is %d for market-%s from %s to %s", expectedSize,
          GoogleWebmasterFilter.countryFilterToString(countryFilter), startDate, endDate));
      Queue<Pair<String, FilterOperator>> jobs = new ArrayDeque<>();
      expandJobs(jobs, _siteProperty);

      allPages = getPages(startDate, endDate, requestedDimensions, countryFilter, jobs);
      allPages.add(_siteProperty);
      actualSize = allPages.size();
      if (actualSize != expectedSize) {
        log.warn(String
            .format("Expected page size for country-%s is %d, but only able to get %d", country, expectedSize,
                actualSize));
      }
      log.info(String
          .format("A total of %d pages fetched for property %s at country-%s from %s to %s", actualSize, _siteProperty,
              country, startDate, endDate));
    }

    ArrayDeque<ProducerJob> jobs = new ArrayDeque<>(actualSize);
    for (String page : allPages) {
      jobs.add(new SimpleProducerJob(page, startDate, endDate));
    }
    return jobs;
  }

  private int getPagesSize(final String startDate, final String endDate, final String country,
      final List<Dimension> requestedDimensions, final List<ApiDimensionFilter> apiDimensionFilters)
      throws IOException {
    final ExecutorService es = Executors.newCachedThreadPool(
        ExecutorsUtils.newDaemonThreadFactory(Optional.of(log), Optional.of(this.getClass().getSimpleName())));

    int startRow = 0;
    long groupSize = Math.max(1, Math.round(API_REQUESTS_PER_SECOND));
    List<Future<Integer>> results = new ArrayList<>((int) groupSize);

    while (true) {
      for (int i = 0; i < groupSize; ++i) {
        startRow += GoogleWebmasterClient.API_ROW_LIMIT;
        final int start = startRow;
        final String interruptedMsg = String
            .format("Interrupted while trying to get the size of all pages for %s. Current start row is %d.", country,
                start);

        Future<Integer> submit = es.submit(new Callable<Integer>() {
          @Override
          public Integer call() {
            log.info(String.format("Getting page size from %s...", start));
            while (true) {
              try {
                LIMITER.acquirePermits(1);
              } catch (InterruptedException e) {
                log.error("RateBasedLimiter: " + interruptedMsg, e);
                return -1;
              }

              if (Thread.interrupted()) {
                log.error(interruptedMsg);
                return -1;
              }

              try {
                List<String> pages = _client
                    .getPages(_siteProperty, startDate, endDate, country, GoogleWebmasterClient.API_ROW_LIMIT,
                        requestedDimensions, apiDimensionFilters, start);
                if (pages.size() < GoogleWebmasterClient.API_ROW_LIMIT) {
                  return pages.size() + start;  //Figured out the size
                } else {
                  return -1;
                }
              } catch (IOException e) {
                log.info(String.format("Getting page size from %s failed. Retrying...", start));
              }
            }
          }
        });
        results.add(submit);
      }
      //Check the results group in order. The first non-negative count indicates the size of total pages.
      for (Future<Integer> result : results) {
        try {
          Integer integer = result.get(GET_PAGE_SIZE_TIME_OUT, TimeUnit.MINUTES);
          if (integer >= 0) {
            es.shutdownNow();
            return integer;
          }
        } catch (InterruptedException | ExecutionException e) {
          throw new RuntimeException(e);
        } catch (TimeoutException e) {
          throw new RuntimeException(String
              .format("Exceeding the timeout of %d minutes while getting the total size of all pages.",
                  GET_PAGE_SIZE_TIME_OUT), e);
        }
      }
      results.clear();
    }
  }

  /**
   * Get all pages in an async mode.
   */
  private Collection<String> getPages(String startDate, String endDate, List<Dimension> dimensions,
      ApiDimensionFilter countryFilter, Queue<Pair<String, FilterOperator>> toProcess)
      throws IOException {
    String country = GoogleWebmasterFilter.countryFilterToString(countryFilter);

    ConcurrentLinkedDeque<String> allPages = new ConcurrentLinkedDeque<>();
    int r = 0;
    while (r <= RETRY) {
      ++r;
      log.info(String.format("Get pages at round %d with size %d.", r, toProcess.size()));
      ConcurrentLinkedDeque<Pair<String, FilterOperator>> nextRound = new ConcurrentLinkedDeque<>();
      ExecutorService es = Executors.newFixedThreadPool(10,
          ExecutorsUtils.newDaemonThreadFactory(Optional.of(log), Optional.of(this.getClass().getSimpleName())));

      while (!toProcess.isEmpty()) {
        submitJob(toProcess.poll(), countryFilter, startDate, endDate, dimensions, es, allPages, nextRound);
      }
      //wait for jobs to finish and start next round if necessary.
      try {
        es.shutdown();
        boolean terminated = es.awaitTermination(5, TimeUnit.MINUTES);
        if (!terminated) {
          es.shutdownNow();
          log.warn(String
              .format("Timed out while getting all pages for country-%s at round %d. Next round now has size %d.",
                  country, r, nextRound.size()));
        }
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }

      if (nextRound.isEmpty()) {
        break;
      }
      toProcess = nextRound;
    }
    if (r == RETRY) {
      throw new RuntimeException(String
          .format("Getting all pages reaches the maximum number of retires %d. Date range: %s ~ %s. Country: %s.",
              RETRY, startDate, endDate, country));
    }
    return allPages;
  }

  private void submitJob(final Pair<String, FilterOperator> job, final ApiDimensionFilter countryFilter,
      final String startDate, final String endDate, final List<Dimension> dimensions, ExecutorService es,
      final ConcurrentLinkedDeque<String> allPages,
      final ConcurrentLinkedDeque<Pair<String, FilterOperator>> nextRound) {
    es.submit(new Runnable() {
      @Override
      public void run() {
        try {
          LIMITER.acquirePermits(1);
        } catch (InterruptedException e) {
          throw new RuntimeException("RateBasedLimiter got interrupted.", e);
        }

        String countryString = countryFilterToString(countryFilter);
        List<ApiDimensionFilter> filters = new LinkedList<>();
        filters.add(countryFilter);

        String prefix = job.getLeft();
        FilterOperator operator = job.getRight();
        String jobString = String.format("job(prefix: %s, operator: %s)", prefix, operator);
        filters.add(GoogleWebmasterFilter.pageFilter(operator, prefix));
        List<String> pages;
        try {
          pages = _client
              .getPages(_siteProperty, startDate, endDate, countryString, GoogleWebmasterClient.API_ROW_LIMIT,
                  dimensions, filters, 0);
          log.debug(String
              .format("%d pages fetched for %s market-%s from %s to %s.", pages.size(), jobString, countryString,
                  startDate, endDate));
        } catch (IOException e) {
          log.debug(String.format("%s failed due to %s. Retrying...", jobString, e.getMessage()));
          nextRound.add(job);
          return;
        }

        //If the number of pages is at the LIMIT, it must be a "CONTAINS" job.
        //We need to create sub-tasks, and check current page with "EQUALS"
        if (pages.size() == GoogleWebmasterClient.API_ROW_LIMIT) {
          log.info(String.format("Expanding the prefix '%s'", prefix));
          expandJobs(nextRound, prefix);
          nextRound.add(Pair.of(prefix, FilterOperator.EQUALS));
        } else {
          //Otherwise, we've done with current job.
          allPages.addAll(pages);
        }
      }
    });
  }

  private void expandJobs(Queue<Pair<String, FilterOperator>> jobs, String prefix) {
    for (String expanded : getUrlPartitions(prefix)) {
      jobs.add(Pair.of(expanded, FilterOperator.CONTAINS));
    }
  }

  /**
   * This doesn't cover all cases but more than 99.9% captured.
   *
   * According to the standard (RFC-3986), here are possible characters:
   * unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
   * reserved      = gen-delims / sub-delims
   * gen-delims    = ":" / "/" / "?" / "#" / "[" / "]" / "@"
   * sub-delims    = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
   *
   *
   * Not included:
   * reserved      = gen-delims / sub-delims
   * gen-delims    = "[" / "]"
   * sub-delims    = "(" / ")" / "," / ";"
   */
  private ArrayList<String> getUrlPartitions(String prefix) {
    ArrayList<String> expanded = new ArrayList<>();
    //The page prefix is case insensitive, A-Z is not necessary.
    for (char c = 'a'; c <= 'z'; ++c) {
      expanded.add(prefix + c);
    }
    for (int num = 0; num <= 9; ++num) {
      expanded.add(prefix + num);
    }
    expanded.add(prefix + "-");
    expanded.add(prefix + ".");
    expanded.add(prefix + "_"); //most important
    expanded.add(prefix + "~");

    expanded.add(prefix + "/"); //most important
    expanded.add(prefix + "%"); //most important
    expanded.add(prefix + ":");
    expanded.add(prefix + "?");
    expanded.add(prefix + "#");
    expanded.add(prefix + "@");
    expanded.add(prefix + "!");
    expanded.add(prefix + "$");
    expanded.add(prefix + "&");
    expanded.add(prefix + "+");
    expanded.add(prefix + "*");
    expanded.add(prefix + "'");
    expanded.add(prefix + "=");
    return expanded;
  }

  @Override
  public List<String[]> performSearchAnalyticsQuery(String startDate, String endDate, int rowLimit,
      List<Dimension> requestedDimensions, List<Metric> requestedMetrics, Collection<ApiDimensionFilter> filters)
      throws IOException {
    SearchAnalyticsQueryResponse response = _client
        .createSearchAnalyticsQuery(_siteProperty, startDate, endDate, requestedDimensions,
            GoogleWebmasterFilter.andGroupFilters(filters), rowLimit, 0).execute();
    return convertResponse(requestedMetrics, response);
  }

  @Override
  public void performSearchAnalyticsQueryInBatch(List<ProducerJob> jobs, List<ArrayList<ApiDimensionFilter>> filterList,
      List<JsonBatchCallback<SearchAnalyticsQueryResponse>> callbackList, List<Dimension> requestedDimensions,
      int rowLimit)
      throws IOException {
    BatchRequest batchRequest = _client.createBatch();

    for (int i = 0; i < jobs.size(); ++i) {
      ProducerJob job = jobs.get(i);
      ArrayList<ApiDimensionFilter> filters = filterList.get(i);
      JsonBatchCallback<SearchAnalyticsQueryResponse> callback = callbackList.get(i);
      _client.createSearchAnalyticsQuery(_siteProperty, job.getStartDate(), job.getEndDate(), requestedDimensions,
          GoogleWebmasterFilter.andGroupFilters(filters), rowLimit, 0).queue(batchRequest, callback);
    }

    batchRequest.execute();
  }

  @Override
  public String getSiteProperty() {
    return _siteProperty;
  }
}


text:
@interface Connection : NSObject

+(instancetype) sharedInstance;

-(void) sendingPostReqestFor:(NSString*)path withDictionary:(NSDictionary*)dictionary withCompletionHandler:(void (^) (NSDictionary* jsonObject))block;
-(void) sendingGetReqestForPath:(NSString*)path withParameters:(NSString* )parameters withCompletionHandler:(void (^) (NSDictionary* jsonObject))block;
-(void) sendingGetReqestForLeaderBoardWithParameters:(NSString* )parameters withCompletionHandler:(void (^) (NSArray* jsonObject)) block;
-(NSInteger) checkStausCode;

@end


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

// ============================================================================
// Copyright (c) 2017-2019, by Vitaly Grigoriev, <Vit.link420@gmail.com>.
// This file is part of ProtocolAnalyzer open source project under MIT License.
// ============================================================================

#include <map>
#include <iostream>

#include "FrameworkApi.hpp"

using namespace analyzer::framework;
using net::SocketSSL;

int32_t main (int32_t size, char** data)
{
    log::Logger::Instance().SwitchLoggingEngine();
    log::Logger::Instance().SetLogLevel(log::LEVEL::INFORMATION);

    std::cerr << SocketSSL::context.AllowSessionResumption(SSL_METHOD_TLS10) << std::endl;
    std::cerr << SocketSSL::context.AllowSessionResumption(SSL_METHOD_TLS11) << std::endl;
    std::cerr << SocketSSL::context.AllowSessionResumption(SSL_METHOD_TLS12) << std::endl;
    std::cerr << SocketSSL::context.AllowSessionResumption(SSL_METHOD_TLS13) << std::endl;

    const auto versions = utility::CheckSupportedTLSProtocols("habrahabr.ru");
    for (const auto& ver : versions) {
        LOG_INFO("Find next TLS protocol version - ", ver);
    }

    /*auto sockets = analyzer::framework::system::allocMemoryForArrayOfObjects<SocketSSL>(3, SSL_METHOD_TLS12);
    if (sockets == nullptr) {
        std::cerr << "[error] Alloc memory fail..." << std::endl;
        return EXIT_FAILURE;
    }*/

    auto request = [] (SocketSSL* sock, const std::string& domain) noexcept -> bool
    {
        if (sock->Connect(domain.c_str()) == false) {
            return false;
        }

        const std::string buffer = "GET / HTTP/1.1\r\nHost: " + domain + "\r\nConnection: keep-alive\r\nAccept: */*\r\nDNT: 1\r\n\r\n";
        int32_t result = sock->Send(buffer.c_str(), buffer.size());
        if (result == -1) {
            return false;
        }

        char buff_receive[DEFAULT_BUFFER_SIZE] = { };
        result = sock->Recv(buff_receive, DEFAULT_BUFFER_SIZE, true);
        if (result == -1) {
            return false;
        }
        return true;
    };

    //std::cerr << request(sockets[0].get(), "tproger.ru") << std::endl;
    //std::cerr << request(sockets[1].get(), "habrahabr.ru") << std::endl;

    auto socket1 = system::allocMemoryForObject<SocketSSL>(SSL_METHOD_TLS13);
    request(socket1.get(), "habrahabr.ru");
    socket1->Shutdown();

    auto socket2 = system::allocMemoryForObject<SocketSSL>(socket1->GetSessionSSL(), SSL_METHOD_TLS13);
    socket2->SetOnlySecureCiphers();
    request(socket2.get(), "habrahabr.ru");

    return EXIT_SUCCESS;
}


text:
package eventlistener

import (
	"testing"
	"github.com/docker/docker/api/types"
	"golang.org/x/net/context"
	"fmt"
	"time"
	"github.com/docker/docker/api/types/events"
)

//We simulate docker die event and expect to get the die container id in the tasks channel
func TestEventListener(t *testing.T) {

	const labelToMonitor = "tugbot-test"
	tsk := make(chan string, 10)

	//l := NewEventListener(dockerClientMock{}, labelToMonitor, tsk)
	Register(dockerClientMock{}, labelToMonitor, tsk)
	select {
	case res := <-tsk:
		fmt.Println("we recieved the die container id via the tasks chan: ", res)
	case <-time.After(time.Second * 5):
		t.Error("we did not recieved the die container id on the tasks chan after 5 sec!")
	}
}

type dockerClientMock struct {}

func (d dockerClientMock) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) {
	eventsChan := make(chan events.Message, 10)
	errChan := make(chan error, 10)
	event := events.Message{ Type: "container", Action: "die", }
	eventsChan <- event
	return eventsChan, errChan
}
func (d dockerClientMock) Info(ctx context.Context) (types.Info, error) {
	panic("This function not suppose to be called")
}
func (d dockerClientMock) RegistryLogin(ctx context.Context, auth types.AuthConfig) (types.AuthResponse, error) {
	panic("This function not suppose to be called")
}

func (d dockerClientMock) DiskUsage(ctx context.Context) (types.DiskUsage, error) {
	panic("This function not suppose to be called")
}

func (d dockerClientMock) Ping(ctx context.Context) (bool, error) {
	panic("This function not suppose to be called")
}