text:
#ifndef IRRADIANCEDETECTOR_H_
#define IRRADIANCEDETECTOR_H_

#include <fstream>
#include <string>
#include "SurfaceProperty.h"
#include "Ray.h"
#include <omp.h>
#include <tbb/concurrent_vector.h>
#include "Surface.h"

using namespace std;
using namespace tbb;

class IrradianceDetector : public SurfaceProperty {

 public:

//		IrradianceDetector();
  IrradianceDetector(Surface* detectorObject, int XPixels, int YPixels,
                     int N_RAYS);
  virtual ~IrradianceDetector();
  AbstractGeometry* receiveRay(Ray& ray, Surface* surface,
                               AbstractGeometry* from, AbstractGeometry* to);

  void RecordRayData(Ray& ray);
 public:

  void SaveRays(string& RayFileName);

  void Irradiance(string& DetectorDataFileName, int NUM_THREADS);

  void ConstructIrradianceData(int NUM_THREADS);

  void IrradianceCrossSectionVertical(int ColNumber,
                                      string& CrossSectionDataFileName);
  void IrradianceCrossSectionHorizontal(int RowNumber,
                                        string& CrossSectionDataFileName);

  void Spectrum(string& SpectrumDataFileName);

 public:
  // X and Y pixel number
  int XPix;
  int YPix;

  // step-variables
  double XSTEP;
  double YSTEP;

  double RS_width;
  double RS_height;

  // Container for the detected rays
  concurrent_vector<Ray> DetectedRays;

  // Total detected flux
  double TotalFlux;

  mat FluxData;

  // Number of Rays propagated
  int TotalNumberOfRays;

  vec pos;
  vec uvec;
  vec vvec;

 private:

  static int count;

};

#endif /* IRRADIANCEDETECTOR_H_ */


text:
/*global define,dojo,alert */
/*jslint browser:true,sloppy:true,nomen:true */
/*
 | Copyright 2014 Esri
 |
 | Licensed under the Apache License, Version 2.0 (the "License");
 | you may not use this file except in compliance with the License.
 | You may obtain a copy of the License at
 |
 |    http://www.apache.org/licenses/LICENSE-2.0
 |
 | Unless required by applicable law or agreed to in writing, software
 | distributed under the License is distributed on an "AS IS" BASIS,
 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 | See the License for the specific language governing permissions and
 | limitations under the License.
 */
//============================================================================================================================//
define([
    "dojo/_base/declare",
    "dojo/text!./templates/sortby.html",
    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
    "dijit/_WidgetsInTemplateMixin",
    "dojo/i18n!nls/localizedStrings",
    "dojo/query",
    "dojo/_base/lang",
    "dojo/topic",
    "dojo/Deferred",
    "dojo/dom-class",
    "dojo/dom-attr",
    "dojo/on"
], function (declare, template, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, nls, query, lang, topic, Deferred, domClass, domAttr, on) {

    return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
        templateString: template,
        nls: nls,

        postCreate: function () {
            if (dojo.configData.ApplicationSettings.sortField === "modified") {
                domAttr.set(this.sortByLabel, "innerHTML", nls.sortByViewText);
            } else {
                domAttr.set(this.sortByLabel, "innerHTML", nls.sortByDateText);
            }
            this.own(on(this.sortByLabel, "click", lang.hitch(this, function () {
                topic.publish("showProgressIndicator");
                if (dojo.sortBy === dojo.configData.ApplicationSettings.sortField) {
                    this._sortByDate(this.sortByLabel);
                } else {
                    this._sortByViews(this.sortByLabel);
                }
            })));
            this.own(on(this.sortByViewMbl, "click", lang.hitch(this, function () {
                this._sortByViews(this.sortByLabel);
            })));
            this.own(on(this.sortByDateMbl, "click", lang.hitch(this, function () {
                this._sortByDate(this.sortByLabel);
            })));
        },

        _sortByDate: function (sortByLabel) {
            dojo.sortBy = "modified";
            this._sortPodOrder(dojo.sortBy, sortByLabel, nls.sortByViewText);
            domClass.remove(query(".esriCTListSelected")[0], "esriCTListSelected");
            domClass.add(query(".sortByDateMbl")[0], "esriCTListSelected");
        },

        _sortByViews: function (sortByLabel) {
            dojo.sortBy = dojo.configData.ApplicationSettings.sortField;
            this._sortPodOrder(dojo.sortBy, sortByLabel, nls.sortByDateText);
            domClass.remove(query(".esriCTListSelected")[0], "esriCTListSelected");
            domClass.add(query(".sortByViewMbl")[0], "esriCTListSelected");
        },

        _sortPodOrder: function (sortField, sortByLabel, text) {
            var defObj = new Deferred();
            topic.publish("queryGroupItem", dojo.queryString, sortField, dojo.configData.ApplicationSettings.sortOrder.toLowerCase(), defObj);
            defObj.then(function (data) {
                domAttr.set(sortByLabel, "innerHTML", text);
                dojo.results = data.results;
                dojo.nextQuery = data.nextQueryParams;
                topic.publish("createPods", data.results, true);
            }, function (err) {
                alert(err.message);
                defObj.resolve();
                topic.publish("hideProgressIndicator");
            });
        }
    });
});

redpajama_set_name: RedPajamaGithub


text:
package io.joynr.integration;

import static com.google.inject.util.Modules.override;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.stubbing.Answer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Named;
import com.google.inject.name.Names;

import io.joynr.arbitration.ArbitrationStrategyFunction;
import io.joynr.arbitration.DiscoveryQos;
import io.joynr.arbitration.DiscoveryScope;
import io.joynr.capabilities.ParticipantIdKeyUtil;
import io.joynr.common.JoynrPropertiesModule;
import io.joynr.dispatching.MutableMessageFactory;
import io.joynr.exceptions.JoynrException;
import io.joynr.exceptions.JoynrRuntimeException;
import io.joynr.integration.util.TestSetup;
import io.joynr.messaging.ConfigurableMessagingSettings;
import io.joynr.messaging.FailureAction;
import io.joynr.messaging.JoynrMessageProcessor;
import io.joynr.messaging.MessagingPropertyKeys;
import io.joynr.messaging.MessagingQos;
import io.joynr.messaging.MessagingSkeletonFactory;
import io.joynr.messaging.SuccessAction;
import io.joynr.messaging.inprocess.InProcessMessagingStubFactory;
import io.joynr.messaging.mqtt.IMqttMessagingSkeleton;
import io.joynr.messaging.mqtt.JoynrMqttClient;
import io.joynr.messaging.mqtt.MqttClientFactory;
import io.joynr.messaging.mqtt.MqttMessagingSkeletonFactory;
import io.joynr.messaging.mqtt.MqttMessagingSkeletonProvider;
import io.joynr.messaging.mqtt.MqttMessagingStub;
import io.joynr.messaging.mqtt.MqttMessagingStubFactory;
import io.joynr.messaging.mqtt.MqttModule;
import io.joynr.messaging.mqtt.hivemq.client.HivemqMqttClientFactory;
import io.joynr.messaging.mqtt.hivemq.client.HivemqMqttClientModule;
import io.joynr.messaging.routing.RoutingEntry;
import io.joynr.messaging.routing.RoutingTable;
import io.joynr.messaging.websocket.WebSocketClientMessagingStubFactory;
import io.joynr.messaging.websocket.WebSocketMessagingStub;
import io.joynr.messaging.websocket.WebSocketMessagingStubFactory;
import io.joynr.messaging.websocket.WebsocketModule;
import io.joynr.provider.JoynrProvider;
import io.joynr.provider.ProviderAnnotations;
import io.joynr.proxy.Future;
import io.joynr.proxy.ProxyBuilder;
import io.joynr.proxy.ProxyBuilder.ProxyCreatedCallback;
import io.joynr.proxy.ProxyBuilderFactory;
import io.joynr.proxy.ProxyBuilderFactoryImpl;
import io.joynr.proxy.ProxyInvocationHandlerFactory;
import io.joynr.proxy.StatelessAsyncCallbackDirectory;
import io.joynr.runtime.CCWebSocketRuntimeModule;
import io.joynr.runtime.JoynrRuntime;
import io.joynr.runtime.ShutdownListener;
import io.joynr.runtime.ShutdownNotifier;
import io.joynr.runtime.SystemServicesSettings;
import io.joynr.smrf.EncodingException;
import io.joynr.smrf.UnsuppportedVersionException;
import joynr.BroadcastFilterParameters;
import joynr.BroadcastSubscriptionRequest;
import joynr.ImmutableMessage;
import joynr.Message;
import joynr.MutableMessage;
import joynr.OnChangeSubscriptionQos;
import joynr.Reply;
import joynr.Request;
import joynr.system.DiscoveryAsync;
import joynr.system.RoutingTypes.MqttAddress;
import joynr.system.RoutingTypes.RoutingTypesUtil;
import joynr.test.JoynrTestLoggingRule;
import joynr.tests.DefaulttestProvider;
import joynr.types.DiscoveryEntryWithMetaInfo;
import joynr.types.GlobalDiscoveryEntry;
import joynr.types.ProviderQos;
import joynr.types.ProviderScope;

/**
 * Integration tests for RoutingTable reference count handling.
 */
public class AbstractRoutingTableCleanupTest {

    private static final Logger logger = LoggerFactory.getLogger(AbstractRoutingTableCleanupTest.class);
    @Rule
    public JoynrTestLoggingRule joynrTestRule = new JoynrTestLoggingRule(logger);

    private final String TESTGBID1 = "testgbid1";
    private final String TESTGBID2 = "testgbid2";
    protected final String[] gbids = new String[]{ TESTGBID1, TESTGBID2 };
    protected final MqttAddress replyToAddress = new MqttAddress(gbids[1], "");

    protected final String TESTCUSTOMDOMAIN1 = "testCustomDomain1";
    protected final String TESTCUSTOMDOMAIN2 = "testCustomDomain2";
    protected final String TESTCUSTOMDOMAIN3 = "testCustomDomain3";

    protected final String FIXEDPARTICIPANTID1 = "provider-1";
    protected final String FIXEDPARTICIPANTID2 = "provider-2";
    protected final String FIXEDPARTICIPANTID3 = "provider-3";

    private final long ROUTINGTABLE_CLEANUP_INTERVAL_MS = 100l;
    private final long ROUTING_MAX_RETRY_COUNT = 2;

    private Properties properties;
    protected Injector injector;
    // JoynrRuntime to simulate user operations
    protected JoynrRuntime joynrRuntime;
    // MessagingSkeletonFactory to simulate incoming messages through messaging skeletons
    protected MqttMessagingSkeletonFactory mqttSkeletonFactory;
    protected MessagingSkeletonFactory messagingSkeletonFactory;
    protected MutableMessageFactory messageFactory;

    // RoutingTable for verification, use the apply() method to count entries and get info about stored addresses
    protected RoutingTable routingTable;

