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

    function initFactory($q, $rootScope, $cacheFactory, apiBaseFactory) {
        var apibaseurl = "api/workorders/";
        var cache = $cacheFactory("orderCache");
        var dashboardDataKeyName = "dashboardData";

        function _attachLocationCoordinates(postObj) {
            var _loction = $rootScope.currentLocation;
            var _coords = _loction !== undefined ? _loction.coords : {};
            if (_coords && _coords["latitude"] !== undefined) {
                postObj["longitude"] = _coords["longitude"];
                postObj["latitude"] = _coords["latitude"];
            }
            return postObj;
        }

        function clearAllCache() {
            cache.remove(dashboardDataKeyName);
            cache.removeAll();
        }

        function getMobileDashboard(forceGet, initialData) {
            if (angular.isDefined(forceGet) && forceGet) {
                cache.remove(dashboardDataKeyName);
            }
            var orders = cache.get(dashboardDataKeyName);
            if (angular.isDefined(orders) && orders) {
                return $q.when(orders);
            } else {
                return apiBaseFactory
                    .get(apibaseurl + "GetMobileDashboard")
                    .then(function (response) {
                        cache.put(dashboardDataKeyName, response);
                        return response;
                    });
            }
        }

        function getBarcodeDetails(barcode) {
            return apiBaseFactory.get(
                apibaseurl + "GetBarcodeDetails?barcode=" + barcode
            );
        }

        function deleteProduct(barcode, num) {
            return apiBaseFactory.get(
                apibaseurl +
                    "DeleteProduct?barcode=" +
                    barcode +
                    "&productNum=" +
                    num
            );
        }

        function updateProduct(model) {
            return apiBaseFactory.post(
                apibaseurl + "UpdateProduct?fromMobile=true",
                model
            );
        }

        function searchProduct(searchValue, alphabet) {
            return apiBaseFactory.get(
                apibaseurl +
                    "GetProductsLists?searchPattern=" +
                    searchValue +
                    "&alphabet=" +
                    alphabet +
                    "&fromMobile=true"
            );
        }

        function addProduct(model) {
            return apiBaseFactory.post(
                apibaseurl + "AddProductsToOrder?fromMobile=true",
                model
            );
        }

        function getBarcodeInvoiceAndProductDetails(barcode) {
            return apiBaseFactory.get(
                apibaseurl +
                    "GetBarcodeInvoiceAndProductDetails?barcode=" +
                    barcode
            );
        }

        function saveJsonSignForBarcode(obj) {
            obj = _attachLocationCoordinates(obj);
            return apiBaseFactory.post(
                apibaseurl + "SaveJsonSignForBarcode",
                obj
            );
        }

        function sendInvoiceMail(model) {
            return apiBaseFactory.post(apibaseurl + "SendInvoiceMail", model);
        }

        function getImagesList(barcode) {
            return apiBaseFactory.get(
                apibaseurl + "GetImagesList?barcode=" + barcode
            );
        }

        function getUploadedDocuments(barcode) {
            return apiBaseFactory.get(
                apibaseurl + "GetUploadedDocuments?barcode=" + barcode
            );
        }

        function uploadFile(model) {
            return apiBaseFactory.post(apibaseurl + "UploadFile", model);
        }

        function createEntity() {
            var entity = cache.get("workOrderEntity");
            if (angular.isDefined(entity) && entity) {
                return $q.when(entity);
            } else {
                return apiBaseFactory
                    .get(apibaseurl + "CreateEntity")
                    .then(function (response) {
                        cache.put("workOrderEntity", response);
                        return response;
                    });
            }
        }

        function createWorkOrder(model) {
            return apiBaseFactory.post(apibaseurl + "CreateWorkOrder", model);
        }

        function getBarCodeNumber() {
            return apiBaseFactory.get(apibaseurl + "GetBarCodeNumber");
        }

        function updateWorkOrderMobile(model) {
            model = _attachLocationCoordinates(model);
            return apiBaseFactory.post(
                apibaseurl + "UpdateWorkOrderMobile",
                model
            );
        }

        function updateJobStatus(sch) {
            if (sch.clientTime === undefined || sch.clientTime === null) {
                sch.clientTime = kendo.toString(new Date(), "g");
            }
            sch = _attachLocationCoordinates(sch);
            return apiBaseFactory.post(apibaseurl + "UpdateJobStatus", sch);
        }

        function updateSchedule(model) {
            model = _attachLocationCoordinates(model);
            if (model.customSchedules) {
                model.customSchedules = JSON.stringify(model.customSchedules);
            }
            return apiBaseFactory.post(
                apibaseurl + "UpdateSchedule?fromMobile=true",
                model
            );
        }

        //this method will be called from dashboard schedule update modal
        //we can update on Service Provider | schedule start and finish times
        function updateSchedule2(model) {
            return apiBaseFactory.post(
                apibaseurl + "UpdateSchedule?fromMobile=true",
                model
            );
        }

        function addWorkOrderSchedule(schedule) {
            return apiBaseFactory.post(
                apibaseurl + "AddWorkOrderSchedule",
                schedule
            );
        }

        function updateOrderProduct(product) {
            return apiBaseFactory.post(
                apibaseurl + "UpdateOrderProduct",
                product
            );
        }
        var workOrderCalendarKeyName = "workorder:calendar";

        function getDatewiseEvents(forceGet) {
            forceGet = forceGet === null ? false : forceGet;
            if (forceGet === true) {
                cache.remove(workOrderCalendarKeyName);
            }
            var calenderSchedules = cache.get(workOrderCalendarKeyName);
            if (angular.isDefined(calenderSchedules) && calenderSchedules) {
                return $q.when(calenderSchedules);
            } else {
                return apiBaseFactory
                    .get("api/Scheduler/GetMyCalender?fromMobile=true")
                    .then(function (response) {
                        cache.put(workOrderCalendarKeyName, response);
                        return response;
                    });
            }
        }

        function updateCustomScheduleData(o) {
            return apiBaseFactory.post(
                apibaseurl + "UpdateCustomScheduleData",
                o
            );
        }

        function getWorkOrderResolution(id) {
            return apiBaseFactory.get(
                apibaseurl + "GetWorkOrderResolution?id=" + id
            );
        }

        function updateSchduleTotalTime(schedule) {
            schedule = _attachLocationCoordinates(schedule);
            return apiBaseFactory.post(
                apibaseurl + "UpdateSchduleTotalTime",
                schedule
            );
        }

        function deleteImageFromBlob(num, barcode) {
            return apiBaseFactory.deleteReq(
                apibaseurl +
                    "DeleteImage?imageId=" +
                    num +
                    "&barcode=" +
                    barcode
            );
        }

        function uploadFilesN(files) {
            return apiBaseFactory.post(apibaseurl + "UploadFilesN", files);
        }

        function addProductFromBarcodeScanner(skuCode, barcode) {
            return apiBaseFactory.get(
                apibaseurl +
                    "AddProductFromBarcodeScanner?skuCode=" +
                    skuCode +
                    "&barcode=" +
                    barcode
            );
        }

        function uploadFiles(files, model) {
            return apiBaseFactory.upload(
                apibaseurl + "TryUpload",
                files,
                model
            );
        }

        function checkIfBarcodeClosed(barcode) {
            return apiBaseFactory.get(
                apibaseurl + "CheckIfBarcodeClosed?barcode=" + barcode
            );
        }

        function getBarcodePayments(barcode) {
            return apiBaseFactory.get(
                apibaseurl + "GetWorkOrderPayments?barcode=" + barcode
            );
        }

        function addUpdatePayment(o) {
            return apiBaseFactory.post(apibaseurl + "AddUpdatePayment", o);
        }

        function deletePayment(num) {
            return apiBaseFactory.get(apibaseurl + "DeletePayment?num=" + num);
        }

        function updateTaxRate(barcode, taxRate) {
            return apiBaseFactory.get(
                apibaseurl +
                    "UpdateTaxRate?barcode=" +
                    barcode +
                    "&taxRate=" +
                    taxRate
            );
        }

        function submitPayment(model) {
            return apiBaseFactory.post("api/Checkout/SubmitPayment", model);
        }

        function deleteSchedule(num) {
            return apiBaseFactory.deleteReq(
                apibaseurl + "DeleteSchedule?num=" + num + "&fromMobile=true"
            );
        }

        function getScheduleById(num) {
            return apiBaseFactory.get(
                apibaseurl +
                    "GetScheduleById?scheduleId=" +
                    num +
                    "&fromMobile=true"
            );
        }

        function getSchedulesWithSameDateTime(
            barcode,
            currentSchedule,
            checkForStatus
        ) {
            return apiBaseFactory.get(
                apibaseurl +
                    "GetSchedulesWithSameDateTime?barcode=" +
                    encodeURIComponent(barcode) +
                    "&currentSchedule=" +
                    encodeURIComponent(currentSchedule) +
                    "&checkForStatus=" +
                    encodeURIComponent(checkForStatus)
            );
        }

        function updateJobStatusMultiple(sch) {
            if (sch.clientTime === undefined || sch.clientTime === null) {
                sch.clientTime = kendo.toString(new Date(), "g");
            }
            sch = _attachLocationCoordinates(sch);
            return apiBaseFactory.post(
                apibaseurl + "UpdateJobStatusMultipleSchedulesAsync",
                sch
            );
        }

        function updateScheduleBillableState(scheduleNum, isBillable) {
            return apiBaseFactory.get(
                apibaseurl +
                    "UpdateScheduleBillableState?scheduleNum=" +
                    scheduleNum +
                    "&isBillable=" +
                    isBillable
            );
        }

        function deleteDocument(docNum) {
            return apiBaseFactory.deleteReq(
                apibaseurl + "DeleteDocument?num=" + docNum + "&fromMobile=true"
            );
        }

        function getBarcodeInvoiceAndScheduleDetails(barcode) {
            return apiBaseFactory.get(
                apibaseurl +
                    "GetBarcodeInvoiceAndScheduleDetails?barcode=" +
                    barcode +
                    "&loadSchedules=false"
            );
        }

        return {
            deleteDocument: deleteDocument,
            updateScheduleBillableState: updateScheduleBillableState,
            updateJobStatusMultiple: updateJobStatusMultiple,
            getSchedulesWithSameDateTime: getSchedulesWithSameDateTime,
            getScheduleById: getScheduleById,
            submitPayment: submitPayment,
            checkIfBarcodeClosed: checkIfBarcodeClosed,
            uploadFiles: uploadFiles,
            addProductFromBarcodeScanner: addProductFromBarcodeScanner,
            uploadFilesN: uploadFilesN,
            deleteImageFromBlob: deleteImageFromBlob,
            updateSchduleTotalTime: updateSchduleTotalTime,
            getWorkOrderResolution: getWorkOrderResolution,
            updateCustomScheduleData: updateCustomScheduleData,
            getMobileDashboard: getMobileDashboard,
            getBarcodeDetails: getBarcodeDetails,
            deleteProduct: deleteProduct,
            updateProduct: updateProduct,
            searchProduct: searchProduct,
            addProduct: addProduct,
            getBarcodeInvoiceAndProductDetails:
                getBarcodeInvoiceAndProductDetails,
            saveJsonSignForBarcode: saveJsonSignForBarcode,
            sendInvoiceMail: sendInvoiceMail,
            getImagesList: getImagesList,
            getUploadedDocuments: getUploadedDocuments,
            uploadFile: uploadFile,
            createEntity: createEntity,
            createWorkOrder: createWorkOrder,
            getBarCodeNumber: getBarCodeNumber,
            updateWorkOrderMobile: updateWorkOrderMobile,
            updateJobStatus: updateJobStatus,
            updateSchedule: updateSchedule,
            updateSchedule2: updateSchedule2,
            addWorkOrderSchedule: addWorkOrderSchedule,
            updateOrderProduct: updateOrderProduct,
            getDatewiseEvents: getDatewiseEvents,
            clearAllCache: clearAllCache,
            getBarcodePayments: getBarcodePayments,
            addUpdatePayment: addUpdatePayment,
            deletePayment: deletePayment,
            updateTaxRate: updateTaxRate,
            deleteSchedule: deleteSchedule,
            getBarcodeInvoiceAndScheduleDetails:
                getBarcodeInvoiceAndScheduleDetails
        };
    }
    initFactory.$inject = [
        "$q",
        "$rootScope",
        "$cacheFactory",
        "api-base-factory"
    ];
    angular.module("fpm").factory("work-orders-factory", initFactory);
})();


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports Microsoft.CodeAnalysis.Editor.CSharp.GoToDefinition
Imports Microsoft.CodeAnalysis.Editor.GoToDefinition
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities.GoToHelpers
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Navigation
Imports Microsoft.CodeAnalysis.Text
Imports Roslyn.Utilities
Imports Microsoft.VisualStudio.Commanding

Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToDefinition
    <[UseExportProvider]>
    Public Class GoToDefinitionCancellationTests

        <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)>
        Public Sub TestCancellation()
            ' Run without cancelling.
            Dim updates As Integer = Me.Cancel(Integer.MaxValue, False)
            Assert.InRange(updates, 0, Integer.MaxValue)
            Dim i As Integer = 0
            While i < updates
                Dim n As Integer = Me.Cancel(i, True)
                Assert.Equal(n, i + 1)
                i = i + 1
            End While
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)>
        Public Sub TestInLinkedFiles()
            Dim definition =
