text:
package org.elasticsearch.client.transport;

import org.elasticsearch.Version;
import org.elasticsearch.action.GenericAction;
import org.elasticsearch.action.admin.cluster.node.liveness.LivenessResponse;
import org.elasticsearch.action.admin.cluster.node.liveness.TransportLivenessAction;
import org.elasticsearch.action.admin.cluster.state.ClusterStateAction;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.client.AbstractClientHeadersTestCase;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.env.Environment;
import org.elasticsearch.plugins.NetworkPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.plugins.PluginsService;
import org.elasticsearch.test.transport.MockTransportService;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.MockTransportClient;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.TransportException;
import org.elasticsearch.transport.TransportInterceptor;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.transport.TransportRequestHandler;
import org.elasticsearch.transport.TransportRequestOptions;
import org.elasticsearch.transport.TransportResponse;
import org.elasticsearch.transport.TransportResponseHandler;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.Matchers.is;

public class TransportClientHeadersTests extends AbstractClientHeadersTestCase {

    private MockTransportService transportService;

    @Override
    public void tearDown() throws Exception {
        try {
            // stop this first before we bubble up since
            // transportService uses the threadpool that super.tearDown will close
            transportService.stop();
            transportService.close();
        } finally {
            super.tearDown();
        }

    }

    @Override
    protected Client buildClient(Settings headersSettings, GenericAction[] testedActions) {
        transportService = MockTransportService.createNewService(Settings.EMPTY, Version.CURRENT, threadPool, null);
        transportService.start();
        transportService.acceptIncomingRequests();
        TransportClient client = new MockTransportClient(Settings.builder()
                .put("client.transport.sniff", false)
                .put("cluster.name", "cluster1")
                .put("node.name", "transport_client_" + this.getTestName())
                .put(headersSettings)
                .build(), InternalTransportServiceInterceptor.TestPlugin.class);
        InternalTransportServiceInterceptor.TestPlugin plugin = client.injector.getInstance(PluginsService.class)
            .filterPlugins(InternalTransportServiceInterceptor.TestPlugin.class).stream().findFirst().get();
        plugin.instance.threadPool = client.threadPool();
        plugin.instance.address = transportService.boundAddress().publishAddress();
        client.addTransportAddress(transportService.boundAddress().publishAddress());
        return client;
    }

    public void testWithSniffing() throws Exception {
        try (TransportClient client = new MockTransportClient(
                Settings.builder()
                        .put("client.transport.sniff", true)
                        .put("cluster.name", "cluster1")
                        .put("node.name", "transport_client_" + this.getTestName() + "_1")
                        .put("client.transport.nodes_sampler_interval", "1s")
                        .put(HEADER_SETTINGS)
                        .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()).build(),
                InternalTransportServiceInterceptor.TestPlugin.class)) {
            InternalTransportServiceInterceptor.TestPlugin plugin = client.injector.getInstance(PluginsService.class)
                .filterPlugins(InternalTransportServiceInterceptor.TestPlugin.class).stream().findFirst().get();
            plugin.instance.threadPool = client.threadPool();
            plugin.instance.address = transportService.boundAddress().publishAddress();
            client.addTransportAddress(transportService.boundAddress().publishAddress());

            if (!plugin.instance.clusterStateLatch.await(5, TimeUnit.SECONDS)) {
                fail("takes way too long to get the cluster state");
            }

            assertThat(client.connectedNodes().size(), is(1));
            assertThat(client.connectedNodes().get(0).getAddress(), is(transportService.boundAddress().publishAddress()));
        }
    }

    public static class InternalTransportServiceInterceptor implements TransportInterceptor {

        ThreadPool threadPool;
        TransportAddress address;

        public static class TestPlugin extends Plugin implements NetworkPlugin {
            private InternalTransportServiceInterceptor instance = new InternalTransportServiceInterceptor();

            @Override
            public List<TransportInterceptor> getTransportInterceptors(NamedWriteableRegistry namedWriteableRegistry) {
                return Collections.singletonList(new TransportInterceptor() {
                    @Override
                    public <T extends TransportRequest> TransportRequestHandler<T> interceptHandler(String action, String executor,
                                                                                TransportRequestHandler<T> actualHandler) {
                        return instance.interceptHandler(action, executor, actualHandler);
                    }

                    @Override
                    public AsyncSender interceptSender(AsyncSender sender) {
                        return instance.interceptSender(sender);
                    }
                });
            }
        }

        final CountDownLatch clusterStateLatch = new CountDownLatch(1);

        @Override
        public AsyncSender interceptSender(AsyncSender sender) {
            return new AsyncSender() {
                @Override
                public <T extends TransportResponse> void sendRequest(Transport.Connection connection, String action,
                                                                      TransportRequest request,
                                                                      TransportRequestOptions options,
                                                                      TransportResponseHandler<T> handler) {
                    if (TransportLivenessAction.NAME.equals(action)) {
                        assertHeaders(threadPool);
                        ((TransportResponseHandler<LivenessResponse>) handler).handleResponse(
                            new LivenessResponse(new ClusterName("cluster1"), connection.getNode()));
                        return;
                    }
                    if (ClusterStateAction.NAME.equals(action)) {
                        assertHeaders(threadPool);
                        ClusterName cluster1 = new ClusterName("cluster1");
                        ClusterState.Builder builder = ClusterState.builder(cluster1);
                        //the sniffer detects only data nodes
                        builder.nodes(DiscoveryNodes.builder().add(new DiscoveryNode("node_id", address, Collections.emptyMap(),
                                Collections.singleton(DiscoveryNode.Role.DATA), Version.CURRENT)));
                        ((TransportResponseHandler<ClusterStateResponse>) handler)
                                .handleResponse(new ClusterStateResponse(cluster1, builder.build()));
                        clusterStateLatch.countDown();
                        return;
                    }

                    handler.handleException(new TransportException("", new InternalException(action)));
                }
            };
        }
    }
}


text:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace System.Data.SqlClient.ManualTesting.Tests
{
    public class CopySomeFromDataTableAsync
    {
        public static void Test(string srcConstr, string dstConstr, string dstTable)
        {
            // Use this semaphore to ensure that results are written to the log in the correct order
            SemaphoreSlim outputSemaphore = new SemaphoreSlim(0, 1);

            Task t = TestAsync(srcConstr, dstConstr, dstTable, outputSemaphore);
            outputSemaphore.Release();
            t.Wait();
            Assert.True(t.IsCompleted, "Task did not complete! Status: " + t.Status);
        }

        private static async Task TestAsync(string srcConstr, string dstConstr, string dstTable, SemaphoreSlim outputSemaphore)
        {
            DataSet dataset;
            SqlDataAdapter adapter;
            DataTable datatable;

            using (SqlConnection dstConn = new SqlConnection(dstConstr))
            using (SqlCommand dstCmd = dstConn.CreateCommand())
            {
                dstConn.Open();

                try
                {
                    Helpers.Execute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10), col4 datetime)");
                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
                    using (SqlCommand srcCmd = new SqlCommand("select * from employees", srcConn))
                    {
                        srcConn.Open();

                        dataset = new DataSet("MyDataSet");
                        adapter = new SqlDataAdapter(srcCmd);
                        adapter.Fill(dataset);
                        datatable = dataset.Tables[0];

                        datatable.Rows[0].BeginEdit();
                        datatable.Rows[0][0] = 333;
                        datatable.Rows[0].EndEdit();

                        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
                        {
                            bulkcopy.DestinationTableName = dstTable;
                            bulkcopy.BatchSize = 7;

                            SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;

                            ColumnMappings.Add(0, "col1");
                            ColumnMappings.Add(1, "col2");
                            ColumnMappings.Add(2, "col3");
                            bulkcopy.WriteToServer(datatable, DataRowState.Unchanged);
                            datatable.Rows.GetEnumerator().Reset();
                            await bulkcopy.WriteToServerAsync(datatable, DataRowState.Modified);
                            datatable.Rows.GetEnumerator().Reset();
                            await bulkcopy.WriteToServerAsync(datatable, DataRowState.Deleted);
                            bulkcopy.Close();
                        }

                        await outputSemaphore.WaitAsync();
                        Helpers.VerifyResults(dstConn, dstTable, 4, 18);
                    }
                }
                finally
                {
                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.ignaciotcrespo.mrpolite;

/**
 * Created by crespo on 2/27/17.
 */
abstract class CollectionOf<T, V> extends PoliteDesireForClass<T, V> {
    final int size;

    CollectionOf(int size, Class<T> clazz) {
        super(clazz);
        this.size = size;
    }

}


text:
import { Component, Input, ViewChild, ViewContainerRef, ComponentRef } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { TranslateService } from '@ngx-translate/core';

import { BaseComponent } from 'app/base.component';
import { SlideManager } from 'app/slides/services/slide-manager.service';
import { BaseSlideComponent } from 'app/slides/base-slide-component';
import { SlideData } from 'app/core/core-services/projector-data.service';
import { ProjectorElement } from 'app/shared/models/core/projector';
import { ViewProjector } from 'app/site/projector/models/view-projector';

function hasError(obj: object): obj is { error: string } {
    return (<{ error: string }>obj).error !== undefined;
}
/**
 * Container for one slide. Cares about the position (scale, scroll) in the projector,
 * and loading of slides.
 */
@Component({
    selector: 'os-slide-container',
    templateUrl: './slide-container.component.html',
    styleUrls: ['./slide-container.component.scss']
})
export class SlideContainerComponent extends BaseComponent {
    private previousSlideName: string;

    @ViewChild('slide', { read: ViewContainerRef })
    private slide: ViewContainerRef;
    private slideRef: ComponentRef<BaseSlideComponent<object>>;

    /**
     * The data for this slide. Will be accessed below.
     */
    private _slideData: SlideData<object>;

    @Input()
    public set slideData(slideData: SlideData<object>) {
        // If there is no ata or an error, clear and exit.
        if (!slideData || hasError(slideData) || (slideData.data && hasError(slideData.data))) {
            // clear slide container:
            if (this.slide) {
                this.slide.clear();
            }

            let error;
            if (hasError(slideData)) {
                error = slideData.error;
            } else if (slideData.data && hasError(slideData.data)) {
                error = slideData.data.error;
            }

            if (error) {
                console.log(error);
            }
            return;
        }

        this._slideData = slideData;
        if (this.previousSlideName !== slideData.element.name) {
            this.slideChanged(slideData.element);
            this.previousSlideName = slideData.element.name;
        }
        this.setDataForComponent();
    }

    public get slideData(): SlideData<object> {
        return this._slideData;
    }

    private _projector: ViewProjector;

    /**
     * Variable, if the projector header is enabled.
     */
    @Input()
    public set projector(projector: ViewProjector) {
        this._projector = projector;
        this.setProjectorForComponent();
        this.updateScroll();
    }

    public get projector(): ViewProjector {
        return this._projector;
    }

    /**
     * The current projector scroll.
     */
    private _scroll: number;

    /**
     * Updates the slideStyle, when the scroll changes.
     */
    @Input()
    public set scroll(value: number) {
        this._scroll = value;
        this.updateScroll();
    }

    public get scroll(): number {
        return this._scroll;
    }

    /**
     * Update the slideStyle, when the scale changes.
     */
    @Input()
    public set scale(value: number) {
        if (this.slideOptions.scaleable) {
            value *= 10;
            value += 100;
            this.slideStyle['font-size'] = `${value}%`;
        } else {
            this.slideStyle['font-size'] = '100%';
        }
    }

    /**
     * The current slideoptions.
     */
    public slideOptions: { scaleable: boolean; scrollable: boolean } = { scaleable: false, scrollable: false };

    /**
     * Styles for scaling and scrolling.
     */
    public slideStyle: { 'font-size': string; 'margin-top': string } = {
        'font-size': '100%',
        'margin-top': '50px'
    };

    public constructor(titleService: Title, translate: TranslateService, private slideManager: SlideManager) {
        super(titleService, translate);
    }

    /**
     * Updates the 'margin-top' attribute in the slide styles.
     */
    private updateScroll(): void {
        if (this.slideOptions.scrollable) {
            let value = this.scroll;
            value *= -100;
            if (this.projector.show_header_footer) {
                value += 50; // Default offset for the header
            }
            this.slideStyle['margin-top'] = `${value}px`;
        } else {
            this.slideStyle['margin-top'] = '0px';
        }
    }

    /**
     * Loads the slides via the SlideManager. Creates the slide components and provide the slide data to it.
     *
     * @param slideName The slide to load.
     */
    private slideChanged(element: ProjectorElement): void {
        const options = this.slideManager.getSlideConfiguration(element.name);
        if (typeof options.scaleable === 'boolean') {
            this.slideOptions.scaleable = options.scaleable;
        } else {
            this.slideOptions.scaleable = options.scaleable(element);
        }
        if (typeof options.scrollable === 'boolean') {
            this.slideOptions.scrollable = options.scrollable;
        } else {
            this.slideOptions.scrollable = options.scrollable(element);
        }
        this.slideManager.getSlideFactory(element.name).then(slideFactory => {
            this.slide.clear();
            this.slideRef = this.slide.createComponent(slideFactory);
            this.setDataForComponent();
            this.setProjectorForComponent();
        });
    }

    /**
     * "injects" the slide data into the slide component.
     */
    private setDataForComponent(): void {
        if (this.slideRef && this.slideRef.instance) {
            this.slideRef.instance.data = this.slideData;
        }
    }

    /**
     * "injects" the projector into the slide component.
     */
    private setProjectorForComponent(): void {
        if (this.slideRef && this.slideRef.instance) {
            this.slideRef.instance.projector = this.projector;
        }
    }
}


text:
layout: single
title: "Lifecycle and Cascade of WeChat Social Messaging Groups"
modified: 2017-01-26T09:53:00
comments: true
categories:
  - group dynamics
tags:
  - wechat
excerpt: ""
author: "王成军"
---

{% include toc title="Table" icon="file-text" %}

Jiezhong Qiu于2016年在WWW会议上发表了题为 The Lifecycle and Cascade of WeChat Social Messaging Groups的论文。[^qiu]

[^qiu]: Qiu, J., Li, Y., Tang, J., Lu, Z., Ye, H., & Chen, B., et al. (2016). The Lifecycle and Cascade of WeChat Social Messaging Groups. International Conference on World Wide Web (pp.311-320). International World Wide Web Conferences Steering Committee.

wechat是一种social messaging groups,基于手机的app应用,虽然市场占有率还没有whatsapp多,但是增长趋势非常惊人。

微信的数据一直以来比较难获得,清华大学和香港科技大学杨强团队、康奈尔大学与微信数据部门合作。

long-term and short-term groups are inherently distinct.

![long-short-group](http://oaf2qt3yk.bkt.clouddn.com/d2259f67bda9f10a1061a0196a0e4218.png)

"Beside studying the friendship structure, we also discuss the group formation processes, namely by investigating the group membership invitation cascading tree structure. We start with defining the group cascade tree below."

**Wiener index**, is useful for disambiguating between shallow, broadcast-like diffusion and the deep branching structures.

Wiener index is defined by the average distance between any two nodes in the cascade tree. For example, the cascade trees in Fig- ure 4(a) and Figure 4(b) have Wiener indexes of 3.99 and 1.83, respectively.

![graphical-example-wechat](http://oaf2qt3yk.bkt.clouddn.com/6a1232e626c94bba46428bbcb700d5b6.png)

For instance, the **big dotted circle** in Figure 6 encompasses all the current members within a group.

There are two essential steps behind each invitation:
- 1) a member in a group become active (denoted by blue in Figure 6), and
- 2) the active member selects his/her friends (denoted by red in Figure 6) into the group chat.

**Invitation Interval** is defined as the time inter- val between any two consecutive invitations from a group member.

Additionally, First Invitation Latency is defined as the interval be- tween the timestamp at which a user joins a group (invited by some existing member) and the timestamp when he/she, for the first time, invites another friend to the same group.

we develop a membership cascade model and demonstrate the effectiveness by achieving AUC of 95.31% in predicting inviter, and an AUC of 98.66% in predicting invitee.

# 参考文献


text:
package com.github.suzukihr.smoothcolorpicker;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.widget.LinearLayout;

public class RectColorPickerView extends LinearLayout {

    private SvView mSvView;
    private SvOverlayView mSvOverlayView;
    private RectHueOverlayView mRectHueOverlayView;
    private ColorPickerListener mListener;

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

    private void init() {
        inflate(getContext(), R.layout.rect_color_picker_view, this);
        setOrientation(HORIZONTAL);

        mSvView = (SvView) findViewById(R.id.svView);
        mRectHueOverlayView = (RectHueOverlayView) findViewById(R.id.rectHueOverlayView);
        mSvOverlayView = (SvOverlayView) findViewById(R.id.svOverlayView);

        mRectHueOverlayView.setListener(new HueValueListener() {
            @Override
            public void onHueChanged(float hue, boolean fromUser) {
                mSvView.setHue(hue);
                if (mListener != null) {
                    mListener.onColorChanged(getColor(), getHsv(), fromUser);
                }
            }

            @Override
            public void onStartTrackingTouch() {
                if (mListener != null) {
                    mListener.onStartTrackingTouch();
                }
            }

            @Override
            public void onStopTrackingTouch() {
                if (mListener != null) {
                    mListener.onStopTrackingTouch(getColor(), getHsv());
                }
            }
        });

        mSvOverlayView.setListener(new SvOverlayView.SvValueListener() {
            @Override
            public void onSvChanged(float s, float v, boolean fromUser) {
                if (mListener != null) {
                    mListener.onColorChanged(getColor(), getHsv(), fromUser);
                }
            }

            @Override
            public void onStartTrackingTouch() {
                if (mListener != null) {
                    mListener.onStartTrackingTouch();
                }
            }

            @Override
            public void onStopTrackingTouch() {
                if (mListener != null) {
                    mListener.onStopTrackingTouch(getColor(), getHsv());
                }
            }
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mListener = null;
    }

    public void setColor(int color) {
        float[] hsv = new float[3];
        Color.colorToHSV(color, hsv);
        setHsv(hsv);
    }

    public void setHsv(float[] hsv) {
        mRectHueOverlayView.setHue(hsv[0]);
        mSvView.setHue(hsv[0]);
        mSvOverlayView.setSv(hsv[1], hsv[2]);
    }

    public int getColor() {
        return Color.HSVToColor(getHsv());
    }

    public float[] getHsv() {
        float[] hsv = new float[3];
        hsv[0] = mRectHueOverlayView.getHue();
        hsv[1] = mSvOverlayView.getSaturation();
        hsv[2] = mSvOverlayView.getValue();
        return hsv;
    }

    public void setListener(ColorPickerListener listener) {
        mListener = listener;
    }
}


text:
<?php

class BasicTest extends phpunit_framework_testcase
{
    public function testBuild()
    {
        $GLOBALS['phpunit'] = $this;
        $GLOBALS['builded'] = false;
        $bar = [new Stdclass];
        $build = new crodas\Build(__DIR__);
        $build->build1([__FILE__, __DIR__], $bar);
        $this->assertTrue($GLOBALS['builded']);
        $build->save();
    }

    /**
     *  @dependsOn testBuild
     */
    public function testRebuildDontBuild()
    {
        $GLOBALS['phpunit'] = $this;
        $GLOBALS['builded'] = false;
        $bar = [new Stdclass];
        $build = new crodas\Build(__DIR__);
        $this->assertTrue(is_file($build->build1([__FILE__, __DIR__], $bar)));
        $this->assertFalse($GLOBALS['builded']);
        $build->save();
    }

    /**
     *  @dependsOn testRebuilDontBuild
     */
    public function testRebuildBuildArgs()
    {
        $GLOBALS['phpunit'] = $this;
        $GLOBALS['builded'] = false;
        $bar = [new Stdclass, 1];
        $build = new crodas\Build(__DIR__);
        $this->assertTrue(is_file($build->build1([__FILE__, __DIR__], $bar)));
        $this->assertTrue($GLOBALS['builded']);
        $build->save();
    }

    /**
     *  @dependsOn testRebuilBuildArgs
     */
    public function testRebuildDonotBuildArgs()
    {
        $GLOBALS['phpunit'] = $this;
        $GLOBALS['builded'] = false;
        $bar = [new Stdclass, 1];
        $build = new crodas\Build(__DIR__);
        $this->assertTrue(is_file($build->build1([__FILE__, __DIR__], $bar)));
        $this->assertFalse($GLOBALS['builded']);
        $build->save();
    }

    protected function touch($file)
    {
        touch($file, filemtime($file) + 5);
    }

    /**
     *  @dependsOn testRebuildDontBuild
     */
    public function testReBuildRebuild()
    {
        $GLOBALS['phpunit'] = $this;
        $GLOBALS['builded'] = false;
        $this->touch(__DIR__ . '/tasks/one.php');
        $bar = [new Stdclass];
        $build = new crodas\Build(__DIR__);
        $this->assertTrue(is_file($build->build1([__FILE__, __DIR__], $bar)));
        $this->assertTrue($GLOBALS['builded']);
        $build->save();
    }

    /**
     *  @dependsOn testRebuildRebuild
     */
    public function testProductionModeDontBuild()
    {
        $GLOBALS['phpunit'] = $this;
        $GLOBALS['builded'] = false;
        $this->touch(__DIR__ . '/tasks/one.php');
        crodas\Build::productionMode();
        $bar = [new Stdclass];
        $build = new crodas\Build(__DIR__);
        $file  = $build->build1([__FILE__, __DIR__], $bar);
        $this->assertTrue(is_file($file));
        $this->assertFalse($GLOBALS['builded']);

        unlink($file);
        $this->assertFalse(is_file($file));

        $build = new crodas\Build(__DIR__);
        $bar = [new Stdclass];
        $file2 = $build->build1([__FILE__, __DIR__], $bar);
        $this->assertTrue(is_file($file2));
        $this->assertEquals($file, $file2);
        $this->assertTrue($GLOBALS['builded']);
    }
}


text:
package guitests;

import guitests.guihandles.TaskCardHandle;
import org.junit.Test;

import seedu.manager.commons.exceptions.IllegalValueException;
import seedu.manager.logic.commands.EditCommand;
import seedu.manager.model.task.Desc;
import seedu.manager.model.task.TaskProperty;
import seedu.manager.model.task.Venue;
import seedu.manager.model.task.Task.TaskProperties;
import seedu.manager.testutil.TestTask;
import seedu.manager.testutil.TestUtil;

import static org.junit.Assert.assertTrue;

import java.util.HashMap;
import java.util.Optional;

// @@author A0147924X
public class EditCommandTest extends TaskManagerGuiTest {
    @Test
    public void edit() throws IllegalValueException {
        TestTask[] currentList = td.getTypicalTasks();
        TestUtil.sortListByTime(currentList);

        int indexToEdit = 2;
        TestTask taskToEdit = currentList[indexToEdit - 1];
        TestTask editedTask = editTaskWithProperty(taskToEdit, TaskProperties.DESC, new Desc("Dinner with Guinevere"));
        currentList = assertEditSuccess("edit %1$s Dinner with Guinevere", indexToEdit, editedTask, currentList);

        indexToEdit = 3;
        taskToEdit = currentList[indexToEdit - 1];
        TestTask editedTask1 = editTaskWithProperty(taskToEdit, TaskProperties.VENUE, new Venue("Avalon"));
        currentList = assertEditSuccess("edit %1$s venue Avalon", indexToEdit, editedTask1, currentList);

        // invalid index
        commandBox.runCommand("edit " + (currentList.length + 1) + " Some Description");
        assertResultMessage("The task index provided is invalid");
    }

    /**
     * Edits a task to change a certain property
     * @param taskToEdit The task which should be edited
     * @param property The property of the task to edit
     * @param value The new value for this property
     * @return Edited task
     */
    private TestTask editTaskWithProperty(TestTask taskToEdit, TaskProperties property, TaskProperty value) {
    	HashMap<TaskProperties, Optional<TaskProperty>> newProps =
                taskToEdit.getProperties();

        newProps.put(property, Optional.of(value));

        return new TestTask(newProps);
    }

    /**
     * Asserts that the edit command worked
     * @param editCommand A string representing the command to run
     * @param indexToEdit The index of the task to be edited
     * @param editedTask The edited task Current task list to check panel list against
     * @param currentList Current task list to check panel list against
     * @return The new list of tasks
     */
    private TestTask[] assertEditSuccess(String editCommand, int indexToEdit,
    							   TestTask editedTask, TestTask... currentList) {
        commandBox.runCommand(String.format(editCommand, indexToEdit));

        TaskCardHandle editedCard = taskListPanel.navigateToTask(editedTask.getDesc().get().getValue());
        assertMatching(editedTask, editedCard);

        TestTask[] expectedList = TestUtil.removeTaskFromList(currentList, indexToEdit);
        expectedList = TestUtil.addTasksToListSortedByTime(expectedList, editedTask);
        assertTrue(taskListPanel.isListMatching(expectedList));

        assertResultMessage(String.format(EditCommand.MESSAGE_SUCCESS, editedTask.getAsPrettyText()));

        return expectedList;
    }
}


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

package com.google.api.ads.adwords.axis.v201601.cm;

public class MediaErrorReason implements java.io.Serializable {
    private java.lang.String _value_;
    private static java.util.HashMap _table_ = new java.util.HashMap();

    // Constructor
    protected MediaErrorReason(java.lang.String value) {
        _value_ = value;
        _table_.put(_value_,this);
    }

    public static final java.lang.String _CANNOT_ADD_STANDARD_ICON = "CANNOT_ADD_STANDARD_ICON";
    public static final java.lang.String _CANNOT_SELECT_STANDARD_ICON_WITH_OTHER_TYPES = "CANNOT_SELECT_STANDARD_ICON_WITH_OTHER_TYPES";
    public static final java.lang.String _DUPLICATE_MEDIA = "DUPLICATE_MEDIA";
    public static final java.lang.String _EMPTY_FIELD = "EMPTY_FIELD";
    public static final java.lang.String _ENTITY_REFERENCED_IN_MULTIPLE_OPS = "ENTITY_REFERENCED_IN_MULTIPLE_OPS";
    public static final java.lang.String _FIELD_NOT_SUPPORTED_FOR_MEDIA_SUB_TYPE = "FIELD_NOT_SUPPORTED_FOR_MEDIA_SUB_TYPE";
    public static final java.lang.String _INVALID_MEDIA_ID = "INVALID_MEDIA_ID";
    public static final java.lang.String _INVALID_MEDIA_SUB_TYPE = "INVALID_MEDIA_SUB_TYPE";
    public static final java.lang.String _INVALID_MEDIA_TYPE = "INVALID_MEDIA_TYPE";
    public static final java.lang.String _INVALID_REFERENCE_ID = "INVALID_REFERENCE_ID";
    public static final java.lang.String _INVALID_YOU_TUBE_ID = "INVALID_YOU_TUBE_ID";
    public static final java.lang.String _MEDIA_FAILED_TRANSCODING = "MEDIA_FAILED_TRANSCODING";
    public static final java.lang.String _MEDIA_NOT_TRANSCODED = "MEDIA_NOT_TRANSCODED";
    public static final java.lang.String _MEDIA_TYPE_DOES_NOT_MATCH_OBJECT_TYPE = "MEDIA_TYPE_DOES_NOT_MATCH_OBJECT_TYPE";
    public static final java.lang.String _NO_FIELDS_SPECIFIED = "NO_FIELDS_SPECIFIED";
    public static final java.lang.String _NULL_REFERENCE_ID_AND_MEDIA_ID = "NULL_REFERENCE_ID_AND_MEDIA_ID";
    public static final java.lang.String _TOO_LONG = "TOO_LONG";
    public static final java.lang.String _UNSUPPORTED_OPERATION = "UNSUPPORTED_OPERATION";
    public static final java.lang.String _UNSUPPORTED_TYPE = "UNSUPPORTED_TYPE";
    public static final java.lang.String _YOU_TUBE_SERVICE_UNAVAILABLE = "YOU_TUBE_SERVICE_UNAVAILABLE";
    public static final java.lang.String _YOU_TUBE_VIDEO_HAS_NON_POSITIVE_DURATION = "YOU_TUBE_VIDEO_HAS_NON_POSITIVE_DURATION";
    public static final java.lang.String _YOU_TUBE_VIDEO_NOT_FOUND = "YOU_TUBE_VIDEO_NOT_FOUND";
    public static final MediaErrorReason CANNOT_ADD_STANDARD_ICON = new MediaErrorReason(_CANNOT_ADD_STANDARD_ICON);
    public static final MediaErrorReason CANNOT_SELECT_STANDARD_ICON_WITH_OTHER_TYPES = new MediaErrorReason(_CANNOT_SELECT_STANDARD_ICON_WITH_OTHER_TYPES);
    public static final MediaErrorReason DUPLICATE_MEDIA = new MediaErrorReason(_DUPLICATE_MEDIA);
    public static final MediaErrorReason EMPTY_FIELD = new MediaErrorReason(_EMPTY_FIELD);
    public static final MediaErrorReason ENTITY_REFERENCED_IN_MULTIPLE_OPS = new MediaErrorReason(_ENTITY_REFERENCED_IN_MULTIPLE_OPS);
    public static final MediaErrorReason FIELD_NOT_SUPPORTED_FOR_MEDIA_SUB_TYPE = new MediaErrorReason(_FIELD_NOT_SUPPORTED_FOR_MEDIA_SUB_TYPE);
    public static final MediaErrorReason INVALID_MEDIA_ID = new MediaErrorReason(_INVALID_MEDIA_ID);
    public static final MediaErrorReason INVALID_MEDIA_SUB_TYPE = new MediaErrorReason(_INVALID_MEDIA_SUB_TYPE);
    public static final MediaErrorReason INVALID_MEDIA_TYPE = new MediaErrorReason(_INVALID_MEDIA_TYPE);
    public static final MediaErrorReason INVALID_REFERENCE_ID = new MediaErrorReason(_INVALID_REFERENCE_ID);
    public static final MediaErrorReason INVALID_YOU_TUBE_ID = new MediaErrorReason(_INVALID_YOU_TUBE_ID);
    public static final MediaErrorReason MEDIA_FAILED_TRANSCODING = new MediaErrorReason(_MEDIA_FAILED_TRANSCODING);
    public static final MediaErrorReason MEDIA_NOT_TRANSCODED = new MediaErrorReason(_MEDIA_NOT_TRANSCODED);
    public static final MediaErrorReason MEDIA_TYPE_DOES_NOT_MATCH_OBJECT_TYPE = new MediaErrorReason(_MEDIA_TYPE_DOES_NOT_MATCH_OBJECT_TYPE);
    public static final MediaErrorReason NO_FIELDS_SPECIFIED = new MediaErrorReason(_NO_FIELDS_SPECIFIED);
    public static final MediaErrorReason NULL_REFERENCE_ID_AND_MEDIA_ID = new MediaErrorReason(_NULL_REFERENCE_ID_AND_MEDIA_ID);
    public static final MediaErrorReason TOO_LONG = new MediaErrorReason(_TOO_LONG);
    public static final MediaErrorReason UNSUPPORTED_OPERATION = new MediaErrorReason(_UNSUPPORTED_OPERATION);
    public static final MediaErrorReason UNSUPPORTED_TYPE = new MediaErrorReason(_UNSUPPORTED_TYPE);
    public static final MediaErrorReason YOU_TUBE_SERVICE_UNAVAILABLE = new MediaErrorReason(_YOU_TUBE_SERVICE_UNAVAILABLE);
    public static final MediaErrorReason YOU_TUBE_VIDEO_HAS_NON_POSITIVE_DURATION = new MediaErrorReason(_YOU_TUBE_VIDEO_HAS_NON_POSITIVE_DURATION);
    public static final MediaErrorReason YOU_TUBE_VIDEO_NOT_FOUND = new MediaErrorReason(_YOU_TUBE_VIDEO_NOT_FOUND);
    public java.lang.String getValue() { return _value_;}
    public static MediaErrorReason fromValue(java.lang.String value)
          throws java.lang.IllegalArgumentException {
        MediaErrorReason enumeration = (MediaErrorReason)
            _table_.get(value);
        if (enumeration==null) throw new java.lang.IllegalArgumentException();
        return enumeration;
    }
    public static MediaErrorReason fromString(java.lang.String value)
          throws java.lang.IllegalArgumentException {
        return fromValue(value);
    }
    public boolean equals(java.lang.Object obj) {return (obj == this);}
    public int hashCode() { return toString().hashCode();}
    public java.lang.String toString() { return _value_;}
    public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new org.apache.axis.encoding.ser.EnumSerializer(
            _javaType, _xmlType);
    }
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new org.apache.axis.encoding.ser.EnumDeserializer(
            _javaType, _xmlType);
    }
    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(MediaErrorReason.class);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "MediaError.Reason"));
    }
    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

}