    protected DiscoveryQos discoveryQosGlobal;
    protected DiscoveryQos discoveryQosLocal;
    protected ProviderQos providerQosGlobal;
    protected ProviderQos providerQosLocal;
    protected MessagingQos defaultMessagingQos;

    protected ConcurrentMap<String, RoutingEntry> routingTableHashMap;

    @Mock
    private MqttMessagingStubFactory mqttMessagingStubFactoryMock;
    @Mock
    private WebSocketClientMessagingStubFactory websocketClientMessagingStubFactoryMock;
    @Mock
    private WebSocketMessagingStubFactory webSocketMessagingStubFactoryMock;
    @Spy
    protected InProcessMessagingStubFactory inProcessMessagingStubFactorySpy;

    @Mock
    protected MqttMessagingStub mqttMessagingStubMock;
    @Mock
    protected WebSocketMessagingStub webSocketClientMessagingStubMock;
    @Mock
    private WebSocketMessagingStub webSocketMessagingStubMock;

    @Mock
    protected JoynrMessageProcessor messageProcessorMock;

    @Mock
    private HivemqMqttClientFactory hiveMqMqttClientFactory;
    @Mock
    private JoynrMqttClient joynrMqttClient1;
    @Mock
    private JoynrMqttClient joynrMqttClient2;

    @Spy
    ShutdownNotifier shutdownNotifier = new ShutdownNotifier();

    protected static String sProxyParticipantId;

    protected static class TestProxyBuilderFactory extends ProxyBuilderFactoryImpl {
        private final Set<String> internalProxyParticipantIds;

        @Inject
        public TestProxyBuilderFactory(DiscoveryAsync localDiscoveryAggregator,
                                       ProxyInvocationHandlerFactory proxyInvocationHandlerFactory,
                                       ShutdownNotifier shutdownNotifier,
                                       StatelessAsyncCallbackDirectory statelessAsyncCallbackDirectory,
                                       @Named(ConfigurableMessagingSettings.PROPERTY_MESSAGING_MAXIMUM_TTL_MS) long maxMessagingTtl,
                                       @Named(ConfigurableMessagingSettings.PROPERTY_DISCOVERY_DEFAULT_TIMEOUT_MS) long defaultDiscoveryTimeoutMs,
                                       @Named(ConfigurableMessagingSettings.PROPERTY_DISCOVERY_DEFAULT_RETRY_INTERVAL_MS) long defaultDiscoveryRetryIntervalMs,
                                       @Named(ConfigurableMessagingSettings.PROPERTY_DISCOVERY_MINIMUM_RETRY_INTERVAL_MS) long minimumArbitrationRetryDelay,
                                       @Named(SystemServicesSettings.PROPERTY_CC_DISCOVERY_PROVIDER_PARTICIPANT_ID) String discoveryProviderParticipantId,
                                       @Named(SystemServicesSettings.PROPERTY_CC_ROUTING_PROVIDER_PARTICIPANT_ID) String routingProviderParticipantId,
                                       @Named(MessagingPropertyKeys.CAPABILITIES_DIRECTORY_DISCOVERY_ENTRY) GlobalDiscoveryEntry capabilitiesDirectoryEntry) {
            super(localDiscoveryAggregator,
                  proxyInvocationHandlerFactory,
                  shutdownNotifier,
                  statelessAsyncCallbackDirectory,
                  maxMessagingTtl,
                  defaultDiscoveryTimeoutMs,
                  defaultDiscoveryRetryIntervalMs,
                  minimumArbitrationRetryDelay);
            internalProxyParticipantIds = new HashSet<String>(Arrays.asList(discoveryProviderParticipantId,
                                                                            routingProviderParticipantId,
                                                                            capabilitiesDirectoryEntry.getParticipantId()));
        }

        @Override
        public <T> ProxyBuilder<T> get(Set<String> domains, Class<T> interfaceClass) {
            ProxyBuilder<T> proxyBuilder = super.get(domains, interfaceClass);
            String proxyParticipantId = proxyBuilder.getParticipantId();
            if (!internalProxyParticipantIds.contains(proxyParticipantId)) {
                AbstractRoutingTableCleanupTest.sProxyParticipantId = proxyParticipantId;
            }
            System.out.println("##### TestProxyBuilderFactory.get() called!");
            return proxyBuilder;
        }
    }

    @Before
    public void setUp() throws InterruptedException, IOException {
        doReturn(joynrMqttClient1).when(hiveMqMqttClientFactory).createReceiver(TESTGBID1);
        doReturn(joynrMqttClient1).when(hiveMqMqttClientFactory).createSender(TESTGBID1);
        doReturn(joynrMqttClient2).when(hiveMqMqttClientFactory).createReceiver(TESTGBID2);
        doReturn(joynrMqttClient2).when(hiveMqMqttClientFactory).createSender(TESTGBID2);

        lenient().doReturn(mqttMessagingStubMock).when(mqttMessagingStubFactoryMock).create(any());
        lenient().doReturn(webSocketClientMessagingStubMock)
                 .when(websocketClientMessagingStubFactoryMock)
                 .create(any());
        lenient().doReturn(webSocketMessagingStubMock).when(webSocketMessagingStubFactoryMock).create(any());

        doAnswer(invocation -> {
            return (ImmutableMessage) invocation.getArguments()[0];
        }).when(messageProcessorMock).processIncoming(any(ImmutableMessage.class));
        doAnswer(invocation -> {
            return (MutableMessage) invocation.getArguments()[0];
        }).when(messageProcessorMock).processOutgoing(any(MutableMessage.class));

        discoveryQosGlobal = new DiscoveryQos();
        discoveryQosGlobal.setDiscoveryTimeoutMs(30000);
        discoveryQosGlobal.setRetryIntervalMs(discoveryQosGlobal.getDiscoveryTimeoutMs() + 1); // no retry
        discoveryQosGlobal.setDiscoveryScope(DiscoveryScope.GLOBAL_ONLY);
        discoveryQosGlobal.setCacheMaxAgeMs(10000);

        discoveryQosLocal = new DiscoveryQos();
        discoveryQosLocal.setDiscoveryTimeoutMs(30000);
        discoveryQosLocal.setRetryIntervalMs(discoveryQosLocal.getDiscoveryTimeoutMs() + 1); // no retry
        discoveryQosLocal.setDiscoveryScope(DiscoveryScope.LOCAL_ONLY);

        providerQosGlobal = new ProviderQos();
        providerQosGlobal.setScope(ProviderScope.GLOBAL);

        providerQosLocal = new ProviderQos();
        providerQosLocal.setScope(ProviderScope.LOCAL);

        defaultMessagingQos = new MessagingQos();

        properties = createProperties(TESTGBID1 + ", " + TESTGBID2, "tcp://localhost:1883, tcp://otherhost:1883");
        joynrRuntime = createJoynrRuntime();

        routingTable = injector.getInstance(RoutingTable.class);
        MqttMessagingSkeletonProvider mqttMessagingSkeletonProvider = injector.getInstance(MqttMessagingSkeletonProvider.class);
        mqttSkeletonFactory = (MqttMessagingSkeletonFactory) mqttMessagingSkeletonProvider.get();
        messagingSkeletonFactory = injector.getInstance(MessagingSkeletonFactory.class);
        messageFactory = injector.getInstance(MutableMessageFactory.class);

        // Get routingTable.hashMap
        routingTableHashMap = getFieldValue(routingTable, "hashMap");
        assertFalse(routingTableHashMap.isEmpty());

        sProxyParticipantId = "";
    }

    @After
    public void tearDown() {
        shutdownRuntime();
    }

    private void shutdownRuntime() {
        if (joynrRuntime != null) {
            joynrRuntime.shutdown(true);
        }
    }

    private Properties createProperties(String gbids, String brokerUris) throws IOException {
        Properties properties = new Properties();
        properties.setProperty(WebsocketModule.PROPERTY_WEBSOCKET_MESSAGING_HOST, "localhost");
        properties.setProperty(WebsocketModule.PROPERTY_WEBSOCKET_MESSAGING_PORT, "" + TestSetup.findFreePort());

        properties.setProperty(ConfigurableMessagingSettings.PROPERTY_GBIDS, gbids);
        properties.setProperty(MqttModule.PROPERTY_MQTT_BROKER_URIS, brokerUris);
        properties.setProperty(MqttModule.PROPERTY_KEY_MQTT_KEEP_ALIVE_TIMERS_SEC, "60,30");
        properties.setProperty(MqttModule.PROPERTY_KEY_MQTT_CONNECTION_TIMEOUTS_SEC, "60,30");
        properties.setProperty(ConfigurableMessagingSettings.PROPERTY_ROUTING_MAX_RETRY_COUNT,
                               String.valueOf(ROUTING_MAX_RETRY_COUNT));
        // Put properties for fixed participantIds
        String interfaceName = ProviderAnnotations.getInterfaceName(DefaulttestProvider.class);
        int majorVersion = ProviderAnnotations.getMajorVersion(DefaulttestProvider.class);
        properties.setProperty(ParticipantIdKeyUtil.getProviderParticipantIdKey(TESTCUSTOMDOMAIN1,
                                                                                interfaceName,
                                                                                majorVersion),
                               FIXEDPARTICIPANTID1);
        properties.setProperty(ParticipantIdKeyUtil.getProviderParticipantIdKey(TESTCUSTOMDOMAIN2,
                                                                                interfaceName,
                                                                                majorVersion),
                               FIXEDPARTICIPANTID2);
        properties.setProperty(ParticipantIdKeyUtil.getProviderParticipantIdKey(TESTCUSTOMDOMAIN3,
                                                                                interfaceName,
                                                                                majorVersion),
                               FIXEDPARTICIPANTID3);

        properties.setProperty(ConfigurableMessagingSettings.PROPERTY_ROUTING_TABLE_CLEANUP_INTERVAL_MS,
                               String.valueOf(ROUTINGTABLE_CLEANUP_INTERVAL_MS));
        properties.setProperty(SystemServicesSettings.PROPERTY_CC_REMOVE_STALE_DELAY_MS, String.valueOf(0));
        return properties;
    }

    private CountDownLatch waitForRemoveStale(MqttMessagingStub mqttMessagingStubMock) throws InterruptedException {
        // removeStale is called once at startup because ClusterControllerRuntime calls removeStale
        CountDownLatch cdl = new CountDownLatch(2);
        doAnswer((invocation) -> {
            cdl.countDown();
            return null;
        }).when(mqttMessagingStubMock).transmit(any(), any(), any());
        return cdl;
    }