<Workspace>
    <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
        <Document FilePath="C.cs">
class C
{
    void M()
    {
        M1$$(5);
    }
#if Proj1
    void M1(int x) { }
#endif
#if Proj2
    void M1(int x) { }
#endif
}
        </Document>
    </Project>
    <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
        <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
    </Project>
</Workspace>

            Using workspace = TestWorkspace.Create(
                    definition,
                    exportProvider:=ExportProviderCache.GetOrCreateExportProviderFactory(GoToTestHelpers.Catalog.WithPart(GetType(CSharpGoToDefinitionService))).CreateExportProvider())

                Dim baseDocument = workspace.Documents.First(Function(d) Not d.IsLinkFile)
                Dim linkDocument = workspace.Documents.First(Function(d) d.IsLinkFile)
                Dim view = baseDocument.GetTextView()

                Dim mockDocumentNavigationService =
                    DirectCast(workspace.Services.GetService(Of IDocumentNavigationService)(), MockDocumentNavigationService)

                Dim commandHandler = New GoToDefinitionCommandHandler()
                commandHandler.TryExecuteCommand(view.TextSnapshot, baseDocument.CursorPosition.Value, TestCommandExecutionContext.Create())
                Assert.True(mockDocumentNavigationService._triedNavigationToSpan)
                Assert.Equal(New TextSpan(78, 2), mockDocumentNavigationService._span)

                workspace.SetDocumentContext(linkDocument.Id)

                commandHandler.TryExecuteCommand(view.TextSnapshot, baseDocument.CursorPosition.Value, TestCommandExecutionContext.Create())
                Assert.True(mockDocumentNavigationService._triedNavigationToSpan)
                Assert.Equal(New TextSpan(121, 2), mockDocumentNavigationService._span)
            End Using
        End Sub

        Private Function Cancel(updatesBeforeCancel As Integer, expectedCancel As Boolean) As Integer
            Dim definition =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
            class [|C|] { $$C c; }"
        </Document>
    </Project>
</Workspace>

            Using workspace = TestWorkspace.Create(definition, exportProvider:=GoToTestHelpers.ExportProviderFactory.CreateExportProvider())
                Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
                Dim cursorPosition = cursorDocument.CursorPosition.Value

                Dim mockDocumentNavigationService = DirectCast(workspace.Services.GetService(Of IDocumentNavigationService)(), MockDocumentNavigationService)

                Dim navigatedTo = False
                Dim presenter = New MockStreamingFindUsagesPresenter(Sub() navigatedTo = True)
                Dim presenters = {New Lazy(Of IStreamingFindUsagesPresenter)(Function() presenter)}

                Dim cursorBuffer = cursorDocument.TextBuffer
                Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id)

                Dim goToDefService = New CSharpGoToDefinitionService(presenters)

                Dim waitContext = New TestUIThreadOperationContext(updatesBeforeCancel)
                Dim commandHandler = New GoToDefinitionCommandHandler()

                commandHandler.TryExecuteCommand(document, cursorPosition, goToDefService, New CommandExecutionContext(waitContext))

                Assert.Equal(navigatedTo OrElse mockDocumentNavigationService._triedNavigationToSpan, Not expectedCancel)

                Return waitContext.Updates
            End Using
        End Function
    End Class
End Namespace

redpajama_set_name: RedPajamaGithub


text:
package com.playtika.test.voltdb;

import com.playtika.test.common.spring.DockerPresenceBootstrapConfiguration;
import com.playtika.test.common.utils.ContainerUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.testcontainers.containers.GenericContainer;

import java.util.LinkedHashMap;

import static com.playtika.test.common.utils.ContainerUtils.configureCommonsAndStart;
import static com.playtika.test.voltdb.VoltDBProperties.BEAN_NAME_EMBEDDED_VOLTDB;

@Slf4j
@Configuration
@ConditionalOnExpression("${embedded.containers.enabled:true}")
@AutoConfigureAfter(DockerPresenceBootstrapConfiguration.class)
@ConditionalOnProperty(name = "embedded.voltdb.enabled", matchIfMissing = true)
@EnableConfigurationProperties(VoltDBProperties.class)
public class EmbeddedVoltDBBootstrapConfiguration {

    @Bean
    @ConditionalOnMissingBean
    VoltDBStatusCheck voltDBStartupCheckStrategy() {
        return new VoltDBStatusCheck();
    }

    @Bean(name = BEAN_NAME_EMBEDDED_VOLTDB, destroyMethod = "stop")
    public GenericContainer voltDB(ConfigurableEnvironment environment,
                                   VoltDBProperties properties,
                                   VoltDBStatusCheck voltDbStatusCheck) {

        GenericContainer voltDB = new GenericContainer(ContainerUtils.getDockerImageName(properties))
                .withEnv("HOST_COUNT", "1")
                .withExposedPorts(properties.port)
                .waitingFor(voltDbStatusCheck);
        voltDB = configureCommonsAndStart(voltDB, properties, log);

        registerVoltDBEnvironment(voltDB, environment, properties);
        return voltDB;
    }

    private void registerVoltDBEnvironment(GenericContainer voltDB,
                                           ConfigurableEnvironment environment,
                                           VoltDBProperties properties) {
        Integer mappedPort = voltDB.getMappedPort(properties.port);
        String host = voltDB.getContainerIpAddress();

        LinkedHashMap<String, Object> map = new LinkedHashMap<>();

        map.put("embedded.voltdb.port", mappedPort);
        map.put("embedded.voltdb.host", host);

        String jdbcURL = "jdbc:voltdb://{}:{}";
        log.info("Started VoltDB server. Connection details: {}, " +
                "JDBC connection url: " + jdbcURL, map, host, mappedPort);

        MapPropertySource propertySource = new MapPropertySource("embeddedVoltDBInfo", map);
        environment.getPropertySources().addFirst(propertySource);
    }
}


text:
import React, { PureComponent } from 'react'
import { PropTypes } from 'prop-types'

import classNames from 'classnames/bind'
import { Switch, Route } from 'react-router-dom'

import GatherSource from './gatherSource'
import GatherTarget from './gatherTarget'
import GatherMove from './gatherMove'
import Notice from './notice'
import styles from '../styles/core.scss'

const cx = classNames.bind(styles)

export default class Gather extends PureComponent {
	static propTypes = {
		store: PropTypes.object.isRequired,
		history: PropTypes.object.isRequired,
	}

	componentDidMount() {
		const { actions } = this.props.store
		actions.getStorage()
	}

	render() {
		const { state } = this.props.store

		if (!(state.core && state.core.unraid && state.gather && state.gather.plan)) {
			return null
		}

		if (state.core.unraid.state !== 'STARTED') {
			return (

							The array is not started. Please start the array before performing any operations with
							unBALANCE.

			)
		}

		return (

				<Notice />
				<Switch>
					<Route
						exact
						path="/gather"
						render={props => <GatherSource store={this.props.store} {...props} />}
					/>
					<Route
						exact
						path="/gather/target"
						render={props => <GatherTarget store={this.props.store} {...props} />}
					/>
					<Route
						exact
						path="/gather/move"
						render={props => <GatherMove store={this.props.store} {...props} />}
					/>
				</Switch>

		)
	}
}