text:
package org.picocontainer.behaviors;

import org.picocontainer.Behavior;
import org.picocontainer.ComponentAdapter;
import org.picocontainer.ObjectReference;
import org.picocontainer.references.SimpleReference;

/**
 *

 * {@link ComponentAdapter} implementation that caches the component instance.
 *

 *

 * This adapter supports components with a lifecycle, as it is a
 * {@link Behavior lifecycle manager} which will apply the delegate's
 * {@link org.picocontainer.LifecycleStrategy lifecycle strategy} to the cached
 * component instance. The lifecycle state is maintained so that the component
 * instance behaves in the expected way: it can't be started if already started,
 * it can't be started or stopped if disposed, it can't be stopped if not
 * started, it can't be disposed if already disposed.
 *

 *
 * @author Mauro Talevi
 */
@SuppressWarnings("serial")
public class Cached<T> extends Stored<T> {

    public Cached(ComponentAdapter delegate) {
		this(delegate, new SimpleReference<Instance<T>>());
	}

	public Cached(ComponentAdapter delegate, ObjectReference<Instance<T>> instanceReference) {
		super(delegate, instanceReference);
	}

    public String getDescriptor() {
        return "Cached" + getLifecycleDescriptor();
    }
}


text:
$(function($) {
  if ($("#map-canvas").length > 0){
    // load google maps api
    var script = document.createElement('script');
    script.src = "//maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
    document.body.appendChild(script);
  }
});