    private Field getPrivateField(Class<?> privateClass, String fieldName) {
        Field result = null;
        try {
            result = privateClass.getDeclaredField(fieldName);
        } catch (Exception e) {
            fail(e.getMessage());
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    private <T> T getFieldValue(Object object, String fieldName) {
        Field objectField = getPrivateField(object.getClass(), fieldName);
        assertNotNull(objectField);
        objectField.setAccessible(true);
        T result = null;
        try {
            result = (T) objectField.get(object);
        } catch (Exception e) {
            fail(e.getMessage());
        }
        return result;
    }

    protected Answer<Void> createVoidCountDownAnswer(CountDownLatch countDownLatch) {
        return invocation -> {
            countDownLatch.countDown();
            return null;
        };
    }

    protected String getGcdParticipantId() {
        GlobalDiscoveryEntry gcdDiscoveryEntry = injector.getInstance(Key.get(GlobalDiscoveryEntry.class,
                                                                              Names.named(MessagingPropertyKeys.CAPABILITIES_DIRECTORY_DISCOVERY_ENTRY)));
        return gcdDiscoveryEntry.getParticipantId();
    }

    protected MutableMessage createVoidReply(ImmutableMessage requestMessage) {
        String requestReplyId = requestMessage.getCustomHeaders().get(Message.CUSTOM_HEADER_REQUEST_REPLY_ID);
        return messageFactory.createReply(requestMessage.getRecipient(),
                                          requestMessage.getSender(),
                                          new Reply(requestReplyId),
                                          new MessagingQos());
    }

    protected MutableMessage createReplyWithException(ImmutableMessage requestMessage, JoynrException error) {
        String requestReplyId = requestMessage.getCustomHeaders().get(Message.CUSTOM_HEADER_REQUEST_REPLY_ID);
        return messageFactory.createReply(requestMessage.getRecipient(),
                                          requestMessage.getSender(),
                                          new Reply(requestReplyId, error),
                                          new MessagingQos());
    }

    protected MutableMessage createRequestMsg(final String from, final String to) {
        Request request = new Request("voidOperation", new Object[0], new Class[0]);
        MutableMessage requestMsg = messageFactory.createRequest(from, to, request, defaultMessagingQos);
        String replyTo = RoutingTypesUtil.toAddressString(replyToAddress);
        requestMsg.setReplyTo(replyTo);
        return requestMsg;
    }

    protected MutableMessage createSrqMsg(final String from, final String to, String subscriptionId, long validityMs) {
        OnChangeSubscriptionQos qos = new OnChangeSubscriptionQos().setMinIntervalMs(0).setValidityMs(validityMs);
        BroadcastSubscriptionRequest request = new BroadcastSubscriptionRequest(subscriptionId,
                                                                                "intBroadcast",
                                                                                new BroadcastFilterParameters(),
                                                                                qos);
        MutableMessage requestMsg = messageFactory.createSubscriptionRequest(from, to, request, defaultMessagingQos);
        String replyTo = RoutingTypesUtil.toAddressString(replyToAddress);
        requestMsg.setReplyTo(replyTo);
        return requestMsg;
    }

    protected void fakeIncomingMqttMessage(String targetGbid, MutableMessage msg) throws EncodingException,
                                                                                UnsuppportedVersionException {
        IMqttMessagingSkeleton skeleton = (IMqttMessagingSkeleton) mqttSkeletonFactory.getSkeleton(new MqttAddress(targetGbid,
                                                                                ""));
        skeleton.transmit(msg.getImmutableMessage().getSerializedMessage(),
                          msg.getImmutableMessage().getPrefixedCustomHeaders(),
                          new FailureAction() {
                              @Override
                              public void execute(Throwable error) {
                                  fail("fake incoming MQTT message failed in skeleton.transmit: " + error);
                              }
                          });
    }

    protected void checkRefCnt(String participantId, long expectedRefCnt) {
        if (expectedRefCnt == 0) {
            assertFalse(routingTable.containsKey(participantId));
            return;
        }
        assertTrue(routingTable.containsKey(participantId));
        RoutingEntry routingEntry = routingTableHashMap.get(participantId);
        long actualRefCnt = routingEntry.getRefCount();
        assertEquals(expectedRefCnt, actualRefCnt);
    }

    protected ArbitrationStrategyFunction customArbitrationStrategyFor(Set<String> participantIds) {
        return new ArbitrationStrategyFunction() {
            @Override
            public Set<DiscoveryEntryWithMetaInfo> select(Map<String, String> parameters,
                                                          Collection<DiscoveryEntryWithMetaInfo> capabilities) {
                Set<DiscoveryEntryWithMetaInfo> result = new HashSet<>();
                for (String selectedDomain : participantIds) {
                    for (DiscoveryEntryWithMetaInfo entry : capabilities) {
                        if (entry.getParticipantId().equals(selectedDomain)) {
                            result.add(entry);
                        }
                    }
                }
                return result;
            }
        };
    }

    protected void waitFor(CountDownLatch cdl, long timeout) {
        try {
            assertTrue(cdl.await(timeout, TimeUnit.MILLISECONDS));
        } catch (InterruptedException e) {
            fail("wait failed: " + e);
        }
    }

    protected void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (Exception e) {
            fail("Sleep failed: " + e);
        }
    }

    protected void waitForGarbageCollection(String proxyParticipantId) throws InterruptedException {
        Semaphore gcSemaphore = new Semaphore(0);
        doAnswer((invocation) -> {
            invocation.callRealMethod();
            gcSemaphore.release();
            return null;
        }).when(shutdownNotifier).unregister(any(ShutdownListener.class));
        // wait until unregister of shutdownNotifier
        for (int i = 0; i < 120; i++) { // try for 1 minute
            System.gc();
            if (gcSemaphore.tryAcquire(500, TimeUnit.MILLISECONDS)) {
                System.out.println("Garbage collector has been called to remove proxy at " + i + " iteration!");
                break;
            }
        }
        assertFalse(routingTable.containsKey(proxyParticipantId));
    }

    protected <T> T createProxy(ProxyBuilder<T> proxyBuilder, MessagingQos messagingQos, DiscoveryQos discoveryQos) {
        T proxy = null;
        Future<T> proxyFuture = new Future<>();
        proxyBuilder.setMessagingQos(messagingQos).setDiscoveryQos(discoveryQos).build(new ProxyCreatedCallback<T>() {

            @Override
            public void onProxyCreationFinished(T result) {
                proxyFuture.resolve(result);
            }

            @Override
            public void onProxyCreationError(JoynrRuntimeException error) {
                proxyFuture.onFailure(error);
            }
        });
        try {
            proxy = proxyFuture.get();
        } catch (Exception e) {
            fail("Proxy creation failed: " + e.toString());
        }
        return proxy;
    }

    protected JoynrRuntime createJoynrRuntime() throws InterruptedException {
        AbstractModule testBindingsModule = new AbstractModule() {
            @Override
            protected void configure() {
                // Any mqtt clients shall be mocked
                bind(MqttClientFactory.class).toInstance(hiveMqMqttClientFactory);
                // We want to mock all MessagingStubs except the InProcess one
                bind(WebSocketClientMessagingStubFactory.class).toInstance(websocketClientMessagingStubFactoryMock);
                bind(WebSocketMessagingStubFactory.class).toInstance(webSocketMessagingStubFactoryMock);
                bind(MqttMessagingStubFactory.class).toInstance(mqttMessagingStubFactoryMock);
                bind(InProcessMessagingStubFactory.class).toInstance(inProcessMessagingStubFactorySpy);

                bind(ShutdownNotifier.class).toInstance(shutdownNotifier);
                bind(ProxyBuilderFactory.class).to(TestProxyBuilderFactory.class);

                Multibinder<JoynrMessageProcessor> processors = Multibinder.newSetBinder(binder(),
                                                                                new TypeLiteral<JoynrMessageProcessor>() {
                                                                                });
                processors.addBinding().toInstance(messageProcessorMock);
            }
        };

        injector = Guice.createInjector(override(new CCWebSocketRuntimeModule(),
                                                 new HivemqMqttClientModule()).with(new JoynrPropertiesModule(properties),
                                                                                testBindingsModule));
        CountDownLatch cdl = waitForRemoveStale(mqttMessagingStubMock);

        JoynrRuntime joynrRuntime = injector.getInstance(JoynrRuntime.class);

        assertTrue(cdl.await(10, TimeUnit.SECONDS));
        reset(mqttMessagingStubMock);
        return joynrRuntime;
    }

    protected void registerProvider(JoynrProvider provider, String domain, ProviderQos providerQos) {
        try {
            // wait for successful registration
            joynrRuntime.getProviderRegistrar(domain, provider)
                        .withProviderQos(providerQos)
                        .awaitGlobalRegistration()
                        .register()
                        .get(10000);
        } catch (Exception e) {
            fail("Provider registration failed: " + e.toString());
        }
    }

    protected void registerGlobal(JoynrProvider provider, String domain, ProviderQos providerQos) {
        reset(mqttMessagingStubMock);
        CountDownLatch publishCountDownLatch = new CountDownLatch(1);
        ArgumentCaptor<ImmutableMessage> messageCaptor = ArgumentCaptor.forClass(ImmutableMessage.class);
        doAnswer(createVoidCountDownAnswer(publishCountDownLatch)).when(mqttMessagingStubMock)
                                                                  .transmit(messageCaptor.capture(),
                                                                            any(SuccessAction.class),
                                                                            any(FailureAction.class));

        Future<Void> future = joynrRuntime.getProviderRegistrar(domain, provider)
                                          .withProviderQos(providerQos)
                                          .withGbids(gbids)
                                          .awaitGlobalRegistration()
                                          .register();

        try {
            assertTrue(publishCountDownLatch.await(1500, TimeUnit.MILLISECONDS));
        } catch (InterruptedException e) {
            fail(e.toString());
        }

        verify(mqttMessagingStubMock).transmit(any(ImmutableMessage.class),
                                               any(SuccessAction.class),
                                               any(FailureAction.class));
        ImmutableMessage capturedMessage = messageCaptor.getValue();
        assertEquals(Message.MessageType.VALUE_MESSAGE_TYPE_REQUEST, capturedMessage.getType());
        assertEquals(getGcdParticipantId(), capturedMessage.getRecipient());

        reset(mqttMessagingStubMock);

        try {
            MutableMessage replyMessage = createVoidReply(capturedMessage);
            fakeIncomingMqttMessage(gbids[0], replyMessage);
            // wait for successful registration
            future.get(10000);
        } catch (Exception e) {
            fail("Provider registration failed: " + e.toString());
        }
    }

    protected ArgumentCaptor<ImmutableMessage> prepareGlobalRemove(CountDownLatch removeCdl) {
        ArgumentCaptor<ImmutableMessage> messageCaptor = ArgumentCaptor.forClass(ImmutableMessage.class);
        doAnswer(createVoidCountDownAnswer(removeCdl)).when(mqttMessagingStubMock).transmit(messageCaptor.capture(),
                                                                                any(SuccessAction.class),
                                                                                any(FailureAction.class));
        return messageCaptor;
    }

    protected void waitForGlobalRemove(CountDownLatch removeCdl, ArgumentCaptor<ImmutableMessage> msgCaptor) {

        try {
            assertTrue(removeCdl.await(10000, TimeUnit.MILLISECONDS));
        } catch (InterruptedException e) {
            fail(e.toString());
        }

        verify(mqttMessagingStubMock).transmit(any(ImmutableMessage.class),
                                               any(SuccessAction.class),
                                               any(FailureAction.class));
        ImmutableMessage capturedMessage = msgCaptor.getValue();
        assertEquals(Message.MessageType.VALUE_MESSAGE_TYPE_REQUEST, capturedMessage.getType());
        assertEquals(getGcdParticipantId(), capturedMessage.getRecipient());

        try {
            MutableMessage replyMessage = createVoidReply(capturedMessage);
            fakeIncomingMqttMessage(gbids[0], replyMessage);
        } catch (Exception e) {
            fail("Provider unregistration failed: " + e.toString());
        }

        reset(mqttMessagingStubMock);
    }

    protected void unregisterGlobal(String domain, Object provider) {
        reset(mqttMessagingStubMock);
        CountDownLatch removeCdl = new CountDownLatch(1);
        ArgumentCaptor<ImmutableMessage> msgCaptor = prepareGlobalRemove(removeCdl);
        joynrRuntime.unregisterProvider(domain, provider);
        waitForGlobalRemove(removeCdl, msgCaptor);
        // Wait for a while until global remove has finished (reply processed at LCD)
        try {
            Thread.sleep(200);
        } catch (Exception e) {
            fail("Sleeping failed: " + e.toString());
        }
    }

}


text: CKEDITOR.plugins.setLang("devtools","id",{title:"Informasi Elemen",dialogName:"Nama jendela dialog",tabName:"Nama tab",elementId:"ID Elemen",elementType:"Tipe elemen"});


text:
Zepto(function($){
	rs_init();

});

function rs_init(){
	if(evalReady&&(evalSupported!=null)&&(evalSupported!='')){
		splits = evalSupported.split(",");
		$.each(splits, function(i, k){
			$('.rsType').append("<option>"+k+"</option>");
		});
	}
	else setTimeout('rs_init()', 1000);

	$('#packetContent').on('keydown', function(e){
		if(e.ctrlKey && (e.keyCode == 10 || e.keyCode == 13)){
			packet_go();
		}
		fix_tabchar(this, e);
	});
}

function rs_go_bind(){
	rs_go('bind');
}
function rs_go_back(){
	rs_go('back');
}

function rs_go(rsType){
	rsArgs = "";
	if(rsType=='bind'){
		rsPort = parseInt($('#bindPort').val());
		rsLang = $('#bindLang').val();
		rsArgs = rsPort;
		rsResult = $('#bindResult');
	}
	else if(rsType=='back'){
		rsAddr = $('#backAddr').val();
		rsPort = parseInt($('#backPort').val());
		rsLang = $('#backLang').val();
		rsArgs = rsPort + ' ' + rsAddr;
		rsResult = $('#backResult');
	}

	if((isNaN(rsPort))||(rsPort<=0)||(rsPort>65535)){
		rsResult.html('Invalid port');
		return;
	}

	if(rsArgs!=''){
		send_post({ rsLang:rsLang, rsArgs:rsArgs },
			function(res){
				if(res!='error'){
					splits = res.split('{[|b374k|]}');
					if(splits.length==2){
						output = splits[0]+"
"+splits[1];
						rsResult.html(output);
					}
					else{
						rsResult.html(res);
					}
				}
			}
		);
	}
}

function packet_go(){
	packetHost = $('#packetHost').val();
	packetStartPort = parseInt($('#packetStartPort').val());
	packetEndPort = parseInt($('#packetEndPort').val());
	packetTimeout = parseInt($('#packetTimeout').val());
	packetSTimeout = parseInt($('#packetSTimeout').val());
	packetContent = $('#packetContent').val();
	packetResult = $('#packetResult');
	packetStatus = $('#packetStatus');

	if((isNaN(packetStartPort))||(packetStartPort<=0)||(packetStartPort>65535)){
		packetResult.html('Invalid start port');
		return;
	}
	if((isNaN(packetEndPort))||(packetEndPort<=0)||(packetEndPort>65535)){
		packetResult.html('Invalid end port');
		return;
	}
	if((isNaN(packetTimeout))||(packetTimeout<=0)){
		packetResult.html('Invalid connection timeout');
		return;
	}
	if((isNaN(packetSTimeout))||(packetSTimeout<=0)){
		packetResult.html('Invalid stream timeout');
		return;
	}

	if(packetStartPort>packetEndPort){
		start = packetEndPort;
		end = packetStartPort;
	}
	else{
		start = packetStartPort;
		end = packetEndPort;
	}

	packetResult.html('');
	while(start<=end){
		packetPort = start++;
		packetResult.append("

Host : "+html_safe(packetHost)+":"+packetPort+"

Working... please wait...

");
		packet_send(packetHost, packetPort, packetEndPort, packetTimeout, packetSTimeout, packetContent);

	}
}

function packet_send(packetHost, packetPort, packetEndPort, packetTimeout, packetSTimeout, packetContent){
	send_post({packetHost:packetHost, packetPort:packetPort, packetEndPort:packetEndPort, packetTimeout:packetTimeout, packetSTimeout:packetSTimeout, packetContent:packetContent}, function(res){
		$('#packet'+packetPort).html(res);
	}, false);
}


text:
package frontend;

import frontend.pascal.PascalTokenType;

/**
 * The generic end of file token
 *
 */
public class EofToken extends Token{

	public EofToken(Source source) throws Exception {
		super(source);
		type = PascalTokenType.END_OF_FILE;
	}

	/**
	 * Do nothing. Do not consume any source characters.
	 * @throws Exception if an error occurred
	 */
	@Override
	protected void extract() throws Exception {
		// do nothing
	}
}


text:
<?xml version="1.0"?>
<package>
  <name>tams_ur5_setup</name>
  <version>0.0.0</version>
  <description>meta package for TAMS' UR5 laboratory setup</description>

  <maintainer email="goerner@iformatik.uni-hamburg.de">Michael Goerner</maintainer>
  <author email="5jonetzk@informatik.uni-hamburg.de">Yannick Jonetzko</author>
  <license>BSD</license>

  <buildtool_depend>catkin</buildtool_depend>
  <run_depend>tams_ur5_setup_bringup</run_depend>
  <run_depend>tams_ur5_setup_description</run_depend>
  <run_depend>tams_ur5_setup_moveit_config</run_depend>
  <run_depend>camera_positioner</run_depend>

  <export>
    <metapackage/>
  </export>
</package>


text:
<?php

namespace Mascame\Artificer\Permit;

use Mascame\Artificer\Options\AdminOption;

class MenuPermit extends Permit
{
    public static function access($menu)
    {
        $menu_permissions = AdminOption::get('menu.'.$menu.'.permissions');

        return self::hasPermission($menu_permissions);
    }

    public static function to($action)
    {
    }
}


text:
{-
 - Hacq (c) 2013 NEC Laboratories America, Inc.  All rights reserved.
 -
 - This file is part of Hacq.
 - Hacq is distributed under the 3-clause BSD license.
 - See the LICENSE file for more details.
 -}

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE UndecidableInstances #-}

module Control.Monad.Quantum.Toffoli.ToStandard where

import Control.Applicative (Applicative)
import Control.Monad (when)

import Control.Monad.Ask.Class (MonadAsk)
import Control.Monad.Memo.Class
import Control.Monad.Quantum.Base.Class
import Control.Monad.Quantum.Toffoli.Class
import Control.Monad.Quantum.CircuitBuilder.Class
import Control.Monad.Quantum.Counter.Class
import Data.Quantum.Wire

-- |An implementation of `MonadToffoli` on top of a `MonadQuantumBase`.
--
-- `applyXCC` and `applyZCC` uses the implementation of Toffoli with 7 T gates and T-depth 1,
-- presented by Peter Selinger in the IARPA QCS review meeting in July 2012.
--
-- `destructiveToffoli` uses the implementation with 4 T gates and T-depth 1,
-- as discussed in the TORQUE team meeting on July 19, 2012.
-- As a result, @destructiveToffoli w a b@ applies −iX to @w@ conditioned on @a@ and @b@ both being |1>.

newtype ToffoliToStandardT w m a = ToffoliToStandardT {
  runToffoliToStandardT :: m a
} deriving (Functor, Applicative, Monad, MonadAsk r, MonadQuantumBase w, MonadMemo k, MonadQuantumCounter w c)

deriving instance MonadCircuitBuilder g m => MonadCircuitBuilder g (ToffoliToStandardT Wire m)

instance MonadQuantumBase w m => MonadToffoli w (ToffoliToStandardT w m) where

  rawApplyXCC a b negb c negc =
      with_ (applyH a) $
        rawApplyZCC a False b negb c negc
  {-# INLINABLE rawApplyXCC #-}

  rawApplyZCC a nega b negb c negc =
      with (do
          when nega $ applyX a
          when negb $ applyX b
          when negc $ applyX c
          ab <- ancilla
          bc <- ancilla
          ca <- ancilla
          abc <- ancilla
          cnotWire ab (bit a)
          cnotWire ca (bit a)
          cnotWire abc (bit a)
          cnotWire bc (bit b)
          cnotWire ab (bit b)
          cnotWire abc (bit b)
          cnotWire ca (bit c)
          cnotWire bc (bit c)
          cnotWire abc (bit c)
          return (ab, bc, ca, abc)) $ \(ab, bc, ca, abc) ->
        parallels_ [applyT (bit a) False, applyT (bit b) False, applyT (bit c) False,
                       applyT (bit ab) True, applyT (bit bc) True, applyT (bit ca) True,
                       applyT (bit abc) False]
  {-# INLINABLE rawApplyZCC #-}

  rawDestructiveToffoli w a nega b negb =
      with (do
          when nega $ applyX a
          when negb $ applyX b
          aw <- ancilla
          bw <- ancilla
          abw <- ancilla
          applyH w
          cnotWire aw (bit a)
          cnotWire abw (bit a)
          cnotWire bw (bit b)
          cnotWire abw (bit b)
          cnotWire aw (bit w)
          cnotWire bw (bit w)
          cnotWire abw (bit w)
          return (aw, bw, abw)) $ \(aw, bw, abw) ->
        parallels_ [applyT (bit w) False, applyT (bit aw) True, applyT (bit bw) True, applyT (bit abw) False]
  {-# INLINABLE rawDestructiveToffoli #-}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using System.IO;
using System.Data.OleDb;
using System.Xml;
using System.Configuration;
using System.Collections.Specialized;
using System.Threading;

namespace WeCode1._0
{
    public partial class FormAttachment : DockContent
    {

        //上传参数
        private string _upUrl;
        private string _upFilePath;
        private string _upFileName;

        public FormAttachment()
        {
            InitializeComponent();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void FormAttachment_Load(object sender, EventArgs e)
        {
            //dataGridView1.DataSource = AccessAdo.ExecuteDataSet("select '' as 序号,[title] as 标题,[size] as 大小,[time] as 加入日期 from tattachment where nodeid=-1").Tables[0];
            ReFreshAttachGrid();
        }

        //刷新附件
        public void ReFreshAttachGrid()
        {
            CheckForIllegalCrossThreadCalls = false;
            try {
                //本地附件
            if (Attachment.ActiveDOCType == "local")
            {
                DataView dv = new DataView(AccessAdo.ExecuteDataSet("select affixid,nodeid,'' as 序号,[title] as 标题,format$([size]/1024,\"Fixed\")+'KB' as 大小,[time],' ' as 加入日期 from tattachment where nodeid=" + Attachment.ActiveNodeId).Tables[0]);
                dataGridView1.DataSource = dv;
                dataGridView1.Columns[0].Visible = false;
                dataGridView1.Columns[1].Visible = false;
                dataGridView1.Columns[5].Visible = false;

                int count = dv.Count;
                for (int i = 0; i < count; i++)
                {
                    dataGridView1.Rows[i].Cells[2].Value = i + 1;
                    string TotalSeConds = dataGridView1.Rows[i].Cells[5].Value.ToString();
                    DateTime AttTime = PubFunc.seconds2Time(Convert.ToInt32(TotalSeConds));
                    dataGridView1.Rows[i].Cells[6].Value = AttTime.ToString();
                }
            }
            else if (Attachment.ActiveDOCType == "online")
            {
                //有道附件
                youdao.YouDaoNode2 node = NoteAPI.GetNote(Attachment.ActiveNodeId);
                if (node == null)
                {
                    return;
                }
                DataTable tempDt=new DataTable();
                tempDt.Columns.Add("path");
                tempDt.Columns.Add("序号");
                tempDt.Columns.Add("标题");
                tempDt.Columns.Add("大小");
                tempDt.Columns.Add("加入日期");
                int i=1;
                foreach (Dictionary<string, string> item in node.GetAttachments())
                {
                    DataRow dr = tempDt.NewRow();
                    dr["path"] = item["path"];
                    dr["序号"] = i;
                    dr["标题"] = item["title"];
                    dr["大小"] = (double.Parse(item["filelength"])/1024).ToString("0.00")+"KB";
                    dr["加入日期"] = "";
                    tempDt.Rows.Add(dr);
                    i++;
                }

                DataView dv = new DataView(tempDt);
                dataGridView1.DataSource = dv;
                dataGridView1.Columns[0].Visible = false;
            }
            }
            catch(Exception e)
            {

            }

        }

        //添加附件
        private void toolStripMenuItemAddZIP_Click(object sender, EventArgs e)
        {
            AddAttZip();
        }

        private void AddAttZip()
        {
            if (Attachment.ActiveNodeId == "-1")
                return;

            Stream myStream;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            //openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "All files (*.*)|*.*";
            openFileDialog1.RestoreDirectory = false;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //先校验文件大小以及文件格式
                FileInfo finfo = new FileInfo(openFileDialog1.FileName);
                if (finfo.Length >= 25000000)
                {
                    MessageBox.Show("附件最大大小必须小于25MB,请重试!");
                    return;
                }

                string fileName = openFileDialog1.FileName;
                if ((myStream = openFileDialog1.OpenFile()) != null)
                {
                    // Insert code to read the stream here.
                    FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
                    byte[] data = new byte[fs.Length];
                    fs.Read(data, 0, (int)fs.Length);

                    int Datalength = (int)fs.Length;
                    fs.Close();

                    string NewAffixid = AccessAdo.ExecuteScalar("select max(affixid) from tattachment").ToString();
                    int intNewAffixid = NewAffixid == "" ? 1 : Convert.ToInt32(NewAffixid) + 1;

                    int Nodeid = Convert.ToInt32(Attachment.ActiveNodeId);
                    string Title = openFileDialog1.SafeFileName;
                    int timeSeconds = PubFunc.time2TotalSeconds();

                    //affixid
                    OleDbParameter p1 = new OleDbParameter("@affixid", OleDbType.Integer);
                    p1.Value = intNewAffixid;
                    //nodeid
                    OleDbParameter p2 = new OleDbParameter("@nodeid", OleDbType.Integer);
                    p2.Value = Nodeid;
                    //title
                    OleDbParameter p3 = new OleDbParameter("@title", OleDbType.VarChar);
                    p3.Value = Title;
                    //二进制数据
                    OleDbParameter p4 = new OleDbParameter("@Data", OleDbType.Binary);
                    p4.Value = data;
                    //size
                    OleDbParameter p5 = new OleDbParameter("@size", OleDbType.Integer);
                    p5.Value = Datalength;
                    //time
                    OleDbParameter p6 = new OleDbParameter("@time", OleDbType.Integer);
                    p6.Value = timeSeconds;

                    OleDbParameter[] arrPara = new OleDbParameter[6];
                    arrPara[0] = p1;
                    arrPara[1] = p2;
                    arrPara[2] = p3;
                    arrPara[3] = p4;
                    arrPara[4] = p5;
                    arrPara[5] = p6;
                    string SQL = "insert into tattachment([affixId],[NodeId],[Title],[Data],[Size],[Time]) values(@affixid,@nodeid,@title,@Data,@size,@time)";
                    AccessAdo.ExecuteNonQuery(SQL, arrPara);

                    myStream.Close();

                    ReFreshAttachGrid();
                }
            }
        }

        //另存为
        private void toolStripMenuItemSaveAs_Click(object sender, EventArgs e)
        {
            string Affixid = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
            string Title = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
            byte[] TempData = (byte[])AccessAdo.ExecuteScalar("select data from tattachment where affixid=" + Affixid);

            string Path;
            SaveFileDialog sf=new SaveFileDialog();
            sf.FileName=Title;
            //设置文件类型
            sf.Filter = "All files(*.*)|*.*";
            if (sf.ShowDialog() == DialogResult.OK)
            {
                Path = sf.FileName;
                FileStream fs = new FileStream(Path, FileMode.Create);
                fs.Write(TempData, 0, TempData.Length);
                fs.Close();
            }

        }

        //右键菜单
        private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && e.RowIndex > -1 && e.ColumnIndex > -1 && Attachment.ActiveDOCType == "local")
            {
                dataGridView1.CurrentRow.Selected = false;
                dataGridView1.Rows[e.RowIndex].Selected = true;
                contextMenuStripAtt1.Show(MousePosition.X, MousePosition.Y);
            }
            else if (e.Button == MouseButtons.Right && e.RowIndex > -1 && e.ColumnIndex > -1 && Attachment.ActiveDOCType == "online")
            {
                if (dataGridView1.CurrentRow != null)
                {
                    dataGridView1.CurrentRow.Selected = false;
                }
                dataGridView1.Rows[e.RowIndex].Selected = true;
                contextMenuStripOL1.Show(MousePosition.X, MousePosition.Y);
            }
        }

        //右键菜单
        private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right&&Attachment.ActiveDOCType=="local")
            {
                contextMenuStripAtt2.Show(MousePosition.X, MousePosition.Y);
            }
            else if (e.Button == MouseButtons.Right && Attachment.ActiveDOCType == "online")
            {
                contextMenuStripOL2.Show(MousePosition.X, MousePosition.Y);
            }
        }

        private void 添加附件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddAttZip();
        }

        //打开附件
        private void toolStripMenuItemOpenZIP_Click(object sender, EventArgs e)
        {
            string Affixid = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
            string Title = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
            byte[] TempData = (byte[])AccessAdo.ExecuteScalar("select data from tattachment where affixid=" + Affixid);

            string Path = Environment.CurrentDirectory;
            if (!Directory.Exists(@Path + "\\temp"))
            {
                Directory.CreateDirectory(@Path + "\\temp");
            }
            Path = @Path + "\\temp\\"+Title;

            FileStream fs = new FileStream(Path, FileMode.Create);
            fs.Write(TempData, 0, TempData.Length);
            fs.Close();
            System.Diagnostics.Process.Start(Path);
        }

        //删除附件
        private void toolStripMenuItemDelZIP_Click(object sender, EventArgs e)
        {
            string Affixid = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
            AccessAdo.ExecuteNonQuery("delete from tattachment where affixid=" + Affixid);
            ReFreshAttachGrid();
        }

        //重命名
        private void toolStripMenuItemReName_Click(object sender, EventArgs e)
        {
            string Affixid = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
            string Title = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();

            AttRenameDialog ReNameDia = new AttRenameDialog(Title);
            DialogResult dr = ReNameDia.ShowDialog();
            if (dr == DialogResult.OK)
            {
                Title = ReNameDia.ReturnVal[0];
                AccessAdo.ExecuteNonQuery("update tattachment set title='" + Title + "' where affixid=" + Affixid);
                ReFreshAttachGrid();
            }
        }

        //上传云附件
        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            if (ConfigurationManager.AppSettings["AccessToken"] != "")
            {
                try
                {
                    //获取AccessTokon构造URL
                    StringBuilder url = new StringBuilder("https://note.youdao.com/yws/open/resource/upload.json"); //可变字符串

                    NameValueCollection myCol = new NameValueCollection();
                    myCol.Add("nihao", "nihao");

                    OpenFileDialog op = new OpenFileDialog();
                    DialogResult dr = op.ShowDialog();
                    if (dr == DialogResult.OK)
                    {
                        //先校验文件大小以及文件格式
                        FileInfo finfo = new FileInfo(op.FileName);
                        if (finfo.Length >= 25000000)
                        {
                            MessageBox.Show("附件最大大小必须小于25MB,请重试!");
                            return;
                        }
                        else if(finfo.Extension.ToUpper()==".EXE"||finfo.Extension.ToUpper()==".COM"||finfo.Extension.ToUpper()==".BAT"||finfo.Extension.ToUpper()==".CMD"||finfo.Extension.ToUpper()==".SYS")
                        {
                            MessageBox.Show("不允许上传exe、com、cmd、bat、sys格式的附件,请重试!");
                            return;
                        }
                        // string aaa = HttpPostFile(url.ToString(), op.SafeFileName,op.FileName, myCol);
                        //Upload_Request(url.ToString(), op.FileName, op.SafeFileName, progressBar1);
                        //新线程打开下载窗口
                        //_upUrl = url.ToString();
                        //_upFilePath = op.FileName;
                        //_upFileName = op.SafeFileName;

                        //UpLoad upForm = new UpLoad(_upUrl, _upFilePath, _upFileName,Attachment.ActiveNodeId);
                        //upForm.Show();

                        _upUrl = url.ToString();
                        _upFilePath = op.FileName;
                        _upFileName = op.SafeFileName;

                        UpLoad upForm = new UpLoad(_upUrl, _upFilePath, _upFileName, Attachment.ActiveNodeId);
                        upForm.Show();

                        //Thread t = new Thread(new ThreadStart(ThFun));
                        //t.Start();

                    }

                }
                catch (Exception msg) //异常处理
                {
                    MessageBox.Show(msg.Message);
                }
            }
        }