text:
import React, { Component } from 'react';

class MarginCards extends Component {
  render() {
    return (

{this.props.avgMargin.margin} ({this.props.avgMargin.percentage}%)

                          Margen promedio

{this.props.bestMargin.margin} ({this.props.bestMargin.percentage}%)

                          Mayor margen: {this.props.bestMargin.sku + '-' + this.props.bestMargin.product}

{this.props.worstMargin.margin} ({this.props.worstMargin.percentage}%)

                          Menor margen: {this.props.worstMargin.sku + '-' + this.props.worstMargin.product}

${this.props.totalSales}

                          Ventas Totales

${this.props.profit}

                          Margen

    );
  }
}

export default MarginCards;


text:
npm run build
rm -rf webfundamentals
mkdir -p webfundamentals/src/content/en/fundamentals/web-components/examples
find docs -type d -name 'howto-*' | while read line; do cp -r $line/*.md webfundamentals/src/content/en/fundamentals/web-components/examples/; done
cp docs/styles/main.devsite.css webfundamentals/src/content/en/fundamentals/web-components/examples/main.css
cp -r docs/images webfundamentals/src/content/en/fundamentals/web-components/examples/


text:
<component name="ArtifactManager">
  <artifact name="Deploy">
    <output-path>E:/DevData/Trunk/plugins</output-path>
    <root id="root">
      <element id="artifact" artifact-name="Plugin-zip" />
    </root>
  </artifact>
</component>


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title>SlickGrid example: Totals via Data Provider: Showing a grand totals row at the bottom of the grid</title>
  <link rel="stylesheet" href="../css/smoothness/jquery-ui.custom.css" type="text/css"/>
  <link rel="stylesheet" href="../slick.grid.css" type="text/css"/>
  <link rel="stylesheet" href="../slick-editors.css" type="text/css"/>
  <link rel="stylesheet" href="examples.css" type="text/css"/>

Demonstrates

Implementing a data provider to create a totals row at the end of the grid.

This is a simplification of what the DataView does.

View Source:

View Source Code


text:
dynForm = {
    jsonSchema : {
	    title : "Point of interest Form",
	    icon : "map-marker",
	    type : "object",
	    onLoads : {
	    	//pour creer un subevnt depuis un event existant
	    	subPoi : function(){
	    		if(contextData.type && contextData.id ){
    				$('#ajaxFormModal #parentId').val(contextData.id);
	    			$("#ajaxFormModal #parentType").val( contextData.type );
	    		}
	    	}
	    },
	    properties : {
	    	info : {
                inputType : "custom",
                html:"
 Une url.
",
            },
            urls : dyFInputs.urls,
            type : dyFInputs.inputSelect("Type du point d'intérêt", null, poiTypes),
	        name :  dyFInputs.name,
            description : dyFInputs.descriptionOptionnel ,
            location : dyFInputs.location,
            tags : dyFInputs.tags(),
            parentId :dyFInputs.inputHidden(),
            parentType : dyFInputs.inputHidden(),
	    }
	}
};


text:
jngs
====

Java Toolkit for Next generation sequencing


text:
System Role List

    <button class="btn btn-primary" ng-click="navigator.systemSettings.systemRole.create.go()" ng-show="permissionVerifier.canEditSystemRole()">Create Role</button>

            RoleName

            {{role.roleName}}
            Delete

    No system roles

        <sriracha-pager paged-list="systemRoleList" go-to-page="goToPage"></sriracha-pager>

        <button class="btn btn-primary" ng-click="navigator.systemSettings.systemRole.create.go()" ng-show="permissionVerifier.canEditSystemRole()">Create Role</button>


text:
using System;
using System.Collections.Generic;

namespace YAF.Lucene.Net.Index.Memory
{

    public partial class MemoryIndex
    {
        private class TermComparer
        {
            /// <summary>
            /// Sorts term entries into ascending order; also works for
            /// <see cref="Array.BinarySearch{T}(T[], T, IComparer{T})"/> and
            /// <see cref="Array.Sort{T}(T[], IComparer{T})"/>.
            /// </summary>
            public static int KeyComparer<TKey, TValue>(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y)
                where TKey : class, IComparable<TKey>
            {
                if (x.Key == y.Key) return 0;
                return typeof(TKey) == typeof(string)
                           ? string.Compare(x.Key as string, y.Key as string, StringComparison.Ordinal)
                           : x.Key.CompareTo(y.Key);
            }
        }

        private sealed class TermComparer<TKey, TValue> : TermComparer, IComparer<KeyValuePair<TKey, TValue>>
            where TKey : class, IComparable<TKey>
        {
            public int Compare(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y)
            {
                return KeyComparer(x, y);
            }
        }
    }
}


text:
'use strict';

var imageSilo =[];
var dir = '/Users/owy1/codefellows/201/Bus-Mall/images/';
var gutter = document.getElementById('container');
var tally = document.getElementById('tally');
var currentThreeIndex = [];
var totClick = 0;
var allotClick = 25;
var ctx = document.getElementById("myChart").getContext("2d");

var names = ['bag','banana','bathroom','boots','breakfast','bubblegum','chair','cthulhu','dog-duck','dragon','pen','pet-sweep','scissors','shark','sweep','tauntaun','unicorn','usb','water-can','wine-glass'];

// create object
function Image(name) {
this.imageName = dir + name + '.jpg';
this.repeat = false;
this.imageTally = 0;
this.imageViews = 0;
this.image = name
imageSilo.push(this);
}

// new instances
for(var i=0; i<names.length; i++) {
new Image(names[i]);
}
// console.log(imageSilo);
// generate random index
function selectRandNum() {
return Math.floor(Math.random()*imageSilo.length);
}

function selectRandFoto() {
  currentThreeIndex = [];
    var trueTot = 0;
    while (currentThreeIndex.length < 3 && trueTot < 20) {
      var temp = selectRandNum();
      if(imageSilo[temp].repeat === false) {
     imageSilo[temp].repeat = true;
        trueTot +=1;
        currentThreeIndex.push(temp);

      } //end if_imageSilo
    }//end while

    for (var z = 0; z < imageSilo.length; z++) {
      imageSilo[z].repeat = false;
      }
}//close acctRandFoto

function renderFoto() {
  selectRandFoto();

  // console.log(currentThreeIndex, 'currentThreeIndex');
  left.src = imageSilo[currentThreeIndex[0]].imageName;
  imageSilo[currentThreeIndex[0]].imageViews += 1;
  center.src = imageSilo[currentThreeIndex[1]].imageName;
  imageSilo[currentThreeIndex[1]].imageViews += 1;
  right.src = imageSilo[currentThreeIndex[2]].imageName;
  imageSilo[currentThreeIndex[2]].imageViews += 1;
}

// function renderList() {
//   for(var i = 0; i<imageSilo.length; i++) {
//     var liEl = document.createElement('li');
//     liEl.textContent = imageSilo[i].image + '   '+imageSilo[i].imageTally+'   '+imageSilo[i].imageViews;
//     tally.appendChild(liEl);
//   }
// }

//function handleEvent
function handleClickInput(event) {
  event.preventDefault();

  var a = event.target.id;
 console.log(a);

  if( a === 'container'){
    alert('CLICK ON A PICTURE!!!! NOT THE BACKGROUND!!!');

  }

  if (a === 'left') {
    imageSilo[currentThreeIndex[0]].imageTally +=1;
  }

  if (a === 'center') {
    imageSilo[currentThreeIndex[1]].imageTally+=1;
  }

  if (a === 'right') {
    imageSilo[currentThreeIndex[2]].imageTally+=1;
  }
totClick += 1;

 if (totClick > allotClick) {
   alert ('Session ends.');
   tally.innerHTML='';
   return renderChart();
 }
 renderFoto();
 tally.innerHTML='';
 renderList();

}//close handleClickInput

function renderList() {
  for(var i = 0; i<imageSilo.length; i++) {
    var liEl = document.createElement('li');
    liEl.textContent = imageSilo[i].image + '   '+imageSilo[i].imageTally+'   '+imageSilo[i].imageViews;
    tally.appendChild(liEl);
  }
}
function renderChart() {
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['bag','banana','bathroom','boots','breakfast','bubblegum','chair','cthulhu','dog-duck','dragon','pen','pet-sweep','scissors','shark','sweep','tauntaun','unicorn','usb','water-can','wine-glass'],
    datasets: [{
      label: 'Total Views',
      // data: [12, 19, 3, 17, 6, 3, 7,12, 19, 3, 17, 6, 3, 7,12, 19, 3, 17, 6, 3],
      data: [
                imageSilo[0].imageTally,
                imageSilo[1].imageTally,
                imageSilo[2].imageTally,
                imageSilo[3].imageTally,
                imageSilo[4].imageTally,
                imageSilo[5].imageTally,
                imageSilo[6].imageTally,
                imageSilo[7].imageTally,
                imageSilo[8].imageTally,
                imageSilo[9].imageTally,
                imageSilo[10].imageTally,
                imageSilo[11].imageTally,
                imageSilo[12].imageTally,
                imageSilo[13].imageTally,
                imageSilo[14].imageTally,
                imageSilo[15].imageTally,
                imageSilo[16].imageTally,
                imageSilo[17].imageTally,
                imageSilo[18].imageTally,
                imageSilo[19].imageTally,
            ],
      backgroundColor: "rgba(153,255,51,0.4)"
    }, {
      label: 'Total Clicks',
      // data: [2, 29, 5, 5, 2, 3, 10,2, 29, 5, 5, 2, 3, 10,2, 29, 5, 5, 2, 3],
      data: [
                imageSilo[0].imageViews,
                imageSilo[1].imageViews,
                imageSilo[2].imageViews,
                imageSilo[3].imageViews,
                imageSilo[4].imageViews,
                imageSilo[5].imageViews,
                imageSilo[6].imageViews,
                imageSilo[7].imageViews,
                imageSilo[8].imageViews,
                imageSilo[9].imageViews,
                imageSilo[10].imageViews,
                imageSilo[11].imageViews,
                imageSilo[12].imageViews,
                imageSilo[13].imageViews,
                imageSilo[14].imageViews,
                imageSilo[15].imageViews,
                imageSilo[16].imageViews,
                imageSilo[17].imageViews,
                imageSilo[18].imageViews,
                imageSilo[19].imageViews,
            ],
      backgroundColor: "rgba(255,153,0,0.4)"
    }]
  }
});
}

renderFoto();
renderList();
gutter.addEventListener('click', handleClickInput);


text:
"""Abstraction to manage how long many truncations.

As of now, this is used to manage out of graph execution.

A Truncation strategy has 2 functions:
unroll_n_steps()
should_do_truncation(learner)

When executed in a training loop,
First, ops created by should_do_truncation is executed. If this returns true,
one unroll of unroll_n_steps is run.
This repeats untill should_do_truncation returns False at which point
the learner is reset to an initial state.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import gin
import sonnet as snt
import tensorflow.compat.v1 as tf

nest = tf.contrib.framework.nest

class AbstractTruncationStrategy(snt.AbstractModule):
  """Interface to control how truncation works.

  In standard backprop through time, this would just return a fixed number for
  unroll_n_steps and true while training_steps < max length and false otherwise.

  We have found that sampling and or scheduling truncation lengths and how long
  to unroll increases performance. Different subclasses represent different
  strategies to do this.
  """

  def __init__(self, name="AbstratractTruncationStrategy"):
    super(AbstractTruncationStrategy, self).__init__(name=name)
    self()

  def _build(self):
    pass

  def unroll_n_steps(self):
    pass

  def should_do_truncation(self, learner):
    pass

@gin.configurable
class FixedLengthIncreasingTruncationStrategy(AbstractTruncationStrategy):
  """Truncation strategy used for experiments.

  Increase linearly, from `min_unroll_steps` to `truncation_length` over
  `increase_over` steps.

  If the loss diverges, stop the current truncation.
  """

  def __init__(
      self,
      truncation_length=10000,
      increase_over=20000,
      min_unroll_steps=10,
      name="FixedLengthIncreasingTruncationStrategy",
  ):
    super(FixedLengthIncreasingTruncationStrategy, self).__init__(name=name)
    self.increase_over = increase_over
    self.min_unroll_steps = min_unroll_steps
    self.truncation_length = truncation_length

  def unroll_n_steps(self, learner):
    # min_unroll --> truncation_length.
    # never go longer than truncation_length.
    training_step = learner.current_state().training_step

    gs = tf.train.get_global_step()

    # compute the linear interpolation
    ratio = tf.minimum(tf.to_float(gs) / float(self.increase_over), 1.)

    total_steps = self.min_unroll_steps * (1. -
                                           ratio) + self.truncation_length * (
                                               ratio)

    # fudge by 20%
    fudge = tf.random_uniform([], 0.8, 1.2)
    float_steps = total_steps * fudge
    candidate = tf.to_int32(float_steps)

    # clip step amount to never go above truncation length
    steps_left = self.truncation_length - training_step

    steps = tf.minimum(steps_left, candidate)
    return steps

  def should_do_truncation(self, learner):
    training_step = learner.current_state().training_step
    return tf.less(training_step, self.truncation_length)

@gin.configurable
class ConstantTruncationStrategy(AbstractTruncationStrategy):
  """Constant length unrolls."""

  def __init__(self,
               steps_per_unroll=10,
               max_steps=1000,
               name="ConstantTruncationStrategy"):
    super(ConstantTruncationStrategy, self).__init__(name=name)
    self.steps_per_unroll = steps_per_unroll
    self.max_steps = max_steps

  def unroll_n_steps(self, learner):
    steps_left = self.max_steps - learner.current_state().training_step
    candidate = tf.minimum(steps_left, self.steps_per_unroll)
    return candidate

  def should_do_truncation(self, learner):
    training_step = learner.current_state().training_step
    return tf.less(training_step, self.max_steps)


text:
<nz-card nzType="inner" nzTitle="Execution Configuration">
  <nz-table
    *ngIf="config"
    class="no-border small"
    [nzTemplateMode]="true"
    [nzSize]="'small'"
    [nzWidthConfig]="['50%','50%']"
    [nzFrontPagination]="false"
    [nzShowPagination]="false">

        Execution mode
        {{ config['execution-config']['execution-mode'] }}

        Max. number of execution retries
        {{ config['execution-config']['restart-strategy'] }}

        Job parallelism
        {{ config['execution-config']['job-parallelism'] === -1 ? 'auto' : config['execution-config']['job-parallelism'] }}

        Object reuse mode
        {{ config['execution-config']['object-reuse-mode'] }}

  </nz-table>
</nz-card>
<nz-card nzType="inner" nzTitle="User Configuration">
  <nz-table
    *ngIf="config"
    class="no-border small"
    [nzData]="listOfUserConfig"
    [nzSize]="'small'"
    [nzFrontPagination]="false"
    [nzWidthConfig]="['50%','50%']"
    [nzShowPagination]="false">

        {{ config.key }}
        {{ config.value }}

  </nz-table>
</nz-card>


text:
int main(int, char *[])
{
    try
    {
        CWindow window;
        window.Show("Demo #13: Smooth Phong Shading", {800, 600});
        CWindowClient client(window);
        window.DoMainLoop();
    }
    catch (const std::exception &ex)
    {
        const char *title = "Fatal Error";
        const char *message = ex.what();
        SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title, message, nullptr);
    }

    return 0;
}


text:
package Init.String;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.*;
import java.util.regex.MatchResult;

/**
 * Created by Defias on 2020/07.
 * Description:  扫描输入
 *
 */