// var url = window.location.href + "/marker.json";

function initialize() {

  // var markerApi = function(){
  //   return $.ajax({
  //   type: "GET",
  //   url: url,
  //   dataType: "json"
  //   });
  // }

  var drawMap = markerApi().done(
    function(data){
      // var lat = data["marker"]["latitude"];
      // var lon = data["marker"]["longitude"];
      var coordinates = new google.maps.LatLng(40.7048872, -74.0123737);
      var map;
      var mapOptions = {
      center: coordinates,
      zoom: 15,
      disableDefaultUI: true,
      styles: styles
    };

    map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);

    marker = new google.maps.Marker({
      position: coordinates,
      map: map,
    });

  });

}


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Linq.Expressions;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text;
using System.Data.Common;
using System.Reflection;
using Smart.Core.Extensions;
using System.Data;

namespace Smart.Data.Extensions
{
    /// <summary>
    /// DbContext 扩展方法
    /// </summary>
    public static class DbContextExtensions
    {
        private static Regex rxColumns = new Regex(@"\A\s*SELECT\s+((?:\((?>\((?<depth>)|\)(?<-depth>)|.?)*(?(depth)(?!))\)|.)*?)(?<!,\s+)\bFROM\b", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.Compiled);
        private static Regex rxOrderBy = new Regex(@"\bORDER\s+BY\s+(?:\((?>\((?<depth>)|\)(?<-depth>)|.?)*(?(depth)(?!))\)|[\w\(\)\.])+(?:\s+(?:ASC|DESC))?(?:\s*,\s*(?:\((?>\((?<depth>)|\)(?<-depth>)|.?)*(?(depth)(?!))\)|[\w\(\)\.])+(?:\s+(?:ASC|DESC))?)*", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.Compiled);
        private static Regex rxDistinct = new Regex(@"\ADISTINCT\s", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.Compiled);
        private static Regex rxSelect = new Regex(@"\A\s*(SELECT|EXECUTE|CALL|WITH)\s", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Multiline);
        private static Regex rxParamsPrefix = new Regex(@"(?<!@)@\w+", RegexOptions.Compiled);

        /// <summary>
        /// 创建数据库脚本
        /// </summary>
        /// <returns>生成数据库的SQL</returns>
        public static string CreateDatabaseScript(this DbContext db)
        {
            return ((IObjectContextAdapter)db).ObjectContext.CreateDatabaseScript();
        }

        /// <summary>
        /// 创建参数
        /// </summary>
        /// <param name="db"></param>
        /// <param name="parameterName">参数名称,不用加前缀</param>
        /// <param name="dbType">参数数据类型</param>
        /// <param name="parameterDirection">参数输入输出类型</param>
        /// <returns></returns>
        public static DbParameter CreateDbParameter(this DbContext db, string parameterName, DbType dbType, ParameterDirection parameterDirection = ParameterDirection.InputOutput)
        {
            var factory = db.GetDbProviderFactory();
            var parameter = factory.CreateParameter();
            parameter.ParameterName = db.GetParameterPrefix() + parameterName;
            parameter.DbType = dbType;
            parameter.Direction = parameterDirection;
            return parameter;
        }

        /// <summary>
        /// 分离实体
        /// </summary>
        /// <param name="db"></param>
        /// <param name="entity">实体对象</param>
        public static void Detach(this DbContext db, object entity)
        {
            if (entity == null) throw new ArgumentNullException("entity");
            ((IObjectContextAdapter)db).ObjectContext.Detach(entity);
        }

        /// <summary>
        /// 分离实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="db"></param>
        /// <param name="entity"></param>
        public static void Detach<T>(this DbContext db, T entity) where T : class
        {
            if (entity == null) throw new ArgumentNullException("entity");
            ObjectContext oc = ((IObjectContextAdapter)db).ObjectContext;
            oc.Detach(entity);
        }

        /// <summary>
        /// 分离已经存在实体,根据传入实体的主键信息匹配
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="db">数据库上下文对象</param>
        /// <param name="obj">要分离的实体</param>
        ///
        public static void DetachOther<T>(this DbContext db, T obj) where T : class
        {
            var local = db.FindLocal(obj);
            if (local != null)
            {
                db.Detach(local);
            }
        }

        /// <summary>
        /// 执行SQL语句,并返回受影响行数。
        /// </summary>
        /// <param name="db"></param>
        /// <param name="sql">要执行的Sql语句,如:update userinfo set name=@0 where id=@1</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public static int ExecuteSql(this DbContext db, string sql, params object[] parameters)
        {
            //sql.ThrowIfNull("sql");
            using (var cmd = db.CreateDbCommand())
            {
                var ps = db.ProcessParams(sql, parameters);
                cmd.CommandText = ps.Item1;
                cmd.Parameters.AddRange(ps.Item2.ToArray());
                if (cmd.Connection.State != ConnectionState.Open)
                {
                    cmd.Connection.Open();
                }
                return cmd.ExecuteNonQuery();
            }
        }

        /// <summary>
        /// 执行SQL语句,并返回受影响行数。
        /// </summary>
        /// <param name="db"></param>
        /// <param name="sqls">要执行的Sql语句集合</param>
        /// <param name="parameters">参数列表集合</param>
        /// <returns></returns>
        public static int ExecuteSql(this DbContext db, List<string> sqls, List<object[]> parameters)
        {
            sqls.ThrowIfNull("sqls");
            parameters.ThrowIfInvalidOperation(() => parameters != null && sqls.Count != parameters.Count, "sqls 和 parameters 的个数必须一致!");
            using (var cmd = db.CreateDbCommand())
            {
                if (cmd.Connection.State != ConnectionState.Open)
                {
                    cmd.Connection.Open();
                }
                var reslut = 0;
                for (int i = 0; i < sqls.Count; i++)
                {
                    var ps = db.ProcessParams(sqls[i], parameters == null ? null : parameters[i]);
                    cmd.CommandText = ps.Item1;
                    cmd.Parameters.Clear();
                    cmd.Parameters.AddRange(ps.Item2.ToArray());
                    reslut += cmd.ExecuteNonQuery();
                }
                return reslut;
            }
        }

        /// <summary>
        /// 执行SQL语句,并返第一行第一列的值
        /// </summary>
        /// <param name="db"></param>
        /// <param name="sql">要执行的Sql语句,如:select count(1) from sysuser</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public static object ExecuteScalar(this DbContext db, string sql, params object[] parameters)
        {
            using (var cmd = db.CreateDbCommand())
            {
                var ps = db.ProcessParams(sql, parameters);
                cmd.CommandText = ps.Item1;
                cmd.Parameters.AddRange(ps.Item2.ToArray());
                if (cmd.Connection.State != ConnectionState.Open)
                {
                    cmd.Connection.Open();
                }
                return cmd.ExecuteScalar();
            }
        }