        //上传云附件
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            toolStripMenuItem5_Click(sender, e);
        }

        public void GridDiable()
        {
            this.dataGridView1.Enabled = false;
        }

        public void GridEnable()
        {
            this.dataGridView1.Enabled = true;
        }

        //下载云附件
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            try
            {
                //下载路径
                string path = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
                string Title = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();

                //获取AccessTokon构造URL
                StringBuilder url = new StringBuilder(path); //可变字符串
                //追加组合格式字符串
                url.AppendFormat("?oauth_token={0}&", ConfigurationManager.AppSettings["AccessToken"]);

                string Input = url.ToString();

                ////HttpWebRequest对象实例:该类用于获取和操作HTTP请求
                //var request = (HttpWebRequest)WebRequest.Create(Input); //Create:创建WebRequest对象
                ////设置请求方法为GET
                ////request.Headers.Add("Authorization", "Bearer " + accessToken);
                //request.Method = "GET";
                ////HttpWebResponse对象实例:该类用于获取和操作HTTP应答
                //var response = (HttpWebResponse)request.GetResponse(); //GetResponse:获取答复
                ////构造数据流对象实例
                //Stream stream = response.GetResponseStream(); //GetResponseStream:获取应答流

                string Path;
                SaveFileDialog sf = new SaveFileDialog();
                sf.FileName = Title;
                //设置文件类型
                sf.Filter = "All files(*.*)|*.*";
                if (sf.ShowDialog() == DialogResult.OK)
                {
                    Path = sf.FileName;
                    Download dl = new Download(Input, Path);
                    dl.Show();
                }

                //关闭响应流
                //stream.Close();
                //response.Close();
            }
            catch (Exception msg) //异常处理
            {
                MessageBox.Show(msg.Message);
            }
        }

        //删除附件
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            //修改笔记
            string path = Attachment.ActiveNodeId;
            string rsurl=dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
            NoteAPI.DeleteRource(path, rsurl);

            //更新缓存数据
            OleDbConnection ExportConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+PubFunc.GetYoudaoDBPath());
            string gid = AccessAdo.ExecuteScalar(ExportConn, "select gid from ttree where path='" + path + "'").ToString();
            AccessAdo.ExecuteNonQuery(ExportConn, "delete from tattachment where gid='" + gid + "'");

            ReFreshAttachGrid();
        }

        //重命名附件
        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            string path = Attachment.ActiveNodeId;
            string rsurl = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
            string Title = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();

            AttRenameDialog ReNameDia = new AttRenameDialog(Title);
            DialogResult dr = ReNameDia.ShowDialog();
            if (dr == DialogResult.OK)
            {
                Title = ReNameDia.ReturnVal[0];
                NoteAPI.RenameRource(path, rsurl,Title);

                //更新缓存数据
                OleDbConnection ExportConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+PubFunc.GetYoudaoDBPath());
                string gid = AccessAdo.ExecuteScalar(ExportConn, "select gid from ttree where path='" + path + "'").ToString();
                AccessAdo.ExecuteNonQuery(ExportConn,"update tattachment set title='" + Title + "' where gid='" + gid+"'");

                ReFreshAttachGrid();
            }

        }
    }
}