public class TestStringRead {
    public static BufferedReader input = new BufferedReader(
            new StringReader("Sir Robin of Camelot\n22 1.61803"));

    public static String threatData =
            "58.27.82.161@02/10/2005\n" +
            "204.45.234.40@02/11/2005\n" +
            "58.27.82.161@02/11/2005\n" +
            "58.27.82.161@02/12/2005\n" +
            "58.27.82.161@02/12/2005\n" +
            "[Next log section with different data format]";

    public static void main(String[] args) {
        //test1();
        //test2();
        //test3();
        test4();
    }

    public static void test1() {
        try {
            System.out.println("What is your name?");
            String name = input.readLine();
            System.out.println(name);
            System.out.println("How old are you? What is your favorite double?");
            System.out.println("(input: <age> <double>)");
            String numbers = input.readLine();
            System.out.println(numbers);

            String[] numArray = numbers.split(" ");
            int age = Integer.parseInt(numArray[0]);  //解析String为int
            double favorite = Double.parseDouble(numArray[1]);  //解析String为double
            System.out.format("Hi %s.\n", name);
            System.out.format("In 5 years you will be %d.\n", age + 5);
            System.out.format("My favorite double is %f.", favorite / 2);
        } catch(IOException e) {
            System.err.println("I/O exception");
        }
    }

    //更好的方法 - 使用Scanner
    public static void test2() {
        Scanner stdin = new Scanner(input);  //Scanner默认根据空白定界符对输入进行分词
        System.out.println("What is your name?");
        String name = stdin.nextLine();
        System.out.println(name);
        System.out.println(
                "How old are you? What is your favorite double?");
        System.out.println("(input: <age> <double>)");
        int age = stdin.nextInt();  //解析String为int被隐藏在各种next方法中
        double favorite = stdin.nextDouble();
        System.out.println(age);
        System.out.println(favorite);
        System.out.format("Hi %s.\n", name);
        System.out.format("In 5 years you will be %d.\n", age + 5);
        System.out.format("My favorite double is %f.", favorite / 2);
    }

    public static void test3() {
        Scanner scanner = new Scanner("12, 42, 78, 99, 42");
        scanner.useDelimiter("\\s*,\\s*");  //用正则表达式指定定界符进行分词
        while(scanner.hasNextInt())
            System.out.println(scanner.nextInt());
    }

    //使用自定义的正则表达式扫描(扫描复杂数据时非常有用)
    public static void test4() {
        Scanner scanner = new Scanner(threatData);
        String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@" +
                "(\\d{2}/\\d{2}/\\d{4})";
        while(scanner.hasNext(pattern)) {
            scanner.next(pattern);
            MatchResult match = scanner.match();
            String ip = match.group(1);
            String date = match.group(2);
            System.out.format("Threat on %s from %s\n", date,ip);
        }
    }
}


text:
"use strict";
var $ = require("jquery");
var getImageSourceType = function(source) {
    if (!source || "string" !== typeof source) {
        return false
    }
    if (/data:.*base64|\.|\//.test(source)) {
        return "image"
    }
    if (/^[\w-_]+$/.test(source)) {
        return "dxIcon"
    }
    return "fontIcon"
};
var getImageContainer = function(source) {
    var imageType = getImageSourceType(source),
        ICON_CLASS = "dx-icon";
    switch (imageType) {
        case "image":
            return $("<img>", {
                src: source
            }).addClass(ICON_CLASS);
        case "fontIcon":
            return $("<i>", {
                "class": ICON_CLASS + " " + source
            });
        case "dxIcon":
            return $("<i>", {
                "class": ICON_CLASS + " " + ICON_CLASS + "-" + source
            });
        default:
            return null
    }
};
exports.getImageSourceType = getImageSourceType;
exports.getImageContainer = getImageContainer;


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders.Snippets
{
    public class CSharpWhileSnippetCompletionProviderTests : AbstractCSharpConditionalBlockSnippetCompletionProviderTests
    {
        protected override string ItemToCommit => "while";
    }
}


text:
<!DOCTYPE html>

		<meta charset="ISO-8859-1">
		<title>Insert title here</title>

		<link rel="stylesheet" href="https://rawgit.com/codrops/Elastislide/master/css/elastislide.css"/>
		<link rel="stylesheet" href="https://rawgit.com/codrops/Elastislide/master/css/demo.css"/>
		<link rel="stylesheet" href="https://rawgit.com/codrops/Elastislide/master/css/custom.css"/>