        /// <summary>
        /// 执行存储过程。
        /// </summary>
        /// <param name="db"></param>
        /// <param name="procName">存储过程名称</param>
        /// <param name="paramObject">输入参数对象,一般使用一个匿名类型,也可以为null</param>
        /// <param name="parameters">参数数组,DbParameter 使用 db.</param>
        /// <returns>返回受影响行数</returns>
        public static int ExecuteProc(this DbContext db, string procName, object paramObject, params DbParameter[] parameters)
        {
            using (var cmd = db.CreateDbCommand())
            {
                cmd.CommandText = procName;
                cmd.CommandType = CommandType.StoredProcedure;
                #region 参数处理

                if (paramObject != null)
                {
                    var inParams = db.CreateParameters(paramObject);
                    cmd.Parameters.AddRange(inParams.ToArray());
                }

                if (parameters != null)
                {
                    cmd.Parameters.AddRange(parameters);
                }
                #endregion
                if (cmd.Connection.State != ConnectionState.Open)
                {
                    cmd.Connection.Open();
                }

                var result = cmd.ExecuteNonQuery();
                return result;
            }
        }
        /// <summary>
        /// 执行存储过程。
        /// </summary>
        /// <param name="db"></param>
        /// <param name="procName">存储过程名称</param>
        /// <param name="paramObject">输入参数对象,一般使用一个匿名类型,也可以为null</param>
        /// <param name="parameters">参数数组,DbParameter 使用 db.</param>
        /// <returns>返回数据集</returns>
        public static DataSet ExecuteProcDataSet(this DbContext db, string procName, object paramObject, params DbParameter[] parameters)
        {
            using (var cmd = db.CreateDbCommand())
            {
                cmd.CommandText = procName;
                cmd.CommandType = CommandType.StoredProcedure;
                #region 参数处理

                if (paramObject != null)
                {
                    var inParams = db.CreateParameters(paramObject);
                    cmd.Parameters.AddRange(inParams.ToArray());
                }

                if (parameters != null)
                {
                    cmd.Parameters.AddRange(parameters);
                }
                #endregion
                if (cmd.Connection.State != ConnectionState.Open)
                {
                    cmd.Connection.Open();
                }
                var ds = new DataSet();
                var ada = db.GetDbProviderFactory().CreateDataAdapter();
                ada.SelectCommand = cmd;
                ada.Fill(ds);
                return ds;
            }
        }

        /// <summary>
        /// 获取数据库抽象工厂类
        /// </summary>
        /// <param name="db"></param>
        /// <returns></returns>
        public static DbProviderFactory GetDbProviderFactory(this DbContext db)
        {
            var conn = db.Database.Connection;
            var pi = conn.GetType().GetProperty("DbProviderFactory", BindingFlags.NonPublic | BindingFlags.Instance);
            return pi.GetValue(conn, null) as DbProviderFactory;
        }

        /// <summary>
        /// 获取数据库类型
        /// </summary>
        /// <param name="db"></param>
        /// <returns></returns>
        public static string GetDbType(this DbContext db)
        {
            string dbtype = db.Database.Connection.GetType().Name;
            if (dbtype.Contains("MySql")) return "MYSQL";
            else if (dbtype.Contains("SqlCe")) return "SQLSERVERCE";
            else if (dbtype.Contains("Npgsql")) return "POSTGRESQL";
            else if (dbtype.Contains("Oracle")) return "ORACLE";
            else if (dbtype.Contains("SQLite")) return "SQLITE";
            else if (dbtype.Contains("Sql")) return "SQLSERVER";
            else return dbtype.Replace("Connection", "");
        }

        /// <summary>
        /// 获取数据库参数前缀字符
        /// </summary>
        /// <param name="db"></param>
        /// <returns></returns>
        public static string GetParameterPrefix(this DbContext db)
        {
            var dbType = db.GetDbType();
            switch (dbType)
            {
                case "MYSQL":
                    return "?";
                case "ORACLE":
                    return ":";
                default:
                    return "@";
            }
        }

        /// <summary>
        /// 获取实体的主键信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="db"></param>
        /// <returns></returns>
        public static IEnumerable<string> GetEntityKeys<T>(this DbContext db) where T : class
        {
            ObjectContext oc = ((IObjectContextAdapter)db).ObjectContext;
            var keys = oc.CreateObjectSet<T>().EntitySet.ElementType.KeyProperties.Select(x => x.Name);
            return keys;
        }

        /// <summary>
        /// 在Local中查询实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="db"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T FindLocal<T>(this DbContext db, T obj) where T : class
        {
            var keys = db.GetEntityKeys<T>();
            var func = GetFindExp<T>(obj, keys).Compile();
            return db.Set<T>().Local.FirstOrDefault(func);
        }
        private static Expression<Func<T, bool>> GetFindExp<T>(T obj, IEnumerable<string> keys) where T : class
        {
            var p = Expression.Parameter(typeof(T), "x");

            var keyexps = keys.Select(x =>
            {
                var member = Expression.PropertyOrField(p, x);
                var objV = typeof(T).GetProperty(x).GetValue(obj, null);
                var eq = Expression.Equal(member, Expression.Constant(objV));
                return eq;
            }).ToList();

            if (keys.Count() == 1)
            {
                return Expression.Lambda<Func<T, bool>>(keyexps[0], new[] { p });
            }

            var and = Expression.AndAlso(keyexps[0], keyexps[1]);
            for (var i = 2; i < keyexps.Count; i++)
            {
                and = Expression.AndAlso(and, keyexps[i]);
            }
            return Expression.Lambda<Func<T, bool>>(and, new[] { p });
        }

        /// <summary>
        /// 执行SQL语句,获取查询结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="db"></param>
        /// <param name="sql">要执行的Sql语句,如:select * from userinfo where id=@0</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public static IEnumerable<T> Query<T>(this DbContext db, string sql, params object[] parameters)
        {
            if (!rxSelect.IsMatch(sql))
            {
                sql = $"select t.* from {typeof(T).Name} t where {sql}";
            }
            var ps = db.ProcessParams(sql, parameters);
            sql = ps.Item1;
            parameters = ps.Item2.ToArray();
            return db.Database.SqlQuery<T>(sql, parameters);
        }

        /// <summary>
        /// 通过sql查询返回DataTable
        /// </summary>
        /// <param name="db"></param>
        /// <param name="sql">要执行的Sql语句,如:select * from userinfo where id=@0</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public static DataTable QueryDataTable(this DbContext db, string sql, params object[] parameters)
        {
            using (var cmd = db.CreateDbCommand())
            {
                var ps = db.ProcessParams(sql, parameters);
                cmd.CommandText = ps.Item1;
                cmd.Parameters.AddRange(ps.Item2.ToArray());
                if (cmd.Connection.State != ConnectionState.Open)
                {
                    cmd.Connection.Open();
                }

                using (var dataReader = cmd.ExecuteReader())
                {
                    var dt = new DataTable();
                    dt.Load(dataReader);
                    return dt;
                }
            }

        }

        /// <summary>
        ///  通过sql查询返回动态列表
        /// </summary>
        /// <param name="db"></param>
        /// <param name="sql">要执行的Sql语句,如:select * from userinfo where id=@0</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public static IEnumerable<dynamic> QueryDynamic(this DbContext db, string sql, params object[] parameters)
        {
            using (var cmd = db.CreateDbCommand())
            {
                var ps = db.ProcessParams(sql, parameters);
                cmd.CommandText = ps.Item1;
                cmd.Parameters.AddRange(ps.Item2.ToArray());
                if (cmd.Connection.State != ConnectionState.Open)
                {
                    cmd.Connection.Open();
                }

                //var retObject = new List<dynamic>();
                using (var dataReader = cmd.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        yield return dataReader.AsDynamic();
                    }
                }
            }
        }

        /// <summary>
        /// 执行分页查询,返回分页结果
        /// </summary>
        /// <param name="db"></param>
        /// <param name="pageIndex">当前页码,从1开始</param>
        /// <param name="pageSize">分页大小</param>
        /// <param name="sqlText">完整的分页前的查询语句</param>
        /// <param name="parameters">查询SQL的参数列表</param>
        /// <returns>分页数据对象</returns>
        public static Page<T> QueryPage<T>(this DbContext db, int pageIndex, int pageSize, string sqlText, params object[] parameters) where T : class
        {
            if (!rxSelect.IsMatch(sqlText))
            {
                sqlText = $"select t.* from {typeof(T).Name} t where {sqlText}";
            }

            string sqlCount, sqlPage;
            // 生成分页查询
            db.BuildPageQueries((pageIndex - 1) * pageSize, pageSize, sqlText, ref parameters, out sqlCount, out sqlPage);
            // 初始化返回结果
            var sql = db.ProcessParams(sqlCount, parameters);
            var result = db.Database.SqlQuery<Page<T>>(sql.Item1, sql.Item2.ToArray()).First();
            result.CurrentPage = pageIndex;
            result.PageSize = pageSize;
            //result.TotalPages = result.TotalItems / pageSize;
            //if ((result.TotalItems % pageSize) != 0)
            //    result.TotalPages++;
            // 执行查询获取数据
            sql = db.ProcessParams(sqlPage, parameters);
            result.Items = db.Database.SqlQuery<T>(sql.Item1, sql.Item2.ToArray()).ToList();
            return result;
        }

        /// <summary>
        /// 移除实体, 执行 SaveChanges 后提交
        /// <para></para>
        /// <para>示例:</para>
        /// <para>dbContext.Remoe(model);</para>
        /// <para>dbContext.SaveChanges();</para>
        /// </summary>
        /// <typeparam name="TEntity">实体类型</typeparam>
        /// <param name="db"></param>
        /// <param name="entity">要删除的实体,实体中只需要主键字段信息</param>
        public static void Remove<TEntity>(this DbContext db, TEntity entity) where TEntity : class
        {
            db.DetachOther(entity);
            var entry = db.Entry(entity);
            db.Set<TEntity>().Attach(entity);
            entry.State = EntityState.Deleted;
        }

        /// <summary>
        /// 移除实体, 执行 SaveChanges 后提交
        /// <para></para>
        /// <para>示例:</para>
        /// <para>dbContext.Remoe(entites);</para>
        /// <para>dbContext.SaveChanges();</para>
        /// </summary>
        /// <typeparam name="TEntity">实体类型</typeparam>
        /// <param name="db"></param>
        /// <param name="entites">要删除的实体列表,实体中只需要主键字段信息</param>
        public static void Remove<TEntity>(this DbContext db, IEnumerable<TEntity> entites) where TEntity : class
        {
            foreach (var entity in entites)
            {
                db.DetachOther(entity);
                var entry = db.Entry(entity);
                db.Set<TEntity>().Attach(entity);
                entry.State = EntityState.Deleted;
            }
        }

        /// <summary>
        /// 批量更新实体, 执行 SaveChanges 后提交
        /// <para></para>
        /// <para>示例:</para>
        /// <para>更新所有字段:dbContext.Update(models);</para>
        /// <para>更新一个字段:dbContext.Update(models, updateProperties : m=>m.Name);</para>
        /// <para>更新多个字段:dbContext.Update(models, updateProperties : m=>new {m.Name, m.Phone});</para>
        /// <para>忽略多个字段:dbContext.Update(models, ignoreProperties  : m=>new {m.Name, m.Phone});</para>
        /// <para>提交所有变更:dbContext.SaveChanges();</para>
        /// </summary>
        /// <typeparam name="TEntity">实体类型</typeparam>
        /// <param name="db"></param>
        /// <param name="entites">要更新的实体</param>
        /// <param name="updateProperties">要更新的字段</param>
        /// <param name="ignoreProperties">要忽略更新的字段</param>
        public static void Update<TEntity>(this DbContext db, IEnumerable<TEntity> entites,
            Expression<Func<TEntity, object>> updateProperties = null,
            Expression<Func<TEntity, object>> ignoreProperties = null) where TEntity : class
        {
            foreach (var item in entites)
            {
                Update(db, item, updateProperties, ignoreProperties);
            }
        }