text:
"use strict";

const path = require("path");

const given = require("mocha-testdata");
const should = require("should");

const AliasMap = require("../../lib/AliasMap").AliasMap;
const BehaviorMap = require("../../lib/BehaviorMap").BehaviorMap;
const Environment = require("../../lib/Environment").Environment;
const ProjectConfig = require("../../lib/ProjectConfig").ProjectConfig;
const ResourceType = require("../../lib/ResourceType").ResourceType;
const Resource = require("../../lib/Resource").Resource;

describe("Environment", function () {

  beforeEach(function () {
    this.env = new Environment();
    this.env.projectRootPath = path.resolve(__dirname, "../fixtures/empty-project");
  });

  it("is named 'Environment'", function () {
    Environment.name
      .should.be.eql("Environment");
  });

  describe("#constructor()", function () {

    it("is a function", function () {
      Environment.prototype.constructor
        .should.be.a.Function();
    });

  });

  describe("#baseUrl", function () {

    it("has an initial value of '/'", function () {
      let newEnv = new Environment();
      newEnv.baseUrl
        .should.be.eql("/");
    });

  });

  describe("#baseUrl=", function () {

    it("updates value of the property", function () {
      this.env.baseUrl = "http://example.com";
      this.env.baseUrl
        .should.be.eql("http://example.com");
    });

  });

  describe("#behaviors", function () {

    it("is a `BehaviorMap`", function () {
      this.env.behaviors
        .should.be.instanceOf(BehaviorMap);
    });

    it("is read-only", function () {
      (() => this.env.behaviors = 42)
        .should.throw();
    });

  });

  describe("#config", function () {

    it("is a `ProjectConfig", function () {
      this.env.config
        .should.be.instanceOf(ProjectConfig);
    });

    it("is read-only", function () {
      (() => this.env.config = 42)
        .should.throw();
    });

  });

  describe("#defaultGeneratorName", function () {

    it("is 'standard' by default", function () {
      this.env.defaultGeneratorName
        .should.be.eql("standard");
    });

  });

  describe("#defaultGeneratorName=", function () {

    it("throws error if argument 'value' is an empty string", function () {
      let value = "";
      (() => this.env.defaultGeneratorName = value)
        .should.throw("argument 'value' must be a non-empty string");
    });

    it("updates value of the property", function () {
      this.env.defaultGeneratorName = "foo";
      this.env.defaultGeneratorName
        .should.be.eql("foo");
    });

  });

  describe("#defaultModeName", function () {

    it("is 'text' by default", function () {
      this.env.defaultModeName
        .should.be.eql("text");
    });

  });

  describe("#defaultModeName=", function () {

    it("throws error if argument 'value' is an empty string", function () {
      let value = "";
      (() => this.env.defaultModeName = value)
        .should.throw("argument 'value' must be a non-empty string");
    });

    it("updates value of the property", function () {
      this.env.defaultModeName = "foo";
      this.env.defaultModeName
        .should.be.eql("foo");
    });

  });

  describe("#resourceTypes", function () {

    it("is an `AliasMap`", function () {
      this.env.resourceTypes
        .should.be.instanceOf(AliasMap);
    });

    it("is read-only", function () {
      (() => this.env.resourceTypes = 42)
        .should.throw();
    });

    it("falls back to the default resource type '*'", function () {
      this.env.resourceTypes.set("*", new ResourceType());
      this.env.resourceTypes.resolveKey("key-that-does-not-exist")
        .should.be.eql("*");
    });

  });

  describe("#generators", function () {

    it("is an `AliasMap`", function () {
      this.env.generators
        .should.be.instanceOf(AliasMap);
    });

    it("is read-only", function () {
      (() => this.env.generators = 42)
        .should.throw();
    });

  });

  describe("#handlers", function () {

    it("is an `AliasMap`", function () {
      this.env.handlers
        .should.be.instanceOf(AliasMap);
    });

    it("is read-only", function () {
      (() => this.env.handlers = 42)
        .should.throw();
    });

  });

  describe("#hiddenUrlExtensions", function () {

    it("is a set", function () {
      this.env.hiddenUrlExtensions.has
        .should.be.a.Function();
      this.env.hiddenUrlExtensions.add
        .should.be.a.Function();
      this.env.hiddenUrlExtensions.delete
        .should.be.a.Function();
    });

    it("is read-only", function () {
      (() => this.env.hiddenUrlExtensions = new Set())
        .should.throw();
    });

  });

  describe("#hiddenUrlFileNames", function () {

    it("is a set", function () {
      this.env.hiddenUrlFileNames.has
        .should.be.a.Function();
      this.env.hiddenUrlFileNames.add
        .should.be.a.Function();
      this.env.hiddenUrlFileNames.delete
        .should.be.a.Function();
    });

    it("is read-only", function () {
      (() => this.env.hiddenUrlFileNames = new Set())
        .should.throw();
    });

  });

  describe("#modes", function () {

    it("is an `AliasMap`", function () {
      this.env.modes
        .should.be.instanceOf(AliasMap);
    });

    it("is read-only", function () {
      (() => this.env.modes = 42)
        .should.throw();
    });

  });

  describe("#projectRootPath", function () {

    it("is empty by default", function () {
      let newEnv = new Environment();
      newEnv.projectRootPath
        .should.be.eql("");
    });

  });

  describe("#projectRootPath=", function () {

    it("updates value of the property", function () {
      this.env.projectRootPath = "/abc";
      this.env.projectRootPath
        .should.be.eql("/abc");
    });

    it("trims trailing slash from assigned value", function () {
      this.env.projectRootPath = "/abc/";
      this.env.projectRootPath
        .should.be.eql("/abc");
    });

  });

  describe("#templateEngines", function () {

    it("is an `AliasMap`", function () {
      this.env.templateEngines
        .should.be.instanceOf(AliasMap);
    });

    it("is read-only", function () {
      (() => this.env.templateEngines = 42)
        .should.throw();
    });

  });

  describe("#transformers", function () {

    it("is an `AliasMap`", function () {
      this.env.transformers
        .should.be.instanceOf(AliasMap);
    });

    it("is read-only", function () {
      (() => this.env.transformers = 42)
        .should.throw();
    });

  });

  describe("#build()", function () {

    it("is a function", function () {
      this.env.build
        .should.be.a.Function();
    });

    it("returns a promise", function () {
      this.env.build()
        .should.be.a.Promise();
    });

    it("assumes override 'build' behavior", function () {
      let invokedOverride = false;

      this.env.behaviors.set("build", function () {
        invokedOverride = true;
        return Promise.resolve();
      });

      return this.env.build()
        .then(() => {
          invokedOverride.should.be.true();
        });
    });

  });

  describe("#clean()", function () {

    it("is a function", function () {
      this.env.clean
        .should.be.a.Function();
    });

    it("returns a promise", function () {
      this.env.clean()
        .should.be.a.Promise();
    });

    it("assumes override 'clean' behavior", function () {
      let invokedOverride = false;

      this.env.behaviors.set("clean", function () {
        invokedOverride = true;
        return Promise.resolve();
      });

      return this.env.clean()
        .then(() => {
          invokedOverride.should.be.true();
        });
    });

  });

  describe("#createResource", function () {

    it("is a function", function () {
      this.env.createResource
        .should.be.a.Function();
    });

    it("returns a Resource", function () {
      this.env.createResource()
        .should.be.instanceOf(Resource);
    });

    it("returns a new Resource instance each time", function () {
      this.env.createResource()
        .should.not.be.exactly(this.env.createResource());
    });

    it("passes properties to constructor of new resource", function () {
      let props = { type: "greeting", message: "Hello, world!" };
      this.env.createResource(props)
        .should.have.properties(props);
    });

  });

  describe("#getOutputRelativePathForResource(path, [extension], [page])", function () {

    it("is a function", function () {
      this.env.getOutputRelativePathForResource
        .should.be.a.Function();
    });

    it("throws error if argument 'path' is an empty string", function () {
      let path = "";
      (() => this.env.getOutputRelativePathForResource(path))
        .should.throw("argument 'path' must be a non-empty string");
    });

    given(
      [ "blog", null, null, "blog" ],
      [ "blog/index", ".html", null, "blog/index.html" ],
      [ "blog/index", ".html", "2", "blog/index/2.html" ],
      [ "blog/index", null, "2", "blog/index/2" ],
      [ "blog/index", ".def", "2", "blog/index/2.def" ]
    ).
    it("returns the expected output relative path", function (path, extension, page, expectedResult) {
      this.env.getOutputRelativePathForResource(path, extension, page)
        .should.be.eql(expectedResult);
    });

  });

  describe("#getUrlForResource(outputRelativePath, [baseUrl])", function () {

    it("is a function", function () {
      this.env.getUrlForResource
        .should.be.a.Function();
    });

    given(
      [ "", null, "/" ],
      [ "blog", null, "/blog" ],
      [ "blog", "http://example.com", "http://example.com/blog" ],
      [ "blog/index.html", null, "/blog/index.html" ],
      [ "blog/index.html", "http://example.com", "http://example.com/blog/index.html" ],
      [ "blog/feed.rss", null, "/blog/feed.rss" ],
      [ "blog/feed.rss", "http://example.com", "http://example.com/blog/feed.rss" ]
    ).
    it("returns the expected URL", function (outputRelativePath, baseUrl, expectedResult) {
      this.env.getUrlForResource(outputRelativePath, baseUrl)
        .should.be.eql(expectedResult);
    });

    given(
      [ "blog/index.html", null, "/blog/index" ],
      [ "blog/index.html", "http://example.com", "http://example.com/blog/index" ],
      [ "blog/default.html", null, "/blog/default" ],
      [ "blog/default.html", "http://example.com", "http://example.com/blog/default" ]
    ).
    it("returns the expected URL taking hidden extensions into account", function (outputRelativePath, baseUrl, expectedResult) {
      this.env.hiddenUrlExtensions.add(".html");

      this.env.getUrlForResource(outputRelativePath, baseUrl)
        .should.be.eql(expectedResult);
    });

    given(
      [ "blog/index.html", null, "/blog/" ],
      [ "blog/index.html", "http://example.com", "http://example.com/blog/" ],
      [ "blog/default.html", null, "/blog/default.html" ],
      [ "blog/default.html", "http://example.com", "http://example.com/blog/default.html" ]
    ).
    it("returns the expected URL taking hidden file names into account", function (outputRelativePath, baseUrl, expectedResult) {
      this.env.hiddenUrlFileNames.add("index.html");

      this.env.getUrlForResource(outputRelativePath, baseUrl)
        .should.be.eql(expectedResult);
    });

  });

  describe("#resolvePath(name, [relativePath])", function () {

    it("is a function", function () {
      this.env.resolvePath
        .should.be.a.Function();
    });

    it("throws error when argument 'name' is an empty string", function () {
      let name = "";
      (() => this.env.resolvePath(name))
        .should.throw("argument 'name' must be a non-empty string");
    });

    it("resolves path of a named sub-directory within project", function () {
      this.env.resolvePath("def")
        .should.be.eql(path.resolve(__dirname, "../fixtures/empty-project/def"));
    });

    it("resolves path from a named sub-directory within project", function () {
      this.env.resolvePath("def", "ghi/jkl")
        .should.be.eql(path.resolve(__dirname, "../fixtures/empty-project/def/ghi/jkl"));
    });

    it("trims trailing slash from argument 'relativePath'", function () {
      this.env.resolvePath("def", "ghi/jkl/")
        .should.be.eql(path.resolve(__dirname, "../fixtures/empty-project/def/ghi/jkl"));
    });

  });

  describe("#setPath(name, path)", function () {

    it("is a function", function () {
      this.env.setPath
        .should.be.a.Function();
    });

    it("throws error when argument 'name' is an empty string", function () {
      (() => this.env.setPath("", "abc"))
        .should.throw("argument 'name' must be a non-empty string");
    });

    it("throws error when argument 'path' is an empty string", function () {
      (() => this.env.setPath("content", ""))
        .should.throw("argument 'path' must be a non-empty string");
    });

    given(
      "/",
      ".",
      "/abc/def/../ghi/../..",
      process.env.HOME,
      path.join(process.env.HOME, "Documents"),
      path.join(process.env.HOME, "My Documents")
    ).
    it("throws error when resolved output path is potentially dangerous", function (dangerousOutputPath) {
      this.env.projectRootPath = "/";
      (() => this.env.setPath("output", dangerousOutputPath))
        .should.throw("Refusing to set output path that is potentially very dangerous.");
    });

    it("overrides a named path", function () {
      this.env.setPath("content", "new-content/2015");
      this.env.resolvePath("content")
        .should.be.eql(path.resolve(__dirname, "../fixtures/empty-project/new-content/2015"));
    });

    it("trims trailing slash from argument 'path'", function () {
      this.env.setPath("content", "new-content/2015/");
      this.env.resolvePath("content")
        .should.be.eql(path.resolve(__dirname, "../fixtures/empty-project/new-content/2015"));
    });

    it("returns self allowing for chained calls", function () {
      this.env.setPath("content", "new-content/2015")
        .should.be.exactly(this.env);
    });

  });

  describe("#use(pluginSetupFunction, [options])", function () {

    it("is a function", function () {
      this.env.use
        .should.be.a.Function();
    });

    given([
      [ undefined, { } ],
      [ null, { } ],
      [ { a: 42 }, { a: 42 } ]
    ]).
    it("invokes plugin setup function with expected arguments", function (options, expectedOptions) {
      let suppliedEnv, suppliedOptions;
      let fakeSetupFunction = function (env, options) {
        suppliedEnv = env;
        suppliedOptions = options;
      };

      this.env.use(fakeSetupFunction, options);

      suppliedEnv
        .should.be.exactly(this.env);
      suppliedOptions
        .should.be.an.Object();
      suppliedOptions
        .should.have.properties(expectedOptions);
    });

    it("returns self allowing for chained function calls", function () {
      let fakeSetupFunction = function (env, options) { };
      this.env.use(fakeSetupFunction)
        .should.be.exactly(this.env);
    });

  });

});