Cliquez sur l'icone photo ci-dessous
pour charger votre photo.

			<canvas id="canvas" height="600px"></canvas>

			<form class="up">
				<input type="file" class="f" onchange="onS(event)" multiple style="position:absolute"/>

			</form>


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>com.alexgilleran.icesoap.observer.registry (IceSoap 1.1.1 API)</title>
<meta name="date" content="2016-04-21">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.alexgilleran.icesoap.observer.registry

Class Summary

Class
Description

ListObserverRegistry<TypeToReturn,SOAPFaultType>

Extension of ObserverRegistry to deal with ListRequests.

ObserverRegistry<TypeToReturn,SOAPFaultType>

Helper class that holds a collection of SOAP11Observers and allows
 them all to be notified of events with one call.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2016. All rights reserved.


text:
import logging

import json
from lxml import html

from lems_ui.models import LemsElement, LemsModel

from lems.model import model, component
from lems.parser import LEMS

LOG = logging.getLogger(__name__)

def component_json_to_model_root_id(model_json):
        html_root = html.fromstring(json.loads(model_json)['instance_data'])
        components = {}
        for child in html_root.getchildren():
            if child.tag != 'div':
                continue
            comp_info = {
                    'lems_type': child.get('lems_type'),
                    'html': html.tostring(child),
                    'html_obj': child
            }
            c = comp_info['html_obj']

            try:
                id = c.xpath("div[@class='inst_id']/input")[0].get('value')
            except Exception as e:
                LOG.error(html.tostring(c))
            return id;

def component_json_to_lems_xml(model_json, component_top):
        html_root = html.fromstring(json.loads(model_json)['instance_data'])
        wantedId = component_top;
        # get a dict of component objects from the model_json
        components = {}
        for child in html_root.getchildren():
            if child.tag != 'div':
                continue
            components[child.get('id')] = {
                    'lems_type': child.get('lems_type'),
                    'html': html.tostring(child),
                    'html_obj': child
            }

        for comp_uid, comp_info in components.items():
            try:
                for key, val in parse_html_component(comp_info).items():
                    components[comp_uid][key] = val
            except Exception as e:
                return '<error>' + e.message + '</error>'

        # put components in their hierarchy and add to the model
        # add component types to lems_types_xml
        lems_types_xml = ''
        lems_model_obj = model.Model()
        for comp_uid in add_children(components):
            lems_model_obj.add_component(components[comp_uid]['lems_obj'])

            this_name = components[comp_uid]['lems_obj'].type

            while 1:
                lems_type = LemsElement.objects.get(lems_elem='component_types',
                                                    name=this_name)

                if lems_type.from_file.lower() == 'gui created':
                    lems_types_xml = lems_type.xml + '\n\n' + lems_types_xml
                    this_name = lems_type.extends
                else:
                    break

        # pull each component from the model and convert to xml
        lems_xml = ''
        for comp in lems_model_obj.components.values():
            if comp.id == wantedId:
                lems_xml += comp.toxml() + '\n\n'

            for comp2 in comp.children:
                if comp2.id == wantedId:
                    lems_xml += comp2.toxml() + '\n\n'

                for comp3 in comp2.children:
                    if comp3.id == wantedId:
                        lems_xml += comp3.toxml() + '\n\n'

                    for comp4 in comp3.children:
                        if comp4.id == wantedId:
                            lems_xml += comp4.toxml() + '\n\n'

        LOG.debug(lems_xml)

        full_xml = lems_types_xml + lems_xml

        # jlems doesn't like any '><'
        full_xml = full_xml.replace('><', '>  <')
        full_xml = full_xml.encode('utf-8')

        #grab out all the data to recreate the hierachy later
        components_ret = {}
        for component in (components):
            components_ret[components[component]['lems_obj'].id] = {'id' : component}
            components_ret[components[component]['lems_obj'].id]['id'] = component
            components_ret[components[component]['lems_obj'].id]['type'] = components[component]['lems_obj'].type
            components_ret[components[component]['lems_obj'].id]['parameters'] = components[component]['lems_obj'].parameters
            #print " components[component]['lems_obj'].type"
            #print  components[component]['lems_obj'].type
            components_ret[components[component]['lems_obj'].id]['child_dict'] =  components[component]['child_dict']
            components_ret[components[component]['lems_obj'].id]['children_dict'] =  components[component]['children_dict']
            components_ret[components[component]['lems_obj'].id]['comp_ref_dict'] =  components[component]['comp_ref_dict']

        for component in (components_ret):
            for child in (components_ret[component]['child_dict']):
                for component2 in (components_ret):
                    if components_ret[component]['child_dict'][child] == components_ret[component2]['id']:
                        components_ret[component]['child_dict'][child] = component2
                if not isinstance(components_ret[component]['child_dict'][child], basestring):
                    i = 0
                    for child2 in components_ret[component]['child_dict'][child]:
                        for component2 in (components_ret):
                            if components_ret[component]['child_dict'][child][i] == components_ret[component2]['id']:
                                components_ret[component]['child_dict'][child][i] = component2
                        i=i+1
            for child in (components_ret[component]['children_dict']):
                for component2 in (components_ret):
                    if components_ret[component]['children_dict'][child] == components_ret[component2]['id']:
                        components_ret[component]['children_dict'][child] = component2
                if not isinstance(components_ret[component]['children_dict'][child], basestring):
                    i = 0
                    for child2 in components_ret[component]['children_dict'][child]:
                        for component2 in (components_ret):
                            if components_ret[component]['children_dict'][child][i] == components_ret[component2]['id']:
                                components_ret[component]['children_dict'][child][i] = component2
                        i=i+1
            for child in (components_ret[component]['comp_ref_dict']):
                for component2 in (components_ret):
                    if components_ret[component]['comp_ref_dict'][child] == components_ret[component2]['id']:
                        components_ret[component]['comp_ref_dict'][child] = component2
                if not isinstance(components_ret[component]['comp_ref_dict'][child], basestring):
                    i = 0
                    for child2 in components_ret[component]['comp_ref_dict'][child]:
                        for component2 in (components_ret):
                            if components_ret[component]['comp_ref_dict'][child][i] == components_ret[component2]['id']:
                                components_ret[component]['comp_ref_dict'][child][i] = component2
                        i=i+1

        components_ret2 = {}
        components_ret2 = addComponent(components_ret,{},wantedId)

        return {'xml':full_xml,'components' : components_ret2 }

def addComponent(components_ret,hierarchy,component):
    hierarchy[component] = {}
    hierarchy[component]['comp_ref_dict'] = components_ret[component]['comp_ref_dict']
    hierarchy[component]['children_dict'] = components_ret[component]['children_dict']
    hierarchy[component]['child_dict'] = components_ret[component]['child_dict']
    hierarchy[component]['id'] = component
    hierarchy[component]['type'] = components_ret[component]['type']
    hierarchy[component]['parameters'] = components_ret[component]['parameters']

    for child in (hierarchy[component]['child_dict']):
        if not isinstance(hierarchy[component]['child_dict'][child], basestring):
            i = 0
            for child2 in hierarchy[component]['child_dict'][child]:
                for component2 in (components_ret):
                    #print("hierarchy[component]['child_dict'][child]")
                    #print hierarchy[component]['child_dict'][child]
                    if hierarchy[component]['child_dict'][child][i] == component2:
                        hierarchy[component]['child_dict'][child][i] = {}
                        addComponent(components_ret,hierarchy[component]['child_dict'][child][i],component2)
                i=i+1
        for component2 in (components_ret):
            if hierarchy[component]['child_dict'][child] == component2:
                #hierarchy[component]['child_dict'][child] = components_ret[component2]
                hierarchy[component]['child_dict'][child] = {}
                addComponent(components_ret,hierarchy[component]['child_dict'][child],component2)
    for child in (hierarchy[component]['children_dict']):
        if not isinstance(hierarchy[component]['children_dict'][child], basestring):
            i = 0
            for child2 in hierarchy[component]['children_dict'][child]:
                for component2 in (components_ret):
                    if hierarchy[component]['children_dict'][child][i] == component2:
                        hierarchy[component]['children_dict'][child][i] = {}
                        addComponent(components_ret,hierarchy[component]['children_dict'][child][i],component2)
                i=i+1
        for component2 in (components_ret):
            if hierarchy[component]['children_dict'][child] == component2:
                hierarchy[component]['children_dict'][child] = {}
                addComponent(components_ret,hierarchy[component]['children_dict'][child],component2)
    for child in (hierarchy[component]['comp_ref_dict']):
        if not isinstance(components_ret[component]['comp_ref_dict'][child], basestring):
            i = 0
            for child2 in hierarchy[component]['comp_ref_dict'][child]:
                for component2 in (components_ret):
                    #print("hierarchy[component]['comp_ref_dict'][child]")
                    #print hierarchy[component]['comp_ref_dict'][child]
                    if hierarchy[component]['comp_ref_dict'][child][i] == component2:
                        hierarchy[component]['comp_ref_dict'][child][i] = {}
                        addComponent(components_ret,hierarchy[component]['comp_ref_dict'][child][i],component2)
                i=i+1
        for component2 in (components_ret):
            if hierarchy[component]['comp_ref_dict'][child] == component2:
                hierarchy[component]['comp_ref_dict'][child] = {}
                addComponent(components_ret,hierarchy[component]['comp_ref_dict'][child],component2)
    return hierarchy;