        /// <summary>
        /// 更新实体, 执行 SaveChanges 后提交
        /// <para></para>
        /// <para>示例:</para>
        /// <para>更新所有字段:dbContext.Update(model);</para>
        /// <para>更新一个字段:dbContext.Update(model, updateProperties : m=>m.Name);</para>
        /// <para>更新多个字段:dbContext.Update(model, updateProperties : m=>new {m.Name, m.Phone});</para>
        /// <para>忽略多个字段:dbContext.Update(model, ignoreProperties  : m=>new {m.Name, m.Phone});</para>
        /// <para>提交所有变更:dbContext.SaveChanges();</para>
        /// </summary>
        /// <typeparam name="TEntity">实体类型</typeparam>
        /// <param name="db"></param>
        /// <param name="entity">要更新的实体</param>
        /// <param name="updateProperties">要更新的字段</param>
        /// <param name="ignoreProperties">要忽略更新的字段</param>
        public static void Update<TEntity>(this DbContext db, TEntity entity,
            Expression<Func<TEntity, object>> updateProperties = null,
            Expression<Func<TEntity, object>> ignoreProperties = null) where TEntity : class
        {
            if (updateProperties != null && ignoreProperties != null)
                throw new ArgumentException("不能同时指定 更新字段和忽略字段参数");
            //db.DetachOther(entity);
            var attachEntity = db.FindLocal(entity);
            if (attachEntity == null)
            {
                db.Set<TEntity>().Attach(entity);
            }

            var entry = db.Entry(entity);
            if (updateProperties != null)
            {
                // 指定更新部分字段
                var updateProps = GetProperties(entity, updateProperties);
                foreach (var item in updateProps)
                {
                    entry.Property(item).CurrentValue = typeof(TEntity).GetProperty(item).GetValue(entity, null);
                    entry.Property(item).IsModified = true;
                }
            }
            else if (ignoreProperties != null)
            {
                // 忽略指定字段更新
                entry.State = EntityState.Modified;

                var ignoreProps = GetProperties(entity, ignoreProperties);
                foreach (var item in ignoreProps)
                {
                    entry.Property(item).CurrentValue = typeof(TEntity).GetProperty(item).GetValue(entity, null);
                    entry.Property(item).IsModified = false;
                }
            }
            else
            {
                // 指定更新整个实体
                entry.State = EntityState.Modified;
            }
        }

        private static string[] GetProperties<TEntity>(TEntity entity, Expression<Func<TEntity, object>> selectorMember) where TEntity : class
        {
            if (selectorMember == null) return null;

            string[] properties = null;
            if (selectorMember.Body is MemberExpression)
            {
                properties = new string[] { (selectorMember.Body as MemberExpression).Member.Name };
            }
            else if (selectorMember.Body is UnaryExpression) // 可空类型成员
            {
                var me = (selectorMember.Body as UnaryExpression).Operand as MemberExpression;
                if (me != null) properties = new string[] { me.Member.Name };
            }
            else
            {
                var pis = selectorMember.Compile()(entity).GetType().GetProperties();
                properties = new string[pis.Length];
                for (int i = 0; i < pis.Length; i++)
                {
                    properties[i] = pis[i].Name;
                }
            }
            return properties;
        }

        /// <summary>
        /// 创建DbCommand实例
        /// </summary>
        /// <param name="db"></param>
        /// <returns></returns>
        internal static DbCommand CreateDbCommand(this DbContext db)
        {
            var cmd = db.Database.Connection.CreateCommand();
            #region 如果是ODP.NET提供程序,则设置为按名称绑定参数
            if (db.GetDbType() == "ORACLE")
            {
                var pi = cmd.GetType().GetProperty("BindByName");
                if (pi != null) pi.SetValue(cmd, true, null);
            }
            #endregion
            return cmd;
        }

        /// <summary>
        /// 根据对象创建参数列表
        /// </summary>
        /// <param name="db"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        internal static List<DbParameter> CreateParameters(this DbContext db, object parameters)
        {
            var dbProviderFactory = db.GetDbProviderFactory();
            var pis = parameters.GetType().GetProperties();
            List<DbParameter> paramList = new List<DbParameter>();
            foreach (var item in pis)
            {
                var param = dbProviderFactory.CreateParameter();
                param.ParameterName = db.GetParameterPrefix() + item.Name;
                param.Value = item.GetValue(parameters, null);
                paramList.Add(param);
            }
            return paramList;
        }

        /// <summary>
        /// 生成分页查询语句
        /// </summary>
        /// <param name="db"></param>
        /// <param name="skip"></param>
        /// <param name="take"></param>
        /// <param name="sql"></param>
        /// <param name="args"></param>
        /// <param name="sqlCount"></param>
        /// <param name="sqlPage"></param>
        internal static void BuildPageQueries(this DbContext db, long skip, long take, string sql, ref object[] args, out string sqlCount, out string sqlPage)
        {
            var dbType = db.GetDbType();
            string sqlSelectRemoved, sqlOrderBy;
            if (!SplitSqlForPaging(sql, out sqlCount, out sqlSelectRemoved, out sqlOrderBy))
                throw new Exception("无法解析为分页查询的SQL语句");
            if (dbType == "ORACLE" && sqlSelectRemoved.StartsWith("*"))
                throw new Exception("执行分页查询时必须为'*'指定别名。如: select t.* from table t order by t.id");

            // Build the SQL for the actual final result
            if (dbType == "SQLSERVER" || dbType == "ORACLE")
            {
                sqlSelectRemoved = DbContextExtensions.rxOrderBy.Replace(sqlSelectRemoved, "");
                if (rxDistinct.IsMatch(sqlSelectRemoved))
                {
                    sqlSelectRemoved = "peta_inner.* FROM (SELECT " + sqlSelectRemoved + ") peta_inner";
                }
                var orderby = sqlOrderBy.IsEmpty() ? ("ORDER BY (SELECT NULL" + (dbType == "ORACLE" ? " FROM DUAL" : "") + ")") : sqlOrderBy;
                sqlPage = $"SELECT * FROM (SELECT ROW_NUMBER() OVER ({orderby}) _rownum,{ sqlSelectRemoved}) _paged WHERE _rownum>@{ args.Length} AND _rownum<=@{args.Length + 1}";
                args = args.Concat(new object[] { skip, skip + take }).ToArray();
            }
            else if (dbType == "SQLSERVERCE")
            {
                sqlPage = $"{sql}\nOFFSET @{args.Length} ROWS FETCH NEXT @{ args.Length + 1} ROWS ONLY";
                args = args.Concat(new object[] { skip, take }).ToArray();
            }
            else
            {
                sqlPage = $"{sql}\nLIMIT @{args.Length} OFFSET @{args.Length + 1}";
                args = args.Concat(new object[] { take, skip }).ToArray();
            }
        }

        /// <summary>
        /// 将SQL转成分页查询SQL
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="sqlCount">总记录数统计SQL</param>
        /// <param name="sqlSelectRemoved"></param>
        /// <param name="sqlOrderBy">排序条件</param>
        /// <returns></returns>
        internal static bool SplitSqlForPaging(string sql, out string sqlCount, out string sqlSelectRemoved, out string sqlOrderBy)
        {
            sqlSelectRemoved = null;
            sqlCount = null;
            sqlOrderBy = null;

            var m = rxColumns.Match(sql);
            if (!m.Success)
                return false;

            Group g = m.Groups[1];
            sqlSelectRemoved = sql.Substring(g.Index);

            if (rxDistinct.IsMatch(sqlSelectRemoved))
                sqlCount = sql.Substring(0, g.Index) + "COUNT(" + m.Groups[1].ToString().Trim() + ") TotalItems " + sql.Substring(g.Index + g.Length);
            else
                sqlCount = sql.Substring(0, g.Index) + "COUNT(*) TotalItems " + sql.Substring(g.Index + g.Length);

            m = rxOrderBy.Match(sqlCount);
            if (!m.Success)
            {
                sqlOrderBy = null;
            }
            else
            {
                g = m.Groups[0];
                sqlOrderBy = g.ToString();
                sqlCount = sqlCount.Substring(0, g.Index) + sqlCount.Substring(g.Index + g.Length);
            }

            return true;
        }

        /// <summary>
        /// 参数处理
        /// </summary>
        /// <param name="db"></param>
        /// <param name="sql"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        internal static Tuple<string, List<object>> ProcessParams(this DbContext db, string sql, object[] args)
        {
            var prefix = db.GetParameterPrefix();
            var dbProviderFactory = db.GetDbProviderFactory();
            var parameters = new List<object>();
            var sqlText = rxParamsPrefix.Replace(sql, m =>
            {
                string paramName = m.Value.Substring(1);
                object paramValue;
                int paramIndex;

                if (int.TryParse(paramName, out paramIndex))
                {
                    #region 验证参数数值和个数是否匹配

                    if (paramIndex < 0 || paramIndex >= args.Length)
                        throw new ArgumentOutOfRangeException($"参数 '@{paramIndex}' 不在指定的范围内。");
                    paramValue = args[paramIndex];
                    #endregion
                }
                else
                {
                    #region 验证参数名称是不是和对象属性名称一致

                    bool found = false;
                    paramValue = null;
                    foreach (var arg in args)
                    {
                        var argType = arg.GetType();
                        if (argType.IsValueType || argType == typeof(string))
                        {
                            if (paramName == nameof(arg))
                            {
                                paramValue = arg;
                                found = true;
                                break;
                            }
                        }
                        else
                        {
                            var pi = argType.GetProperty(paramName);
                            if (pi != null)
                            {
                                paramValue = pi.GetValue(arg, null);
                                found = true;
                                break;
                            }
                        }
                    }

                    if (!found)
                        throw new ArgumentException($"无法获取参数{paramName}的属性值");
                    #endregion
                }

                #region 创建参数

                // 可迭代类型,但不是 string 和 byte[]
                if ((paramValue as System.Collections.IEnumerable) != null
                     && (paramValue as string) == null
                     && (paramValue as byte[]) == null)
                {
                    var sb = new StringBuilder();
                    foreach (var value in paramValue as System.Collections.IEnumerable)
                    {
                        sb.Append((sb.Length == 0 ? prefix : "," + prefix));
                        sb.Append(parameters.Count.ToString());
                        var param = dbProviderFactory.CreateParameter();
                        param.ParameterName = paramName;
                        param.Value = value;
                        parameters.Add(param);
                    }
                    return sb.ToString();
                }
                else
                {
                    var param = dbProviderFactory.CreateParameter();
                    param.ParameterName = parameters.Count.ToString();
                    param.Value = paramValue;
                    parameters.Add(param);
                    return prefix + param.ParameterName;
                }
                #endregion

            });

            var result = new Tuple<string, List<object>>(sqlText, parameters);
            return result;
        }
    }
}