text:
import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom/server';
import serialize from 'serialize-javascript';
import Helmet from 'react-helmet';

/**
 * Wrapper component containing HTML metadata and boilerplate tags.
 * Used in server-side code only to wrap the string output of the
 * rendered route component.
 *
 * The only thing this component doesn't (and can't) include is the
 * HTML doctype declaration, which is added to the rendered output
 * by the server.js file.
 */
export default class Html extends Component {
  static propTypes = {
    assets: PropTypes.object,
    component: PropTypes.node,
    store: PropTypes.object
  };

  render() {
    const {assets, component, store} = this.props;
    const content = component ? ReactDOM.renderToString(component) : '';
    const head = Helmet.rewind();

    return (
      <html lang="en-us">
        <head>
          {head.base.toComponent()}
          {head.title.toComponent()}
          {head.meta.toComponent()}
          {head.link.toComponent()}
          {head.script.toComponent()}

          <meta name="bankrate-site-verification" content="75387a3abc9bf8cf6cc8" />
          <meta name="p:domain_verify" content="e3881474d5535ec9fcb060799b76d047"/>
          <meta name="google-site-verification" content="1DZOZwCcjvk35l-3ZclhWBnFEXzDLECREa5Buv2E37U" />
          <link rel="shortcut icon" href="/favicon.ico" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          {/* styles (will be present only in production with webpack extract text plugin) */}
          {Object.keys(assets.styles).map((style, key) =>
            <link href={assets.styles[style]} key={key} media="screen, projection"
                  rel="stylesheet" type="text/css" charSet="UTF-8"/>
          )}

          {/* (will be present only in development mode) */}
          {/* outputs a <style/> tag with all bootstrap styles + App.scss + it could be CurrentPage.scss. */}
          {/* can smoothen the initial style flash (flicker) on page load in development mode. */}
          {/* ideally one could also include here the style for the current page (Home.scss, About.scss, etc) */}
          { Object.keys(assets.styles).length === 0 ? <style dangerouslySetInnerHTML={{__html: require('../theme/bootstrap.config.js') + require('../containers/App/App.scss')._style}}/> : null }
          <script dangerouslySetInnerHTML={{__html: `!function(){var a;if(a=window.driftt=window.drift=window.driftt||[],!a.init)
            return a.invoked?void(window.console&&console.error&&console.error("Drift snippet included twice.")):
            (a.invoked=!0,a.methods=["identify","config","track","reset","debug","show","ping","page","hide","off","on"],
            a.factory=function(b){return function(){var c;return c=Array.prototype.slice.call(arguments),c.unshift(b),a.push(c),a}},
            a.methods.forEach(function(b){a[b]=a.factory(b)}),a.load=function(a){var b,c,d,e;b=3e5,e=Math.ceil(new Date/b)*b,
            d=document.createElement("script"),d.type="text/javascript",d.async=!0,d.crossorigin="anonymous",
            d.src="https://js.driftt.com/include/"+e+"/"+a+".js",c=document.getElementsByTagName("script")[0],
            c.parentNode.insertBefore(d,c)})}(),drift.SNIPPET_VERSION="0.3.1",
          drift.load("amy622ayz2ey");`}}/>
        </head>
        <body>
          <script dangerouslySetInnerHTML={{__html: `window.fbAsyncInit=function(){FB.init({appId:"1697227587263342",xfbml:!0,
            version:"v2.8"}),FB.AppEvents.logPageView()},function(e,n,t){var o,c=e.getElementsByTagName(n)[0];e.getElementById(t)||
            (o=e.createElement(n),o.id=t,o.src="//connect.facebook.net/en_US/sdk.js",c.parentNode.insertBefore(o,c))}(document,
            "script","facebook-jssdk");`}}/>
          <div id="content" dangerouslySetInnerHTML={{__html: content}}/>
          <script dangerouslySetInnerHTML={{__html: `window.__data=${serialize(store.getState())};`}} charSet="UTF-8"/>
          <script src={assets.javascript.main} charSet="UTF-8"/>
          <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5888396ac783d21a"></script>
        </body>
      </html>
    );
  }
}