def model_json_to_lems_xml(model_json, include_hier=False, syn_ids=None, include_header=True, include_Components=True):
        html_root = html.fromstring(json.loads(model_json)['instance_data'])

        # get a dict of component objects from the model_json
        components = {}
        for child in html_root.getchildren():
            if child.tag != 'div':
                continue
            components[child.get('id')] = {
                    'lems_type': child.get('lems_type'),
                    'html': html.tostring(child),
                    'html_obj': child
            }

        for comp_uid, comp_info in components.items():
            try:
                for key, val in parse_html_component(comp_info).items():
                    components[comp_uid][key] = val
            except Exception as e:
                return '<error>' + e.message + '</error>'

        # put components in their hierarchy and add to the model
        # add component types to lems_types_xml
        lems_types_xml = ''
        lems_model_obj = model.Model()
        for comp_uid in add_children(components):
            lems_model_obj.add_component(components[comp_uid]['lems_obj'])

            this_name = components[comp_uid]['lems_obj'].type

            while 1:
                lems_type = LemsElement.objects.get(lems_elem='component_types',
                                                    name=this_name)

                if lems_type.from_file.lower() == 'gui created':
                    lems_types_xml = lems_type.xml + '\n\n' + lems_types_xml
                    this_name = lems_type.extends
                else:
                    break

        # pull each component from the model and convert to xml
        lems_xml = ''
        for comp in lems_model_obj.components.values():
            lems_xml += comp.toxml() + '\n\n'

        LOG.debug(lems_xml)

        syn_xml = ''
        if syn_ids:
            # Recursive
            for syn_id in syn_ids:
                syn_xml += model_json_to_lems_xml(LemsModel.objects.get(id=syn_id).json,
                                                  include_hier=True,
                                                  include_header=False)

        # build the final output, header, component types, components and closing tag
        LEMS_HEADER = '<?xml version="1.0" ?>\n<Lems xmlns="http://www.neuroml.org/lems/0.7.3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.neuroml.org/lems/0.7.3 https://raw.github.com/LEMS/LEMS/development/Schemas/LEMS/LEMS_v0.7.3.xsd">'

        if( include_header ):
            if include_Components:
                full_xml = (LEMS_HEADER + '\n\n' + lems_types_xml + lems_xml + syn_xml + '</Lems>\n')
            else:
                full_xml = (LEMS_HEADER + '\n\n' + lems_xml + syn_xml + '</Lems>\n')
                    #lems_xml[lems_xml.find('<Component') :] )
        else:
            if include_Components:
                full_xml = lems_types_xml + lems_xml + syn_xml
            else:
                full_xml = lems_xml + syn_xml

        # jlems doesn't like any '><'
        full_xml = full_xml.replace('><', '>  <')
        full_xml = full_xml.encode('utf-8')
        return full_xml

def add_children(components_info):
    top_level_comps = components_info.keys()

    for comp_info in components_info.values():
        for child_name, child_uid in comp_info['child_dict'].items():
            components_info[child_uid]['lems_obj'].set_parameter('name', child_name)
            comp_info['lems_obj'].add(components_info[child_uid]['lems_obj'])
            if child_uid in top_level_comps: #FK fix for issue with boyle cohen model
                top_level_comps.remove(child_uid)

        for child_name, child_uid_list in comp_info['children_dict'].items():
            for child_uid in child_uid_list:
                components_info[child_uid]['lems_obj'].set_parameter('name', child_name)
                comp_info['lems_obj'].add(
                                    components_info[child_uid]['lems_obj'])
                if child_uid in top_level_comps: #FK fix for issue with boyle cohen model
                    top_level_comps.remove(child_uid)

        for name, uid in comp_info['comp_ref_dict'].items():
            comp_info['lems_obj'].set_parameter(name,
                                    components_info[uid]['lems_obj'].id)

    return top_level_comps

def parse_html_component(comp_info):
    c = comp_info['html_obj']

    try:
        id = c.xpath("div[@class='inst_id']/input")[0].get('value')
    except Exception as e:
        LOG.error(html.tostring(c))
        return {}

    LOG.debug('Parsing component: ' + id + ' : ' + comp_info['lems_type'])
    comp = model.Component(id,
                           comp_info['lems_type'])

    parse_errors = []

    # Add params as key, value
    for param in c.xpath("div[@class='params']/input"):

        # Get unit if present
        unit = ''
        it = param.itersiblings()
        sel = it.next()
        if sel.tag == 'select':
            unit = sel.xpath('option[@selected]')[0].text

        if(not param.get('value')):
            parse_errors.append('Empty Parameter [' + str(param.get('id')) +
                                '], Component [' + id + ']')

        comp.set_parameter(param.get('id'), param.get('value') + unit)

    # Get child dict
    child_dict = {}
    for child_item in c.xpath("div[@class='child_list']/button"):
        it = child_item.itersiblings()
        link = it.next()
        if link.tag == 'a':
            child_dict[child_item.get('id')] = link.get('id')[5:]

    # Get children dict
    children_dict = {}
    for children_item in c.xpath("div[@class='children_list']/button"):
        it = children_item.itersiblings()

        try:
            while(1):
                link = it.next()
                if link.tag == 'a':
                    if not children_dict.has_key(children_item.get('id')):
                        children_dict[children_item.get('id')] = []
                    children_dict[children_item.get('id')].append(
                                                    link.get('id')[5:])
        except:
            # END OF CHILDREN
            pass

    # Get comp ref dict
    comp_ref_dict = {}
    for comp_ref_item in c.xpath("div[@class='comp_refs']/button"):
        it = comp_ref_item.itersiblings()
        link = it.next()
        if link.tag == 'a':
            comp_ref_dict[comp_ref_item.get('id')] = link.get('id')[5:]

    if parse_errors:
        raise Exception(str(parse_errors))

    return {'lems_obj': comp,
            'child_dict': child_dict,
            'children_dict': children_dict,
            'comp_ref_dict': comp_ref_dict}


text:
python_fonenode
===============

This is a python wrapper for fonenode.com

fonenode is a telephony API for Nigeria that allows you build
applications with telephony capabilities (Phone and SMS)

This library will allow you access fonenode with python.

Just import into your python program and use. Kindly read the source for clarity. :D

Thanks

Maintainer: Ehigie (pystar) Aito


text:
import os
import glob
import shutil
import ssl

from setup_app import paths
from setup_app.utils import base
from setup_app.static import AppType, InstallOption, SetupProfiles
from setup_app.config import Config
from setup_app.utils.setup_utils import SetupUtils
from setup_app.installers.base import BaseInstaller

class HttpdInstaller(BaseInstaller, SetupUtils):

    def __init__(self):

        self.service_name = base.httpd_name
        self.pbar_text = "Configuring " + base.httpd_name
        self.app_type = AppType.SERVICE
        self.install_type = InstallOption.OPTONAL
        self.install_var = 'installHttpd'
        self.register_progess()

        self.needdb = False # we don't need backend connection in this class

        self.apache_version = base.determineApacheVersion()

        self.httpdKeyFn = os.path.join(Config.certFolder, 'httpd.key')
        self.httpdCertFn = os.path.join(Config.certFolder, 'httpd.crt')

        self.templates_folder = os.path.join(Config.templateFolder, 'apache')
        self.output_folder = os.path.join(Config.outputFolder, 'apache')

        self.apache2_conf = os.path.join(self.output_folder, 'httpd.conf')
        if Config.profile == SetupProfiles.DISA_STIG:
            self.apache2_24_conf = os.path.join(self.output_folder, 'httpd_2.4.fips.conf')
            self.apache2_ssl_conf = os.path.join(self.output_folder, 'https_gluu.fips.conf')
            self.apache2_ssl_24_conf = os.path.join(self.output_folder, 'https_gluu.fips.conf')
        else:
            self.apache2_24_conf = os.path.join(self.output_folder, 'httpd_2.4.conf')
            self.apache2_ssl_conf = os.path.join(self.output_folder, 'https_gluu.conf')
            self.apache2_ssl_24_conf = os.path.join(self.output_folder, 'https_gluu.conf')

        if base.os_type == 'suse':
            self.https_gluu_fn = '/etc/apache2/vhosts.d/_https_gluu.conf'
        elif base.clone_type == 'rpm':
            self.https_gluu_fn = '/etc/httpd/conf.d/https_gluu.conf'
        else:
            self.https_gluu_fn = '/etc/apache2/sites-available/https_gluu.conf'

    def start_installation(self):
        self.logIt(self.pbar_text, pbar=self.service_name)
        self.stop()

        self.write_httpd_config()

        self.writeFile('/var/www/html/index.html', 'OK')

        if base.os_type == 'suse':
            icons_conf_fn = '/etc/apache2/default-server.conf'
        elif base.clone_type == 'deb':
            icons_conf_fn = '/etc/apache2/mods-available/alias.conf'
        elif base.clone_type == 'rpm':
            icons_conf_fn = '/etc/httpd/conf.d/autoindex.conf'

        with open(icons_conf_fn[:]) as f:
            icons_conf = f.readlines()

        for i, l in enumerate(icons_conf[:]):
            if l.strip().startswith('Alias') and ('/icons/' in l.strip().split()):
                icons_conf[i] =  l.replace('Alias', '#Alias')

        self.writeFile(icons_conf_fn, ''.join(icons_conf))

        error_templates = glob.glob(os.path.join(self.templates_folder,'error_pages/*.html'))

        for tmp_fn in error_templates:
            self.copyFile(tmp_fn, '/var/www/html')

        if Config.profile == SetupProfiles.DISA_STIG:
            self.chown('/var/www/html', 'apache', 'apache', True)

        # we only need these modules
        mods_enabled = ['env', 'log_config', 'proxy', 'proxy_http', 'access_compat', 'alias', 'authn_core', 'authz_core', 'authz_host', 'headers', 'mime', 'mpm_event', 'proxy_ajp', 'security2', 'reqtimeout', 'setenvif', 'socache_shmcb', 'ssl', 'unique_id', 'rewrite']

        cmd_a2enmod = shutil.which('a2enmod')
        cmd_a2dismod = shutil.which('a2dismod')

        if base.clone_type == 'deb':
            for mod_load_fn in glob.glob('/etc/apache2/mods-enabled/*'):
                mod_load_base_name = os.path.basename(mod_load_fn)
                f_name, f_ext = os.path.splitext(mod_load_base_name)
                if f_name not in mods_enabled:
                    self.run([cmd_a2dismod, mod_load_fn])
            for amod in mods_enabled:
                if os.path.exists('/etc/apache2/mods-available/{}.load'.format(amod)):
                    self.run([cmd_a2enmod, amod])

        elif base.os_type == 'suse':
            result = self.run([cmd_a2enmod, '-l'])
            current_modules = result.strip().split()
            for amod in current_modules:
                if amod not in mods_enabled:
                    self.run([cmd_a2dismod, amod])
            for amod in mods_enabled:
                if amod not in current_modules:
                    self.run([cmd_a2enmod, amod])
            cmd_a2enflag = shutil.which('a2enflag')
            self.run([cmd_a2enflag, 'SSL'])

            httpd_conf_fn = '/etc/apache2/httpd.conf'
            httpd_conf_txt = self.readFile(httpd_conf_fn)
            httpd_conf = httpd_conf_txt.splitlines()

            for i, l in enumerate(httpd_conf[:]):
                if l.strip().startswith('DirectoryIndex'):
                    httpd_conf[i] = l.replace('DirectoryIndex', '#DirectoryIndex')

            self.writeFile(httpd_conf_fn, '\n'.join(httpd_conf))

        else:
            modules_config_dir = '/etc/apache2/sysconfig.d' if base.os_type == 'suse' else '/etc/httpd/conf.modules.d'
            for mod_load_fn in glob.glob(os.path.join(modules_config_dir,'*')):
                if not os.path.isfile(mod_load_fn):
                    continue
                with open(mod_load_fn) as f:
                    mod_load_content = f.readlines()

                modified = False

                for i, l in enumerate(mod_load_content[:]):
                    ls = l.strip()

                    if ls and not ls.startswith('#'):
                        lsl = ls.split('/')
                        if not lsl[0].startswith('LoadModule'):
                            continue
                        module =  lsl[-1][4:-3]
                        if module not in mods_enabled:
                            mod_load_content[i] = l.replace('LoadModule', '#LoadModule')
                            modified = True

                if modified:
                    self.writeFile(mod_load_fn, ''.join(mod_load_content))

        if not Config.get('httpdKeyPass'):
            Config.httpdKeyPass = self.getPW()

        # generate httpd self signed certificate
        self.gen_cert('httpd', Config.httpdKeyPass, 'jetty')

        service_name = 'apache2' if base.os_type == 'suse' else base.httpd_name
        self.enable(service_name)
        self.start(service_name)

    def write_httpd_config(self):

        tls_versions = ['+TLSv1.2']
        if hasattr(ssl, 'HAS_TLSv1_3') and ssl.HAS_TLSv1_3:
            tls_versions.append('+TLSv1.3')
        Config.templateRenderingDict['ssl_versions'] = ' '.join(tls_versions)

        self.update_rendering_dict()
        for tmp in (self.apache2_conf, self.apache2_ssl_conf, self.apache2_24_conf, self.apache2_ssl_24_conf):
            self.renderTemplateInOut(tmp, self.templates_folder, self.output_folder)

        if base.os_type == 'suse':
            self.copyFile(self.apache2_ssl_conf, self.https_gluu_fn)

        elif base.clone_type == 'rpm':
            if self.apache_version == "2.4":
                self.copyFile(self.apache2_24_conf, '/etc/httpd/conf/httpd.conf')
            else:
                self.copyFile(self.apache2_conf, '/etc/httpd/conf/httpd.conf')
            self.copyFile(self.apache2_ssl_conf, self.https_gluu_fn)

        elif base.clone_type == 'deb':
            self.copyFile(self.apache2_ssl_conf, self.https_gluu_fn)
            self.run([paths.cmd_ln, '-s', self.https_gluu_fn,
                      '/etc/apache2/sites-enabled/https_gluu.conf'])

    def installed(self):
        return os.path.exists(self.https_gluu_fn)