text:
package movers;

import movers.Constants;
import movers.Constants.levelType;

import java.util.Random;

import movers.Constants.moverType;
import javafx.animation.KeyFrame;
import javafx.geometry.Point2D;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Mover{

	protected Color color;
	protected int centerX,centerY;
	public Random myGenerator;
	protected levelType level;
	protected boolean bumpTag;
	protected boolean destroyTag;
	protected int speed;

	public Mover(levelType playLevel){
		super();
		level = playLevel;
		bumpTag = false;
	}

	public int getCenterX(){
		return centerX;
	}

	public int getCenterY(){
		return centerY;
	}

	public void setBumpTag(){
		bumpTag = true;
	}

	public boolean getBumpTag(){
		return bumpTag;
	}

	public void setDestroyTag(){
		bumpTag = true;
	}

	public boolean getDestroyTag(){
		return bumpTag;
	}

}


text:
import logging

from collections import defaultdict
from errno import ENOENT
from stat import S_IFDIR, S_IFLNK, S_IFREG
from sys import argv, exit
from time import time

from fuse import FUSE, FuseOSError, Operations, LoggingMixIn
from xmlrpclib import Binary
import sys, pickle, xmlrpclib
import pprint
ttl =3000

if not hasattr(__builtins__, 'bytes'):
    bytes = str

############################
### RV: custom functions ###
############################

def putRpcDict(myserver,fileDict):
   key = "dictionary"
   pickled_value = pickle.dumps(fileDict) ## pickle data to be sent

   print "\n \nStoring and retrieving ", type(fileDict)," with RPC"
   print "PUT: \nkey -> ",key, "\nvalue -> ",fileDict ## print data

   ## put the data in HT with key as type name. Eg: key-"integer" data-1000
   myserver.put(xmlrpclib.Binary(key), xmlrpclib.Binary(pickled_value), ttl)
   print "\n"
   print "GET: key ->", key

def getRpcDict(myserver):

   rv = myserver.get(Binary("dictionary"))

   pprint.pprint(rv)
   ## print variable type of data recieved
   print "Type of the data received: ",type(pickle.loads(rv["value"].data))
   print "value.data: "
   ## unmarshall the data from server and pprint the data.
   return pickle.loads(rv["value"].data)

### split path to keys####

def splitPath(spath):

  print "split path"
  if spath == '/':
      return list('/')
  else:
      mapList = spath.split('/')
      #mapList.remove('')
      mapList=['/' + x for x in mapList]
      #print mapList
      return mapList

### make path from list of keys ###
def makePath(plist):
    print "make path"
    nlist  = []

    for x in plist: nlist.append(x[1:])

    npath =  '/'.join(nlist)

    #npath = '/' +npath
    print "npath"

    if npath == '':
        npath = '/'
    #print npath

    return npath

### get file from dictionary ###

def getFileDict(fileDict, fpath): ## rv check path

     if not isinstance(fpath,list):
         mapList = splitPath(fpath)
     else:
         mapList = fpath

     print "get file"
     print mapList

     rfiles = reduce(lambda d, k: d[k]["childnodes"], mapList, fileDict)

     print rfiles
     return rfiles

def setFileDict(fileDict, spath, value): ## set path

    # if not isinstance(spath,list):
    #     mapList = splitPath(spath)
    # else:
    #     mapList = spath

     mapList = splitPath(spath)

     print "setFile"
     print mapList

     if spath == '/':
          fileDict["/"] = value
    # elif len(mapList) == 1:
     #     fileDict[mapList[0]]["metadata"] = value
     #     fileDict[mapList[0]]["childnodes"] = {}
     else:
          par_dir ={}
          print mapList[-1]
          par_dir_childnodes = getFileDict(fileDict, makePath(mapList[:-1]))
          par_dir_childnodes[mapList[-1]] = value

def getParentDict(fileDict, spath): ## gets the key to parent directory

     mapList = splitPath(spath)

     print "setFile"
     print mapList

     if spath == '/':
          return None
     else:
          return getCurFile(fileDict, makePath(mapList[:-1]))

def getCurFile(fileDict, spath): ## gets the key to parent directory

     mapList = splitPath(spath)

     print "get current file"
     print mapList

     if spath == '/':
          return fileDict['/']
     else:
          print "cur_file:", mapList[-1]
          cur_file = getFileDict(fileDict, makePath(mapList[:-1]))[mapList[-1]]
          print "CURR FILE DICT" , cur_file
          return cur_file

def popFileDict(fileDict,spath):

     mapList = splitPath(spath)

     print "setFile"
     print mapList

     if spath == '/':
          return None
     else:
          par_dir= getCurFile(fileDict, makePath(mapList[:-1]))
          popedFile = par_dir["childnodes"].pop(mapList[-1])
          return popedFile

def pathCheck(fileDict,spath):

    print "path check"
    print spath
    print fileDict
    try:
      getCurFile(fileDict,spath)
      return True
    except:
      return False

######
######

class Memory(LoggingMixIn, Operations):
    'Example memory filesystem. Supports only one level of files.'

    def __init__(self,url):
        self.files = {}
        self.myserver = xmlrpclib.ServerProxy(url)
        self.files['/'] = {"metadata":{},"childnodes":{},"data":list()}
        putRpcDict(self.myserver,self.files)
        self.data = defaultdict(bytes)
        self.fd = 0
        now = time()
        self.files['/'] = {"metadata":{},"childnodes":{},"data":list()}
        self.files['/']["metadata"] = dict(st_mode=(S_IFDIR | 0755), st_ctime=now,
                               st_mtime=now, st_atime=now, st_nlink=2)

        putRpcDict(self.myserver,self.files)

    def chmod(self, path, mode):
        fileDict = getRpcDict(self.myserver)
        curFile = getCurFile(fileDict,path) #rv
        curFile["metadata"]['st_mode'] &= 0770000 #rv
        curFile["metadata"]['st_mode'] |= mode    #rv
        putRpcDict(self.myserver,fileDict)

        return 0

    def chown(self, path, uid, gid):
        fileDict = getRpcDict(self.myserver)
        curFile = getCurFile(fileDict,path) #rv
        curFile["metadata"]['st_uid'] = uid
        curFile["metadata"]['st_gid'] = gid
        putRpcDict(self.myserver,fileDict)

    def create(self, path, mode):

        data = {}
        data["metadata"] = dict(st_mode=(S_IFREG | mode), st_nlink=1,
                                st_size=0, st_ctime=time(), st_mtime=time(),
                                st_atime=time())
        data["childnodes"] = {}
        data["data"] = list()

        fileDict = getRpcDict(self.myserver)
        setFileDict(fileDict,path,data)
        putRpcDict(self.myserver,fileDict)

        self.fd += 1
        return self.fd

    def getattr(self, path, fh=None):
        fileDict = getRpcDict(self.myserver)
        print "GETT ATTRS of file: ",path
        if not pathCheck(fileDict,path):#Check if the file exist using pathCheck() rv
            raise FuseOSError(ENOENT)

        return getCurFile(fileDict,path)["metadata"] #rv

    def getxattr(self, path, name, position=0):
        fileDict = getRpcDict(self.myserver)
        print "attr name"
        print name
        print "xattr position"
        print position

        curFile = getCurFile(fileDict,path)
        attrs = curFile["metadata"].get('attrs', {})

        try:
            return attrs[name]
        except KeyError:
            return ''       # Should return ENOATTR

    def listxattr(self, path):
        fileDict = getRpcDict(self.myserver)
        curFile = getCurFile(fileDict,path) #rv
        attrs = curFile["metadata"].get('attrs', {})
        return attrs.keys()

    def mkdir(self, path, mode):
        data = { "metadata": dict(st_mode=(S_IFDIR | mode), st_nlink=2,
                                st_size=0, st_ctime=time(), st_mtime=time(),
                                st_atime=time()),"childnodes": dict(),"data":list()}

        print "MKDIR", path
        fileDict = getRpcDict(self.myserver)
        setFileDict(fileDict,path,data)

        getParentDict(fileDict,path)["metadata"]['st_nlink'] += 1

        putRpcDict(self.myserver,fileDict)

    def open(self, path, flags):
        self.fd += 1
        return self.fd

    def read(self, path, size, offset, fh):
        fileDict = getRpcDict(self.myserver)
        curFile= getCurFile(fileDict,path)
        datalist = curFile["data"][offset:offset + size]
        datastring = ''.join(datalist)
        return datastring
    def readdir(self, path, fh):
        fileDict = getRpcDict(self.myserver)
        curFile = getCurFile(fileDict,path)["childnodes"]
        return ['.', '..'] + [x[1:] for x in curFile if x != '/'] ## rv: DOUBT ##

    def readlink(self, path):
        fileDict = getRpcDict(self.myserver)
        curFile = getCurFile(fileDict,path)
        return curFile["data"]

    def removexattr(self, path, name):
        fileDict = getRpcDict(self.myserver)
        curFile=getCurFile(fileDict,path) #rv
        attrs = curFile["metadata"].get('attrs', {})  #rv

        try:
            del attrs[name]
            putRpcDict(self.myserver,fileDict)
        except KeyError:
            pass        # Should return ENOATTR

    def rename(self, old, new):
         #rv
        fileDict = getRpcDict(self.myserver)
        if not pathCheck(fileDict,old):  #Check if the file exist using pathCheck() rv
            raise FuseOSError(ENOENT)

        popedFile=popFileDict(fileDict,old)
        setFileDict(fileDict,new,popedFile)
        putRpcDict(self.myserver,fileDict)

    def rmdir(self, path):
        fileDict = getRpcDict(self.myserver)
        popFileDict(fileDict,path)

        getParentDict(fileDict,path)["metadata"]['st_nlink'] -= 1

        putRpcDict(self.myserver,fileDict)

    def setxattr(self, path, name, value, options, position=0):
        # Ignore options
        fileDict = getRpcDict(self.myserver)
        curFile=getCurFile(fileDict,path) #rv

        attrs = curFile["metadata"].setdefault('attrs', {})
        attrs[name] = value
        putRpcDict(self.myserver,fileDict)

    def statfs(self, path):
        return dict(f_bsize=512, f_blocks=4096, f_bavail=2048)

    def symlink(self, target, source):
        fileDict = getRpcDict(self.myserver)
        file_dict ={"metadata": dict(st_mode=(S_IFLNK | 0777), st_nlink=1,
                                  st_size=len(source)),"childnodes" : {},"data":{}}

        setFileDict(fileDict,target,file_dict)

        curFile= getCurFile(fileDict,target)

        curFile["data"]=source
        putRpcDict(self.myserver,fileDict)

    def truncate(self, path, length, fh=None):
        fileDict = getRpcDict(self.myserver)
        curFile=getCurFile(fileDict,path)
        curFile["data"] = curFile["data"][:length]
        curFile["metadata"]['st_size'] = length
        putRpcDict(self.myserver,fileDict)

    def unlink(self, path):
        fileDict = getRpcDict(self.myserver)
        popFileDict(fileDict,path)
        putRpcDict(self.myserver,fileDict)

    def utimens(self, path, times=None):
        fileDict = getRpcDict(self.myserver)
        now = time()
        atime, mtime = times if times else (now, now)

        curFile=getCurFile(fileDict,path) #rv
        curFile["metadata"]['st_atime'] = atime
        curFile["metadata"]['st_mtime'] = mtime
        putRpcDict(self.myserver,fileDict)

    def write(self, path, data, offset, fh):
        fileDict = getRpcDict(self.myserver)
        curFile = getCurFile(fileDict,path)
        curFile["data"] = curFile["data"][:offset]+ list(data)
        curFile["metadata"]['st_size'] = len(curFile["data"]) ## rv

        putRpcDict(self.myserver,fileDict)
        return len(data)