text:
from mpi4py import MPI
import sys

comm = MPI.COMM_SELF.Spawn(sys.executable, args=['worker.py'], maxprocs=5)

result = comm.reduce(None, op=MPI.SUM, root=MPI.ROOT)

print("master:", result)

comm.Disconnect()


text:
import { LabelElement } from '../../libs/flow.module.js';
import { BaseNode } from '../core/BaseNode.js';
import { Vector3 } from '../../three.module.js'
import { MathNode, UniformNode } from 'three-nodes/Nodes.js';

const DEFAULT_VALUE = new UniformNode( new Vector3() );

export class NormalizeEditor extends BaseNode {

	constructor() {

		const node = new MathNode( MathNode.NORMALIZE, DEFAULT_VALUE );

		super( 'Normalize', 3, node, 175 );

		const input = new LabelElement( 'A' ).setInput( 3 );

		input.onConnect( () => {

			node.aNode = input.getLinkedObject() || DEFAULT_VALUE;

		} );

		this.add( input );

	}

}


text:
var path = require('path');
var gulp = require('gulp');
var args = require('yargs').argv;
var colors = require('colors');
var execa = require('execa');
var pAll = require('p-all');
var os = require('os');
var fs = require('fs');

const mappings = require('./api-specs.json');
const defaultSpecRoot = "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/current";