text:
DIRS = mysql

EXAMPLE_APP = example
EXAMPLE_APP_FILES = $(shell find $(EXAMPLE_APP).app/*.js) $(shell find $(EXAMPLE_APP).app/*.html)

test: test-deps
	go test -run=UnitSpecs

integration-test: test-deps
	go test -run=IntegrationSpecs

test-deps: mysql/schema.sql $(EXAMPLE_APP).pkg $(EXAMPLE_APP).pkg.1 $(EXAMPLE_APP).pkg.2 another.pkg

mysql/%.sql : force_look
	$(MAKE) -C mysql $(subst mysql/,,$@) $(MFLAGS)

$(EXAMPLE_APP).pkg : $(EXAMPLE_APP_FILES)
	zip -r $@ $(EXAMPLE_APP).app

$(EXAMPLE_APP).pkg.1 : $(EXAMPLE_APP_FILES)
	echo "1" > $(EXAMPLE_APP).app/extra_data
	zip -r $@ $(EXAMPLE_APP).app
	rm -f $(EXAMPLE_APP).app/extra_data

$(EXAMPLE_APP).pkg.2 : $(EXAMPLE_APP_FILES)
	echo "2" > $(EXAMPLE_APP).app/extra_data
	zip -r $@ $(EXAMPLE_APP).app
	rm -f $(EXAMPLE_APP).app/extra_data

another.pkg : $(EXAMPLE_APP).pkg
	echo "another" > $(EXAMPLE_APP).app/extra_data
	zip -r $@ $(EXAMPLE_APP).app
	rm -f $(EXAMPLE_APP).app/extra_data

clean :
	@for d in $(DIRS) ; do \
		$(MAKE) -C $$d clean $(MFLAGS) ; \
	done
	go clean ./...
	rm -f $(EXAMPLE_APP).pkg
	rm -f $(EXAMPLE_APP).pkg.1
	rm -f $(EXAMPLE_APP).pkg.2
	rm -f another.pkg

force_look :
	@true

.PHONY : test integration-test test-deps clean


text:
<resources>
    <string name="app_name">To-Do List</string>
    <string name="main_activity_name">All Tasks</string>
    <string name="add_task_activity_name">Add a New Task</string>

    <!-- Strings for MainActivity -->
    <string name="priority_1">1</string>
    <string name="priority_2">2</string>
    <string name="priority_3">3</string>

    <!-- Strings for AddTaskActivity -->
    <!-- This edit task has a unicode character for "..." = "…" -->
    <string name="edit_task_description">Describe your task…</string>
    <string name="priority_string">Priority</string>

    <string name="high_priority">High</string>
    <string name="med_priority">Medium</string>
    <string name="low_priority">Low</string>

    <string name="add_button">Add</string>

</resources>


text:
namespace crashpad {

//! \brief Wraps `task_for_pid()`.
//!
//! This function exists to support `task_for_pid()` access checks in a setuid
//! environment. Normally, `task_for_pid()` can only return an arbitrary task's
//! port when running as root or when taskgated(8) approves. When not running as
//! root, a series of access checks are perfomed to ensure that the running
//! process has permission to obtain the other process' task port.
//!
//! It is possible to make an executable setuid root to give it broader
//! `task_for_pid()` access by bypassing taskgated(8) checks, but this also has
//! the effect of bypassing the access checks, allowing any process' task port
//! to be obtained. In most situations, these access checks are desirable to
//! prevent security and privacy breaches.
//!
//! When running as setuid root, this function wraps `task_for_pid()`,
//! reimplementing those access checks. A process whose effective user ID is 0
//! and whose real user ID is nonzero is understood to be running setuid root.
//! In this case, the requested task's real, effective, and saved set-user IDs
//! must all equal the running process' real user ID, the requested task must
//! not have changed privileges, and the requested task's set of all group IDs
//! (including its real, effective, and saved set-group IDs and supplementary
//! group list) must be a subset of the running process' set of all group IDs.
//! These access checks mimic those that the kernel performs.
//!
//! When not running as setuid root, `task_for_pid()` is called directly,
//! without imposing any additional checks beyond what the kernel does.
//!
//! \param[in] pid The process ID of the task whose task port is desired.
//!
//! \return A send right to the task port if it could be obtained, or
//!     `TASK_NULL` otherwise, with an error message logged. If a send right is
//!     returned, the caller takes ownership of it.
task_t TaskForPID(pid_t pid);

}  // namespace crashpad

#endif  // CRASHPAD_UTIL_MACH_TASK_FOR_PID_H_


text:
package com.dtx12.android_animations_actions.demo;

import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.dtx12.android_animations_actions.actions.Interpolations;

import java.util.Random;

import static com.dtx12.android_animations_actions.actions.Actions.*;

public class MainActivity extends AppCompatActivity {

    @Bind(R.id.firstAnimContainer)
    protected LinearLayout firstAnimContainer;
    @Bind(R.id.secondAnimContainer)
    protected FrameLayout secondAnimContainer;
    private Random random = new Random();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.playSecondAnim)
    protected void playSecondAnim() {
        firstAnimContainer.removeAllViews();
        secondAnimContainer.removeAllViews();
        Point center = new Point(secondAnimContainer.getMeasuredWidth() / 2, secondAnimContainer.getMeasuredHeight() / 2);
        int size = getResources().getDimensionPixelSize(R.dimen.circle_size);
        float delay = 0;
        for (int i = 0; i < 6; i++) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(size, size);
            final ImageView view = new ImageView(this);
            view.setLayoutParams(params);
            view.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.square));
            Point newPos = new Point();
            switch (i) {
                case 0:
                    newPos.set(0, 0);
                    break;

                case 1:
                    newPos.set(0, center.y);
                    break;

                case 2:
                    newPos.set(0, center.y * 2 - size);
                    break;

                case 3:
                    newPos.set(center.x * 2 - size, 0);
                    break;

                case 4:
                    newPos.set(center.x * 2 - size, center.y);
                    break;

                case 5:
                    newPos.set(center.x * 2 - size, center.y * 2 - size);
                    break;
            }
            play(sequence(parallel(fadeOut(), color(-1, Color.BLUE)), moveTo(center.x, center.y),
                    fadeIn(.5f), parallel(moveTo(newPos.x, newPos.y, 1, Interpolations.ExponentialEaseOut)), run(new Runnable() {
                        @Override
                        public void run() {
                            play(sequence(color(Color.BLUE, Color.GREEN, .1f), forever(sequence(color(Color.GREEN, Color.RED, 1), color(Color.GREEN, Color.RED, 1)))), view);
                        }
                    }),
                    parallel(rotateBy(720, 2, Interpolations.BackEaseOut), sequence(scaleTo(.5f, .5f, 1, Interpolations.BackEaseOut),
                            scaleTo(1, 1, 1, Interpolations.ElasticEaseOut))), sequence(delay(delay), parallel(fadeOut(.5f, Interpolations.ExponentialEaseOut),
                            scaleTo(0, 1, .5f, Interpolations.ExponentialEaseOut)))), view);
            delay += 1f;
            secondAnimContainer.addView(view);
        }
    }

    @OnClick(R.id.playFirstAnim)
    protected void playFirstAnimation() {
        firstAnimContainer.removeAllViews();
        secondAnimContainer.removeAllViews();
        for (int i = 0; i < 6; i++) {
            int size = getResources().getDimensionPixelSize(R.dimen.circle_size);
            int margin = getResources().getDimensionPixelSize(R.dimen.circle_margin);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(size, size);
            params.leftMargin = margin;
            params.rightMargin = margin;
            params.gravity = Gravity.CENTER;
            ImageView view = new ImageView(this);
            view.setLayoutParams(params);
            view.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.circle));
            float delay = random.nextFloat();
            float targetY = random.nextInt((int) (firstAnimContainer.getBottom() / 4f));
            play(sequence(fadeOut(), scaleTo(1.5f, 1.5f), fadeIn(2), delay(delay),
                    parallel(moveBy(0, targetY, 2, Interpolations.ElasticEaseOut), sequence(color(-1, Color.GREEN, 1), color(Color.GREEN, Color.RED, 1)),
                            scaleTo(1, 1, 2, Interpolations.ElasticEaseOut))), view);
            firstAnimContainer.addView(view);
        }
    }
}


text:
import { LightFilled20 } from "../../";

export = LightFilled20;


text:
package com.google.cloud.tools.eclipse.sdk.internal;

import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

import com.google.cloud.tools.managedcloudsdk.ProgressListener;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

/**
 * Test {@link ProgressWrapper}.
 */
@RunWith(MockitoJUnitRunner.class)
public class ProgressWrapperTest {

  // SubMonitor can't be mocked directly
  @Mock private IProgressMonitor monitor;
  private ProgressWrapper wrapper;

  @Before
  public void setUp() {
    SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
    wrapper = new ProgressWrapper(subMonitor);
  }

  @Test
  public void testLifecycle() {
    // SubMonitor may issue calls with slightly different numbers and in different orders.
    ArgumentCaptor<Integer> totalWorkCaptor = ArgumentCaptor.forClass(Integer.class);

    wrapper.start("message", 100);
    wrapper.update("update");
    wrapper.update(100);
    wrapper.done();

    verify(monitor).beginTask(eq(""), totalWorkCaptor.capture());
    verify(monitor).setTaskName("message");
    verify(monitor).subTask("update");
    verify(monitor).worked(totalWorkCaptor.getValue());
    verifyNoMoreInteractions(monitor);
  }

  @Test
  public void testNewChild() {
    wrapper.start("testNewChild", 100);
    assertThat(wrapper.newChild(10), instanceOf(ProgressListener.class));
  }
}


text:
package org.jhotdraw.samples.odg.figures;

import org.jhotdraw.draw.handle.AbstractHandle;
import java.awt.*;
import static org.jhotdraw.samples.odg.ODGAttributeKeys.*;

/**
 * A non-interactive {@link org.jhotdraw.draw.handle.Handle} which draws the outline of a
 * {@link ODGPathFigure} to make adjustments easier.
 *
 * @author Werner Randelshofer
 * @version $Id: ODGPathOutlineHandle.java 582 2009-10-24 08:00:49Z rawcoder $
 */
public class ODGPathOutlineHandle extends AbstractHandle {
    private final static Color HANDLE_FILL_COLOR = new Color(0x00a8ff);
    private final static Color HANDLE_STROKE_COLOR = Color.WHITE;

    /** Creates a new instance. */
    public ODGPathOutlineHandle(ODGPathFigure owner) {
        super(owner);
    }

    public ODGPathFigure getOwner() {
        return (ODGPathFigure) super.getOwner();
    }

    protected Rectangle basicGetBounds() {
        return view.drawingToView(getOwner().getDrawingArea());
    }
    @Override public boolean contains(Point p) {
        return false;
    }

    public void trackStart(Point anchor, int modifiersEx) {
    }

    public void trackStep(Point anchor, Point lead, int modifiersEx) {
    }

    public void trackEnd(Point anchor, Point lead, int modifiersEx) {
    }

    @Override public void draw(Graphics2D g) {
        Shape bounds = getOwner().getPath();
        if (getOwner().get(TRANSFORM) != null) {
            bounds = getOwner().get(TRANSFORM).createTransformedShape(bounds);
        }
        bounds = view.getDrawingToViewTransform().createTransformedShape(bounds);
        g.setColor(HANDLE_FILL_COLOR);
        g.draw(bounds);
    }
}


text:
const path = require("path")
const { spawnSync } = require("child_process")

spawnSync(path.join(__dirname, '../node_modules/.bin/prebuild' + (process.platform === "win32" ? '.cmd' : '')), ['--upload-all', process.env.GITHUB_AUTH_TOKEN], {stdio: 'inherit'})


text:
import urllib, urllib2
import json

def fetch_wikidata_props():
	WIKIDATA_API_URL = 'https://www.wikidata.org/w/api.php'
	param = {}
	param['action'] = 'query'
	param['format'] = 'json'
	param['generator'] = 'allpages'
	param['gapnamespace'] = 120
	param['gaplimit'] = 'max'
	param['prop'] = 'pageterms'
	param['wbptterms'] = 'label|alias'
	while True:
		params = urllib.urlencode(param)
		url = WIKIDATA_API_URL + '?' + params
		urlobj = urllib2.urlopen(url)
		json_data = json.load(urlobj)
		for pageid, resp in json_data['query']['pages'].items():
			labels = list(resp['terms']['label'])
			if resp['terms'].get('alias'):
				labels.extend(resp['terms']['alias'])
			filename = resp['title'].replace('Property:', '')
			filestream = open(filename, 'w')
			content = '\n'.join(labels)
			filestream.write(content.encode('utf-8'))
			filestream.close()
		if json_data.get('continue'):
			param.update(json_data['continue'])
		else:
			break

if __name__ == '__main__':
	fetch_wikidata_props()


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net.Mail;
using Microsoft.AspNet.WebHooks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions;
using Microsoft.Azure.WebJobs.Extensions.Files;
using Microsoft.Azure.WebJobs.Extensions.WebHooks;
using Microsoft.Azure.WebJobs.Host;

namespace ExtensionsSample
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            JobHostConfiguration config = new JobHostConfiguration();

            config.Tracing.ConsoleLevel = TraceLevel.Verbose;

            // Set to a short polling interval to facilitate local
            // debugging. You wouldn't want to run prod this way.
            config.Queues.MaxPollingInterval = TimeSpan.FromSeconds(2);

            FilesConfiguration filesConfig = new FilesConfiguration();
            if (string.IsNullOrEmpty(filesConfig.RootPath))
            {
                // when running locally, set this to a valid directory
                filesConfig.RootPath = @"c:\temp\files";
            }
            EnsureSampleDirectoriesExist(filesConfig.RootPath);
            config.UseFiles(filesConfig);

            config.UseTimers();
            config.UseSample();
            config.UseCore();
            var sendGridConfiguration = new SendGridConfiguration()
            {
                ToAddress = "admin@webjobssamples.com",
                FromAddress = new MailAddress("samples@webjobssamples.com", "WebJobs Extensions Samples")
            };
            config.UseSendGrid(sendGridConfiguration);

            ConfigureTraceMonitor(config, sendGridConfiguration);

            WebHooksConfiguration webHooksConfig = new WebHooksConfiguration();
            webHooksConfig.UseReceiver<GitHubWebHookReceiver>();
            config.UseWebHooks(webHooksConfig);

            JobHost host = new JobHost(config);

            host.Call(typeof(MiscellaneousSamples).GetMethod("ExecutionContext"));
            host.Call(typeof(FileSamples).GetMethod("ReadWrite"));
            host.Call(typeof(SampleSamples).GetMethod("Sample_BindToStream"));
            host.Call(typeof(SampleSamples).GetMethod("Sample_BindToString"));
            host.Call(typeof(TableSamples).GetMethod("CustomBinding"));

            host.RunAndBlock();
        }

        /// <summary>
        /// Set up monitoring + notifications for WebJob errors. This shows how to set things up
        /// manually on startup. You can also use <see cref="ErrorTriggerAttribute"/> to designate
        /// error handler functions.
        /// </summary>
        private static void ConfigureTraceMonitor(JobHostConfiguration config, SendGridConfiguration sendGridConfiguration)
        {
            var notifier = new ErrorNotifier(sendGridConfiguration);

            var traceMonitor = new TraceMonitor()
                .Filter(new SlidingWindowTraceFilter(TimeSpan.FromMinutes(5), 3))
                .Filter(p =>
                {
                    FunctionInvocationException functionException = p.Exception as FunctionInvocationException;
                    return p.Level == TraceLevel.Error && functionException != null &&
                           functionException.MethodName == "ExtensionsSample.FileSamples.ImportFile";
                }, "ImportFile Job Failed")
                .Subscribe(notifier.WebNotify, notifier.EmailNotify)
                .Throttle(TimeSpan.FromMinutes(30));

            config.Tracing.Tracers.Add(traceMonitor);
        }

        private static void EnsureSampleDirectoriesExist(string rootFilesPath)
        {
            // Ensure all the directories referenced by the file sample bindings
            // exist
            Directory.CreateDirectory(rootFilesPath);
            Directory.CreateDirectory(Path.Combine(rootFilesPath, "import"));
            Directory.CreateDirectory(Path.Combine(rootFilesPath, "cache"));
            Directory.CreateDirectory(Path.Combine(rootFilesPath, "convert"));
            Directory.CreateDirectory(Path.Combine(rootFilesPath, "converted"));

            File.WriteAllText(Path.Combine(rootFilesPath, "input.txt"), "WebJobs SDK Extensions!");
        }
    }
}


text:
/**
 * Represents an Eval job along with the information needed for that job.
 */
export interface EvalJob {
  id: number;
  name: string;
  findings: string;
  goldens: string;
  stats: string;
  debug: string;
  status: number;
  logTrace: string;
  timestamp: Date;
}

/**
 * Represents an Eval stats entry.
 */
export interface EvalStats {
  infoType: string;
  recall?: number;
  precision?: number;
  fScore?: number;
  truePositives?: number;
  falsePositives?: number;
  falseNegatives?: number;
  timestamp: Date;
}