if __name__ == '__main__':
    if len(argv) != 3:
        print('usage: %s <mountpoint> <server-url>' % argv[0])
        exit(1)
    url = argv[2]
    logging.getLogger().setLevel(logging.DEBUG)
    fuse = FUSE(Memory(url), argv[1], foreground=True,debug=True)


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea metaleptodes Nyl.

### Remarks
null


text:
#import "OAIPipelineActivity.h"

@implementation OAIPipelineActivity

- (instancetype)init {
  self = [super init];
  if (self) {
    // initialize property's default value, if any

  }
  return self;
}

/**
 * Maps json key to property name.
 * This method is used by `JSONModel`.
 */
+ (JSONKeyMapper *)keyMapper {
  return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{ @"_class": @"_class", @"artifacts": @"artifacts", @"durationInMillis": @"durationInMillis", @"estimatedDurationInMillis": @"estimatedDurationInMillis", @"enQueueTime": @"enQueueTime", @"endTime": @"endTime", @"_id": @"id", @"organization": @"organization", @"pipeline": @"pipeline", @"result": @"result", @"runSummary": @"runSummary", @"startTime": @"startTime", @"state": @"state", @"type": @"type", @"commitId": @"commitId" }];
}

/**
 * Indicates whether the property with the given name is optional.
 * If `propertyName` is optional, then return `YES`, otherwise return `NO`.
 * This method is used by `JSONModel`.
 */
+ (BOOL)propertyIsOptional:(NSString *)propertyName {

  NSArray *optionalProperties = @[@"_class", @"artifacts", @"durationInMillis", @"estimatedDurationInMillis", @"enQueueTime", @"endTime", @"_id", @"organization", @"pipeline", @"result", @"runSummary", @"startTime", @"state", @"type", @"commitId"];
  return [optionalProperties containsObject:propertyName];
}

@end


text:
Credentials
-----------
The TRAW Client can pull in credentials in three ways:

* Passing parameters to ``__init__`` during traw.Client instantiation

  .. code-block:: python

      client = traw.Client(username='user@email.com', password='password', url='url')
      # client = traw.Client(username='user@email.com', user_api_key='userapikey', url='url')

* Setting environment variables

  .. code-block:: bash

      $ export TRAW_USERNAME="user@email.com"
      $ export TRAW_PASSWORD="userapikey"
      $ # export TRAW_USER_API_KEY="userapikey"  # (Optional) - in place of TRAW_PASSWORD
      $ export TRAW_URL="https://example.testrail.net"

* Writing them to a configuration file in the user's home directory

  .. code-block:: bash

      $ cat ~/.traw_config
      [TRAW]
      username = <username>
      password = <password>
      # user_api_key = <user_api_key>  # (Optional) - in place of password
      url = <url>

You can create multiple clients to access different TestRail installations:

.. code-block:: python

    client1 = traw.Client(username='user1@email.com', password='password', url='https://example.testrail.net')
    client2 = traw.Client(username='user2@email.com', password='password', url='https://your.domain.com')


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

  <TextView
      android:id="@+id/result_tv"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="8dp"
      android:gravity="center"
      android:text="false"
      />

  <Button
      android:id="@+id/start_task_btn"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="8dp"
      android:text="START TASK"
      />

</LinearLayout>


text:
#import "VolumesPopUpButton.h"
#import "FSUtils.h"

@implementation VolumesPopUpButton

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(NSRect)frameRect {
    self = [super initWithFrame:frameRect];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
    [[self menu] setDelegate:self];

    [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
                                                           selector: @selector(volumesChanged:)
                                                               name:NSWorkspaceDidMountNotification
                                                             object: nil];
    [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
                                                           selector: @selector(volumesChanged:)
                                                               name:NSWorkspaceDidUnmountNotification
                                                             object:nil];
    [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
                                                           selector: @selector(volumesChanged:)
                                                               name:NSWorkspaceDidRenameVolumeNotification
                                                             object:nil];

    [self populateMenu];
}

- (void)menuWillOpen:(NSMenu *)menu {
    for (NSMenuItem *item in [menu itemArray]) {
        NSString *volPath = [item toolTip];
        if (volPath && ![volPath isEqualToString:@""]) {
            NSImage *icon = [[NSWorkspace sharedWorkspace] iconForFile:[item toolTip]];
            [icon setSize:NSMakeSize(16, 16)];
            [item setImage:icon];
        }
    }
}

- (void)menuDidClose:(NSMenu *)menu {
    for (NSMenuItem *item in [menu itemArray]) {
        [item setImage:nil];
    }
}

- (void)volumesChanged:(NSNotification *)notification {
    [self populateMenu];
}

- (void)notifyDelegateSelectionHasChanged:(id)sender {
    [[self delegate] volumeSelectionChanged:[[self selectedItem] toolTip]];
}

- (void)populateMenu {
    NSMenu *volumesMenu = [self menu];

    // Get currently selected volume
    NSMenuItem *selectedItem = [self selectedItem];
    NSString *selectedPath = [selectedItem toolTip];

    // Get info about mounted file systems
    NSDictionary *filesystems = [FSUtils mountedFileSystems];

    // Clear menu
    [volumesMenu removeAllItems];

    // All + separator
    NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:@"All"
                                                  action:@selector(notifyDelegateSelectionHasChanged:)
                                           keyEquivalent:@""];
    [item setTarget:self];
    [item setToolTip:@""];
    [volumesMenu addItem:item];
    [volumesMenu addItem:[NSMenuItem separatorItem]];

    // NEW METHOD: Add all filesystems (except /dev)
    for (NSNumber *fsid in [filesystems allKeys]) {
        NSDictionary *fs = filesystems[fsid];
        if ([fs[@"mountpoint"] isEqualToString:@"/dev"]) {
            continue;
        }
        NSString *menuItemName = fs[@"mountpoint"];

        // Get volume name, if possible
        NSURL *url = [NSURL fileURLWithPath:fs[@"mountpoint"]];
        NSString *volumeName;
        NSError *err;
        [url getResourceValue:&volumeName forKey:NSURLVolumeNameKey error:&err];
        if (volumeName != nil) {
            menuItemName = [NSString stringWithFormat:@"%@ - %@", volumeName, fs[@"mountpoint"]];
        }

        SEL action = @selector(notifyDelegateSelectionHasChanged:);
        NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:menuItemName
                                                      action:action
                                               keyEquivalent:@""];
        [item setTarget:self];
        [item setToolTip:fs[@"mountpoint"]];
        [item setRepresentedObject:fs];
        [volumesMenu addItem:item];

    }

    // Restore selection, if possible
    NSMenuItem *itemToSelect = [volumesMenu itemArray][0];
    for (NSMenuItem *item in [volumesMenu itemArray]) {
        if ([[item toolTip] isEqualToString:selectedPath]) {
            itemToSelect = item;
            break;
        }
    }
    [self selectItem:itemToSelect];

    if (selectedItem != itemToSelect) {
        [self notifyDelegateSelectionHasChanged:itemToSelect];
    }
}

@end


text:
package com.ibm.crshnburn.zosconnect.interceptor;

import java.security.Principal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.osgi.service.component.ComponentContext;

import com.ibm.wsspi.zos.connect.*;

public class SimpleInterceptorImpl implements Interceptor {

	private DateFormat df = SimpleDateFormat.getDateTimeInstance();

	protected void activate(ComponentContext context,
			Map<String, Object> properties) {
		System.out.println("Sample interceptor activated");
	}

	protected void deactivate(ComponentContext context) {
		System.out.println("Sample interceptor deactivated");
	}

	protected void modified(Map<String, Object> properties) {

	}

	@Override
	public String getName() {
		return "zOSConnectReferenceInterceptor";
	}

	@Override
	public void preInvoke(Map<Object, Object> requestStateMap,
			HttpZosConnectRequest httpZosConnectRequest, Data data)
			throws InterceptorException {
		Principal principal = httpZosConnectRequest.getUserPrincipal();
		String user = "<unknown>";
		if(principal != null){
			user = principal.getName().trim();
		}
		String path = httpZosConnectRequest.getRequestURI().trim();
		System.out.printf("ReferenceInterceptor preInvoke\nUser %s called URI %s at %s\n", user, path,
				df.format(new Date()));
	}

	@Override
	public void postInvoke(Map<Object, Object> requestStateMap,
			HttpZosConnectRequest httpZosConnectRequest, Data data)
			throws InterceptorException {
		Principal principal = httpZosConnectRequest.getUserPrincipal();
		String user = "<unknown>";
		if(principal != null){
			user = principal.getName().trim();
		}
		String path = httpZosConnectRequest.getRequestURI().trim();
		System.out.printf("ReferenceInterceptor postInvoke\nUser %s finished calling URI %s at %s\n", user,
				path, df.format(new Date()));
	}

	@Override
	public int getSequence() {
		return 1;
	}

}