gulp.task('default', function() {
    console.log("Usage: gulp codegen " +
        "[--spec-root <swagger specs root>] " +
        "[--projects <project names>] " +
        "[--autorest <autorest info>] " +
        "[--autorest-java <autorest.java info>] " +
        "[--debug] " +
        "[--parallel <number>] " +
        "[--autorest-args <AutoRest arguments>]\n");

    console.log("--spec-root");
    console.log(`\tRoot location of Swagger API specs, default value is "${defaultSpecRoot}"`);

    console.log("--projects");
    console.log("\tComma separated projects to regenerate, default is all. List of available project names:");
    Object.keys(mappings).forEach(function(i) {
        console.log('\t' + i.magenta);
    });

    console.log("--autorest");
    console.log("\tThe version of AutoRest. E.g. 2.0.9, or the location of AutoRest repo, e.g. E:\\repo\\autorest");

    console.log("--autorest-java");
    console.log("\tPath to an autorest.java generator to pass as a --use argument to AutoRest.");
    console.log("\tUsually you'll only need to provide this and not a --autorest argument in order to work on Java code generation.");
    console.log("\tSee https://github.com/Azure/autorest/blob/master/docs/developer/autorest-extension.md");

    console.log("--debug");
    console.log("\tFlag that allows you to attach a debugger to the autorest.java generator.");

    console.log("--parallel");
    console.log("\tSpecifies the maximum number of projects to generate in parallel.");
    console.log("\tDefaults to the number of logical CPUs on the system. (On this system, " + os.cpus().length + ")");

    console.log("--autorest-args");
    console.log("\tPasses additional argument to AutoRest generator");
});

const maxParallelism = parseInt(args['parallel'], 10) || os.cpus().length;
var specRoot = args['spec-root'] || defaultSpecRoot;
var projects = args['projects'];
var autoRestVersion = 'latest'; // default
if (args['autorest'] !== undefined) {
    autoRestVersion = args['autorest'];
}
var debug = args['debug'];
var autoRestArgs = args['autorest-args'] || '';
var autoRestExe;

gulp.task('codegen', function(cb) {
    if (autoRestVersion.match(/[0-9]+\.[0-9]+\.[0-9]+.*/) ||
        autoRestVersion == 'latest') {
            autoRestExe = 'autorest ---version=' + autoRestVersion;
            handleInput(projects, cb);
    } else {
        autoRestExe = "node " + path.join(autoRestVersion, "src/autorest-core/dist/app.js");
        handleInput(projects, cb);
    }
});

var handleInput = function(projects, cb) {
    console.info(`Generating up to ${maxParallelism} projects in parallel..`);
    if (projects === undefined) {
        const actions = Object.keys(mappings).map(proj => {
            return () => codegen(proj, cb);
        });
        pAll(actions, { concurrency: maxParallelism });
    } else {
        const actions = projects.split(",").map(proj => {
            return () => {
                proj = proj.replace(/\ /g, '');
                if (mappings[proj] === undefined) {
                    console.error('Invalid project name "' + proj + '"!');
                    process.exit(1);
                }
                return codegen(proj, cb);
            }
        });
        pAll(actions, { maxParallelism });
    }
}

var codegen = function(project, cb) {
    if (!args['preserve']) {
        const sourcesToDelete = path.join(
            mappings[project].dir,
            '/src/main/java/',
            mappings[project].package.replace(/\./g, '/'));

        deleteFolderRecursive(sourcesToDelete);
    }

    console.log('Generating "' + project + '" from spec file ' + specRoot + '/' + mappings[project].source);
    var generator = '--fluent';
    if (mappings[project].fluent !== null && mappings[project].fluent === false) {
        generator = '';
    }

    const generatorPath = args['autorest-java']
        ? `--use=${path.resolve(args['autorest-java'])} `
        : '';

    const regenManager = args['regenerate-manager'] ? ' --regenerate-manager=true ' : '';

    const outDir = path.resolve(mappings[project].dir);
    // path.join won't work if specRoot is a URL
    cmd = autoRestExe + ' ' + specRoot + "/" + mappings[project].source +
                        ' --java ' +
                        ' --azure-arm ' +
                        generator +
                        ` --namespace=${mappings[project].package} ` +
                        ` --output-folder=${outDir} ` +
                        ` --license-header=MICROSOFT_MIT_NO_CODEGEN ` +
                        generatorPath +
                        regenManager +
                        autoRestArgs;

    if (mappings[project].args !== undefined) {
        cmd += ' ' + mappings[project].args;
    }

    if (debug) {
        cmd += ' --java.debugger';
    }

    console.log('Command: ' + cmd);
    return execa(cmd, [], { shell: true, stdio: "inherit" });
};

var deleteFolderRecursive = function(path) {
    var header = "Code generated by Microsoft (R) AutoRest Code Generator";
    if(fs.existsSync(path)) {
        fs.readdirSync(path).forEach(function(file, index) {
            var curPath = path + "/" + file;
            if(fs.lstatSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath);
            } else { // delete file
                var content = fs.readFileSync(curPath).toString('utf8');
                if (content.indexOf(header) > -1) {
                    fs.unlinkSync(curPath);
                }
            }
        });
    }
};


text:
from rest_framework import serializers
from news.models import News

class NewsSerializer(serializers.ModelSerializer):

    class Meta:
        model = News
        fields = ('id', 'name', 'description', 'date_upl', 'is_party', 'publishing', 'files')
        read_only_fields = ('id', 'date_upl')
        depth = 1


text:
package com.b2international.collections.ints;

import com.b2international.collections.PrimitiveList;

/**
 * @since 4.7
 */
public interface IntList extends PrimitiveList, IntCollection {

	int get(int index);

	@Override
	IntListIterator listIterator();

	@Override
	IntListIterator listIterator(int startIndex);

	int set(int index, int value);

	int removeInt(int index);
}


text:
* Rework AlfFile that loads its operand in memory.

* RENAME: add prefix, suffix and lambda renaming

        (rename :suppliers, [:name, :city], :prefix => "supplier_")
        (rename :suppliers, [:name, :city], :suffix => "_sup")
        (rename :suppliers, [:name, :city], lambda{|name| name.upcase})

* WRAP: provide a multi-wrapping ability?

        (wrap (wrap :supplies, [:a, :b], :x), [:x, :c], :y)
         => (wrap :supplies, :x => [:a, :b], :y => [:x, :c])

    But this would only work with Ruby 1.9 as the hash order would be important
    as such

* GROUP: provide a multi-grouping ability?

    Similar to wrap, with same limitation.

* Add PIVOT and UNPIVOT operators

* Find a way to complete the description of Quota...


text:
<?php

namespace JMS\DiExtraBundle\Tests\Metadata;

use JMS\DiExtraBundle\Metadata\ClassMetadata;

class ClassMetadataTest extends \PHPUnit_Framework_TestCase
{
    public function testSerializeUnserialize()
    {
        $classMetadata = new ClassMetadata('JMS\DiExtraBundle\Tests\Fixture\LoginController');
        $classMetadata->arguments = array('foo', 'bar');
        $classMetadata->abstract = true;
        $classMetadata->public = false;
        $classMetadata->id = 'foo';

        $this->assertEquals($classMetadata, unserialize(serialize($classMetadata)));
    }
}


text:
using System;
using System.Collections.Generic;
using Dauber.Core.Contracts;

namespace Dauber.Azure.DocumentDb.Test
{
    public class Driver : ViewModel
    {
        public Guid FleetId { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string PhoneNumber { get; set; }
        public DriversLicense DriversLicense { get; set; }
        public bool IsOnCall { get; set; }
        public Guid? MostRecentJobLoadId { get; set; }
        public string ImageUrl { get; set; } = "https://fleetimages.azureedge.net/images/placeholder/driver.png";
        public string ProfileImageUrl { get; set; }
        public List<SimpleTag> Tags { get; set; }
        public bool IsActive { get; set; } = true;
        //public Guid? StartOfDayTruckId { get; set; }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Beco</tipo><logradouro>Um</logradouro><bairro>Parque Florido</bairro><cidade>Gravataí</cidade><uf>RS</uf><cep>94075314</cep></feed>


text:
using MS.Internal;
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Windows;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Markup;
using MS.Internal.PresentationCore;

namespace System.Windows.Media
{
    /// <summary>
    /// GeneralTransform class provides services to transform points and rects
    /// </summary>
    [Localizability(LocalizationCategory.None, Readability = Readability.Unreadable)]
    public abstract partial class GeneralTransform : Animatable
    {
        /// <summary>
        /// Transform a point
        /// </summary>
        /// <param name="inPoint">Input point</param>
        /// <param name="result">Output point</param>
        /// <returns>True if the point was transformed successfuly, false otherwise</returns>
        public abstract bool TryTransform(Point inPoint, out Point result);

        /// <summary>
        /// Transform a point
        ///
        /// If the transformation does not succeed, this will throw an InvalidOperationException.
        /// If you don't want to try/catch, call TryTransform instead and check the boolean it
        /// returns.
        ///
        /// Note that this method will always succeed when called on a subclass of Transform
        /// </summary>
        /// <param name="point">Input point</param>
        /// <returns>The transformed point</returns>
        public Point Transform(Point point)
        {
            Point transformedPoint;

            if (!TryTransform(point, out transformedPoint))
            {
                throw new InvalidOperationException(SR.Get(SRID.GeneralTransform_TransformFailed, null));
            }

            return transformedPoint;
        }

        /// <summary>
        /// Transforms the bounding box to the smallest axis aligned bounding box
        /// that contains all the points in the original bounding box
        /// </summary>
        /// <param name="rect">Bounding box</param>
        /// <returns>The transformed bounding box</returns>
        public abstract Rect TransformBounds(Rect rect);

        /// <summary>
        /// Returns the inverse transform if it has an inverse, null otherwise
        /// </summary>
        public abstract GeneralTransform Inverse { get; }

        /// <summary>
        /// Returns a best effort affine transform
        /// </summary>
        internal virtual Transform AffineTransform
        {
            [FriendAccessAllowed] // Built into Core, also used by Framework.
            get { return null; }
        }
    }
}