text:
var mongo = require('mongodb');
var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure;

var MONGODB_URI = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/misiondb';

var db;
var coll;

mongo.MongoClient.connect(MONGODB_URI, function(err, database) {
    if(err) throw err;
    db = database;
    db.collection('misions', {strict:true}, function(errs, collection) {
        populateDB();
    });
});

//All methods will check app_id Calling.
exports.startUp = function(req, res)
{
    res.sendfile("README.html");
};

//All methods will check app_id Calling.
exports.getMision = function(req, res)
{
    var application_id = req.params.application_id = "MMO_RPG_START";
    var mision_id = req.params.mision_id;
    console.log('Retrieving mision: ' + mision_id);
    db.collection('misions', function(err, collection) {
        collection.findOne({'_id':new BSON.ObjectID(mision_id), app_id: application_id}, function(err, item) {
            res.send(item);
        });
    });
};

exports.getMisions = function(req, res) {
    var application_id = req.params.application_id = "MMO_RPG_START";
    db.collection('misions', function(err, collection) {
        collection.find({app_id: application_id}).toArray(function(err, items) {
            res.send(items);
        });
    });
};

exports.getActiveMisions = function(req, res) {
    var application_id = req.params.application_id = "MMO_RPG_START";
    db.collection('misions', function(err, collection) {
        collection.find({app_id: application_id, completed: false}).toArray(function(err, items) {
            res.send(items);
        });
    });
};

exports.getPlayerMisions = function(req, res) {
    var application_id = req.params.application_id = "MMO_RPG_START";
    var misioner_id = req.params.player_id;
    db.collection('misions', function(err, collection) {
        collection.find({app_id: application_id, misioner_id: misioner_id}).toArray(function(err, items) {
            res.send(items);
        });
    });
};

exports.getRegionMisions = function(req, res) {
    var application_id = req.params.application_id = "MMO_RPG_START";
    var region = req.params.region;
    db.collection('misions', function(err, collection) {
        collection.find({app_id: application_id, region: region}).toArray(function(err, items) {
            res.send(items);
        });
    });
};

exports.getPlayerActiveMisions = function(req, res) {
    var application_id = req.params.application_id = "MMO_RPG_START";
    var misioner_id = req.params.player_id;
    db.collection('misions', function(err, collection) {
        collection.find({app_id: application_id, misioner_id: misioner_id, completed: false}).toArray(function(err, items) {
            res.send(items);
        });
    });
};

exports.deleteMision = function(req, res) {
    var application_id = req.params.application_id = "MMO_RPG_START";
    var mision_id = req.params.mision_id;
    console.log('Deleting mision: ' + mision_id);
    db.collection('misions', function(err, collection) {
        collection.remove({'_id':new BSON.ObjectID(mision_id), app_id: application_id}, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred - ' + err});
            } else {
                console.log('' + result + ' document(s) deleted');
                res.send(result);
            }
        });
    });
};

exports.addMision = function(req, res) {
    var application_id = req.params.application_id = "MMO_RPG_START";
    var mision = req.body;
    mision.application_id = application_id;

    db.collection('misions', function(err, collection) {
        collection.insert(mision, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred'});
            } else {
                res.send(result[0]);
            }
        });
    });
};

exports.updateMision = function(req, res) {
    var application_id = req.params.application_id = "MMO_RPG_START";
    var mision_id = req.params.mision_id;
    var mision = req.body;
    console.log('Updating mision: ' + mision_id);
    db.collection('misions', function(err, collection) {
        collection.update({'_id':new BSON.ObjectID(mision_id), app_id: application_id}, mision, {safe:true}, function(err, result) {
            if (err) {
                console.log('Error updating mision: ' + err);
                res.send({'error':'An error has occurred'});
            } else {
                console.log('' + result + ' document(s) updated');
                res.send(result);
            }
        });
    });
};

exports.completeMision = function(req, res) {
    var application_id = req.params.application_id = "MMO_RPG_START";
    var mision_id = req.params.mision_id;
    var mision_reqs = req.body;

    db.collection('misions', function(err, collection) {

        collection.find({'_id':new BSON.ObjectID(mision_id), app_id: application_id}).toArray(function(err, items){

            if (hasTheItems(items[0].items_requested, mision_reqs)){
               collection.update({'_id':new BSON.ObjectID(mision_id), app_id: application_id}, {$set: {completed:true}}, {safe:true}, function(err, result) {
                    if (err) {
                        res.send({'error':'An error has occurred'});
                    }
                    else{
                        console.log('' + result + ' document(s) updated');
                        res.send(items[0].items_rewarded);
                    }
                });
            }
            else{
                res.send("no misions to be completed");
            }
        });
    });
};

exports.lookForCompletionMisions = function(req, res) {
    var application_id = req.params.application_id = "MMO_RPG_START";
    var misioner_id = req.params.player_id;
    var mision_req_items = req.body;
    db.collection('misions', function(err, collection) {
        collection.find({app_id: application_id, misioner_id: misioner_id}).toArray(function(err, items) {
            var misions_complete = [];
            for (var i = 0; i < items.length; i++) {
                if (hasTheItems(items[i].items_requested, mision_req_items))
                    misions_complete.push(items[i]);
            }
            res.send(misions_complete);
        });
    });
};

exports.lookForCompletionExternalMisions = function(req, res) {
    var application_id = req.params.application_id = "MMO_RPG_START";
    var all_my_items = req.body;
    db.collection('misions', function(err, collection) {
        collection.find({app_id: application_id}).toArray(function(err, items) {
            //create a method to validate this -----------TODO: REF 1---------
            var misions_complete = [];
            for (var i = 0; i < items.length; i++) {
                if (hasTheItems(items[i].items_requested, all_my_items))
                    misions_complete.push(items[i]);
            }
            res.send(misions_complete);
        });
    });
};

//Odd solution, TODO: change for smarter one
var hasTheItems = function (items_requested, all_my_items)
{
    var enough = false;
    for (var i = 0; i < items_requested.length; i++) {
        for (var j = 0; j < all_my_items.length; j++) {
           enough = has_enough_of_this_item(items_requested[i], all_my_items[j]);
           if (enough) break;
        }
        if (!enough) return false;
    }
    return enough;
    //here, check each item to see if there are enough to complete the requests for the mision
    //return JSON.stringify(items_requested) == JSON.stringify(all_my_items);
};

var has_enough_of_this_item = function(item_requested, my_item)
{
   return (item_requested.name == my_item.name &&
            item_requested.quant <= my_item.quant &&
            hasThePecularities(item_requested.peculiariaties, my_item.peculiariaties));
};

var hasThePecularities = function(item_req_pecs, item_i_have_pecs)
{
    for (var prop in item_req_pecs){
        if (item_req_pecs[prop] != item_i_have_pecs[prop])
        {
            return false;
        }
    }
    return true;
};

/*--------------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
// You'd typically not find this code in a real-life app, since the database would already exist.

var populateDB = function() {
   var misions = [
    {
        app_id: "MMO_RPG_START",
        misioner_id: "1",
        mision_id: "1",
        name: "kill'em all",
        history: "History is short, just kill them",
        description: "Do you need a picture?, just kill them all",
        picture: "killeemm.jpg",
        level_required: 1,
        sub_level_required: null,
        class_required: "magical",
        second_class_required: "witch",
        coins_requested: 0,
        coins_rewarded: 800,
        experience_required: 0,
        experience_rewarded: 800,
        completed: false,
        repetable: true,
        region: "Tall Guiso",
        items_requested: [
        {
            item_id: 1,
            name:"orc head",
            quant: 20,
            peculiariaties:  {status: "without orc body", weight: 100}
        }],
        items_rewarded: [
        {
            item_id: 2,
            name: "super axe",
            quant: 1,
            peculiariaties: {damage_status: "20", item_class: "magical"}
        }]
    }
    ];

    db.collection('misions', function(err, collection) {
        collection.remove({app_id: "MMO_RPG_START"}, {safe:true}, function(err, result) {});
        collection.insert(misions, {safe:true}, function(err, result) {});
    });
};

var schema =
 {
        app_id: String.empty,
        misioner_id: String.empty,
        mision_id: String.empty,
        name: String.empty,
        history: String.empty,
        description: String.empty,
        picture: String.empty,
        level_required: 0,
        sub_level_required: 0,
        class_required: String.empty,
        second_class_required: String.empty,
        coins_requested: 0,
        coins_rewarded: 0,
        experience_required: 0,
        experience_rewarded: 0,
        completed: false,
        repetable: false,
        region: String.empty,
        items_requested: [
        {
            item_id: 0,
            name:String.empty,
            quant: 0,
            peculiariaties: {}
        }],
        items_rewarded: [
        {
            item_id: 0,
            name:String.empty,
            quant: 0,
            peculiariaties: {}
        }]
    };


text:
package com.booking.validator.connectors;

import com.booking.validator.data.Data;
import com.booking.validator.data.source.DataSource;
import com.booking.validator.data.transformation.TransformationFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by dbatheja on 12/02/20.
 *
 * This is used to have a single client connection per Data Source from Validator Config
 */
public class ActiveDataSourceConnections {
    private Map<String, DataSourceConnection> connections;
    private static final ActiveDataSourceConnections instance = new ActiveDataSourceConnections();
    private ActiveDataSourceConnections(){
        connections = new HashMap<>();
    }
    public static ActiveDataSourceConnections getInstance() { return instance; }

    public ActiveDataSourceConnections add(String name, String type, Map<String, String> configuration) {
        DataSourceConnection conn = DataSourceConnectionFactory.initConnection(type, configuration);
        if (connections.containsKey(name)){
            throw new RuntimeException("DataSource name:" + name + " already exists in active connections.");
        } else if (conn == null) {
            throw new RuntimeException("DataSource connection couldn't be established:" + name + type + configuration.toString());
        } else {
            connections.put(name, conn);
        }
        return instance;
    }

    public DataSourceConnection get(String name) {
        if (connections.containsKey(name)) {
            return connections.get(name);
        } else {
            throw new RuntimeException("DataSource connection not found for name:" + name);
        }
    }

    public Data query(DataSource source) {
        DataSourceConnection conn = get(source.getName());
        return TransformationFactory.applyTransformations(conn.query(source.getOptions()), source.getOptions().getTransformations());
    }

    public void closeAll() {
        for(DataSourceConnection conn : connections.values()) { conn.close(); }
        connections.clear();
    }

    public Map<String, DataSourceConnection> getConnections() {
        return connections;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
package org.apache.taverna.activities.externaltool.views;
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;

import org.apache.taverna.activities.externaltool.utils.Tools;
import org.apache.taverna.lang.ui.DeselectingButton;
import org.apache.taverna.lang.ui.ReadOnlyTextArea;

/**
 * @author alanrw
 *
 */
public class StaticStringPanel extends JPanel {

	private static final String STATIC_STRING_DESCRIPTION = "A fixed string can be written to the specified file.";
	private final List<ExternalToolStaticStringViewer> staticStringViewList;

	int staticGridy = 1;

	private static String[] elementLabels = new String[] {"String to copy", "To file"};

	public StaticStringPanel(final List<ExternalToolStaticStringViewer> staticStringViewList) {
		super(new BorderLayout());
		this.staticStringViewList = staticStringViewList;
		final JPanel staticEditPanel = new JPanel(new GridBagLayout());

		final GridBagConstraints staticConstraint = new GridBagConstraints();
		staticConstraint.insets = new Insets(5, 5, 5, 5);
		staticConstraint.anchor = GridBagConstraints.FIRST_LINE_START;
		staticConstraint.gridx = 0;
		staticConstraint.gridy = 0;
		staticConstraint.weightx = 0.1;
		staticConstraint.fill = GridBagConstraints.BOTH;

		staticConstraint.gridx = 0;
		synchronized (staticStringViewList) {
			for (ExternalToolStaticStringViewer staticView : staticStringViewList) {
				addStaticStringViewer(StaticStringPanel.this, staticEditPanel,
						staticView);
			}
		}

		JTextArea descriptionText = new ReadOnlyTextArea(
				STATIC_STRING_DESCRIPTION);
		descriptionText.setEditable(false);
		descriptionText.setFocusable(false);
		descriptionText.setBorder(new EmptyBorder(5, 5, 10, 5));
		this.add(descriptionText, BorderLayout.NORTH);

		this.add(new JScrollPane(staticEditPanel),
				BorderLayout.CENTER);
		JButton addStaticStringButton = new DeselectingButton("Add string",
				new AbstractAction() {
			// FIXME refactor this into a method
			public void actionPerformed(ActionEvent e) {

				ExternalToolStaticStringViewer newViewer = new ExternalToolStaticStringViewer();
				synchronized (staticStringViewList) {
					staticStringViewList.add(newViewer);
					addStaticStringViewer(StaticStringPanel.this, staticEditPanel,
							newViewer);
					staticEditPanel.revalidate();
					staticEditPanel.repaint();
				}
			}

		});

		JPanel buttonPanel = new JPanel(new BorderLayout());

		buttonPanel.add(addStaticStringButton, BorderLayout.EAST);

		this.add(buttonPanel, BorderLayout.SOUTH);

	}

	private void addStaticStringViewer(final JPanel outerPanel,
			final JPanel panel, ExternalToolStaticStringViewer viewer) {
		Tools.addViewer(panel,
				elementLabels,
				new JComponent[] {new JScrollPane(viewer.getContentField()), viewer.getValueField()},
				staticStringViewList,
				viewer,
				outerPanel);
	}

}


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>perfect-scrollbar example</title>
    <link href="../dist/css/perfect-scrollbar.css" rel="stylesheet">

Default; pageSpeed:90

Fast: pageSpeed:360

Slow: pageSpeed:30


text:
![Building](https://api.travis-ci.org/JanHuang/container.svg?branch=master)
[![Latest Stable Version](https://poser.pugx.org/fastd/container/v/stable)](https://packagist.org/packages/fastd/container) [![Total Downloads](https://poser.pugx.org/fastd/container/downloads)](https://packagist.org/packages/fastd/container) [![Latest Unstable Version](https://poser.pugx.org/fastd/container/v/unstable)](https://packagist.org/packages/fastd/container) [![License](https://poser.pugx.org/fastd/container/license)](https://packagist.org/packages/fastd/container)

Simple DI Container

### requirements

* PHP >=7.0

### installation

```
composer require "fastd/container" -vvv
```

### usage

#### using method injection

```php
$container = new FastD\Container\Container();

$container
    ->injectOn('date', new MethodInjection())
    ->withMethod('now')
    ->withArguments([
        new DateTime(),
    ]);

$obj = $container->get('date');

echo $obj->date; // (new DateTime())->format(DateTime::W3C)
```

#### using construct injection

```php
$container = new FastD\Container\Container();

$container
    ->injectOn('date', ConstructorInjection::class)
    ->withConstruct()
    ->withArguments([
        new DateTime(),
    ]);

$date = $container->get('date');

echo $obj->date; // (new DateTime())->format(DateTime::W3C)
```

#### using closure

```php
$container = new FastD\Container\Container();

$container->add('date', function () use ($container) {
    return new DateTime('now', $container->get('zone'));
});

$container->add('zone', function () {
    return new DateTimeZone('UTC');
});

$dateTime = $container->get('date');

echo $obj->date; // (new DateTime('now', new DateTimeZone("UTC")))->format(DateTime::W3C)
```

#### using DI

```php
$container = new FastD\Container\Container();

$container->add('zone', new DateTimeZone('UTC'));

$container->injectOn('date', function (DateTimeZone $dateTimeZone) {
    return new DateTime('now', $dateTimeZone);
});

$dateTimeZone = $container->get('date'); // new DateTime('now', new DateTimeZone('UTC'));
```

### Testing

```php
phpunit
```

### 贡献

非常欢迎感兴趣,愿意参与其中,共同打造更好PHP生态,Swoole生态的开发者。

如果你乐于此,却又不知如何开始,可以试试下面这些事情:

* 在你的系统中使用,将遇到的问题 [反馈](https://github.com/JanHuang/fastD/issues)。
* 有更好的建议?欢迎联系 [bboyjanhuang@gmail.com](mailto:bboyjanhuang@gmail.com) 或 [新浪微博:编码侠](http://weibo.com/ecbboyjan)。

### 联系

如果你在使用中遇到问题,请联系: [bboyjanhuang@gmail.com](mailto:bboyjanhuang@gmail.com). 微博: [编码侠](http://weibo.com/ecbboyjan)

## License MIT


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.storage.file.share.implementation.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.DateTimeRfc1123;
import com.azure.storage.file.share.models.CopyStatusType;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import java.time.OffsetDateTime;

/**
 * Defines headers for StartCopy operation.
 */
@JacksonXmlRootElement(localName = "File-StartCopy-Headers")
@Fluent
public final class FileStartCopyHeaders {
    /*
     * If the copy is completed, contains the ETag of the destination file. If
     * the copy is not complete, contains the ETag of the empty file created at
     * the start of the copy.
     */
    @JsonProperty(value = "ETag")
    private String eTag;

    /*
     * Returns the date/time that the copy operation to the destination file
     * completed.
     */
    @JsonProperty(value = "Last-Modified")
    private DateTimeRfc1123 lastModified;

    /*
     * This header uniquely identifies the request that was made and can be
     * used for troubleshooting the request.
     */
    @JsonProperty(value = "x-ms-request-id")
    private String requestId;

    /*
     * Indicates the version of the File service used to execute the request.
     */
    @JsonProperty(value = "x-ms-version")
    private String version;

    /*
     * A UTC date/time value generated by the service that indicates the time
     * at which the response was initiated.
     */
    @JsonProperty(value = "Date")
    private DateTimeRfc1123 dateProperty;

    /*
     * String identifier for this copy operation. Use with Get File or Get File
     * Properties to check the status of this copy operation, or pass to Abort
     * Copy File to abort a pending copy.
     */
    @JsonProperty(value = "x-ms-copy-id")
    private String copyId;

    /*
     * State of the copy operation identified by x-ms-copy-id. Possible values
     * include: 'pending', 'success', 'aborted', 'failed'
     */
    @JsonProperty(value = "x-ms-copy-status")
    private CopyStatusType copyStatus;

    /*
     * The errorCode property.
     */
    @JsonProperty(value = "x-ms-error-code")
    private String errorCode;

    /**
     * Get the eTag property: If the copy is completed, contains the ETag of
     * the destination file. If the copy is not complete, contains the ETag of
     * the empty file created at the start of the copy.
     *
     * @return the eTag value.
     */
    public String getETag() {
        return this.eTag;
    }

    /**
     * Set the eTag property: If the copy is completed, contains the ETag of
     * the destination file. If the copy is not complete, contains the ETag of
     * the empty file created at the start of the copy.
     *
     * @param eTag the eTag value to set.
     * @return the FileStartCopyHeaders object itself.
     */
    public FileStartCopyHeaders setETag(String eTag) {
        this.eTag = eTag;
        return this;
    }

    /**
     * Get the lastModified property: Returns the date/time that the copy
     * operation to the destination file completed.
     *
     * @return the lastModified value.
     */
    public OffsetDateTime getLastModified() {
        if (this.lastModified == null) {
            return null;
        }
        return this.lastModified.getDateTime();
    }

    /**
     * Set the lastModified property: Returns the date/time that the copy
     * operation to the destination file completed.
     *
     * @param lastModified the lastModified value to set.
     * @return the FileStartCopyHeaders object itself.
     */
    public FileStartCopyHeaders setLastModified(OffsetDateTime lastModified) {
        if (lastModified == null) {
            this.lastModified = null;
        } else {
            this.lastModified = new DateTimeRfc1123(lastModified);
        }
        return this;
    }

    /**
     * Get the requestId property: This header uniquely identifies the request
     * that was made and can be used for troubleshooting the request.
     *
     * @return the requestId value.
     */
    public String getRequestId() {
        return this.requestId;
    }

    /**
     * Set the requestId property: This header uniquely identifies the request
     * that was made and can be used for troubleshooting the request.
     *
     * @param requestId the requestId value to set.
     * @return the FileStartCopyHeaders object itself.
     */
    public FileStartCopyHeaders setRequestId(String requestId) {
        this.requestId = requestId;
        return this;
    }

    /**
     * Get the version property: Indicates the version of the File service used
     * to execute the request.
     *
     * @return the version value.
     */
    public String getVersion() {
        return this.version;
    }

    /**
     * Set the version property: Indicates the version of the File service used
     * to execute the request.
     *
     * @param version the version value to set.
     * @return the FileStartCopyHeaders object itself.
     */
    public FileStartCopyHeaders setVersion(String version) {
        this.version = version;
        return this;
    }

    /**
     * Get the dateProperty property: A UTC date/time value generated by the
     * service that indicates the time at which the response was initiated.
     *
     * @return the dateProperty value.
     */
    public OffsetDateTime getDateProperty() {
        if (this.dateProperty == null) {
            return null;
        }
        return this.dateProperty.getDateTime();
    }

    /**
     * Set the dateProperty property: A UTC date/time value generated by the
     * service that indicates the time at which the response was initiated.
     *
     * @param dateProperty the dateProperty value to set.
     * @return the FileStartCopyHeaders object itself.
     */
    public FileStartCopyHeaders setDateProperty(OffsetDateTime dateProperty) {
        if (dateProperty == null) {
            this.dateProperty = null;
        } else {
            this.dateProperty = new DateTimeRfc1123(dateProperty);
        }
        return this;
    }

    /**
     * Get the copyId property: String identifier for this copy operation. Use
     * with Get File or Get File Properties to check the status of this copy
     * operation, or pass to Abort Copy File to abort a pending copy.
     *
     * @return the copyId value.
     */
    public String getCopyId() {
        return this.copyId;
    }

    /**
     * Set the copyId property: String identifier for this copy operation. Use
     * with Get File or Get File Properties to check the status of this copy
     * operation, or pass to Abort Copy File to abort a pending copy.
     *
     * @param copyId the copyId value to set.
     * @return the FileStartCopyHeaders object itself.
     */
    public FileStartCopyHeaders setCopyId(String copyId) {
        this.copyId = copyId;
        return this;
    }

    /**
     * Get the copyStatus property: State of the copy operation identified by
     * x-ms-copy-id. Possible values include: 'pending', 'success', 'aborted',
     * 'failed'.
     *
     * @return the copyStatus value.
     */
    public CopyStatusType getCopyStatus() {
        return this.copyStatus;
    }

    /**
     * Set the copyStatus property: State of the copy operation identified by
     * x-ms-copy-id. Possible values include: 'pending', 'success', 'aborted',
     * 'failed'.
     *
     * @param copyStatus the copyStatus value to set.
     * @return the FileStartCopyHeaders object itself.
     */
    public FileStartCopyHeaders setCopyStatus(CopyStatusType copyStatus) {
        this.copyStatus = copyStatus;
        return this;
    }

    /**
     * Get the errorCode property: The errorCode property.
     *
     * @return the errorCode value.
     */
    public String getErrorCode() {
        return this.errorCode;
    }

    /**
     * Set the errorCode property: The errorCode property.
     *
     * @param errorCode the errorCode value to set.
     * @return the FileStartCopyHeaders object itself.
     */
    public FileStartCopyHeaders setErrorCode(String errorCode) {
        this.errorCode = errorCode;
        return this;
    }
}


text:
package show

import (
	"context"
	"strconv"

	"go-common/app/interface/main/app-show/model"
	"go-common/app/interface/main/app-show/model/show"
	locmdl "go-common/app/service/main/location/model"
	"go-common/library/log"
)

// cpmRecommend
func (s *Service) cpmRecommend(c context.Context, mid int64, build int, buvid, resource, network, mobiApp, device, ipaddr string) (sis map[int]*show.Item) {
	if _, ok := s.cpmRcmmndMid[mid]; !ok && (mid == 0 || int(mid)%100 >= s.cpmRcmmndNum) && !s.cpmRcmmndAll {
		return
	}
	var (
		info                    *locmdl.Info
		country, province, city string
		err                     error
	)
	if info, err = s.loc.Info(c, ipaddr); err != nil {
		log.Warn("s.loc.Info(%v) error(%v)", ipaddr, err)
		err = nil
	}
	if info != nil {
		country = info.Country
		province = info.Province
		city = info.Province
	}
	adr, err := s.ad.ADRequest(c, mid, build, buvid, resource, ipaddr, country, province, city, network, mobiApp, device, s.adIsPost)
	if err != nil {
		log.Error("s.ad.ADRequest error(%v)", err)
		return
	}
	sis = map[int]*show.Item{}
	sAdis := adr.ADIndexs[resource]
	if len(sAdis) == 0 {
		log.Info("mobi_app:%v-build:%v-resource:%v-is_ad_loc:%v", mobiApp, build, resource, false)
		return
	}
	var aids []int64
	for sidStr, adi := range sAdis {
		sid, _ := strconv.Atoi(sidStr)
		var si = &show.Item{
			IsAdLoc:     true,
			IsAd:        adi.IsAd,
			IsAdReplace: false,
			CmMark:      adi.CmMark,
			Rank:        adi.Index,
			SrcId:       sid,
			RequestId:   adr.RequestID,
			ClientIp:    ipaddr,
		}
		if adInfo := adi.Info; adInfo != nil {
			aids = append(aids, adInfo.CreativeContent.VideoID)
			// si
			si.Goto = model.GotoAv
			si.Param = strconv.FormatInt(adInfo.CreativeContent.VideoID, 10)
			si.URI = model.FillURI(model.GotoAv, si.Param, nil)
			si.Title = adInfo.CreativeContent.Title
			si.Cover = model.CoverURL(adInfo.CreativeContent.ImageURL)
			si.IsAdReplace = true
			si.AdCb = adInfo.AdCb
			si.CreativeId = adInfo.CreativeID
			si.ShowUrl = adInfo.CreativeContent.ShowURL
			si.ClickUrl = adInfo.CreativeContent.ClickURL
		}
		sis[si.Rank] = si
		log.Info("mobi_app:%v-build:%v-resource:%v-is_ad_loc:%v", mobiApp, build, resource, true)
	}
	if len(aids) == 0 {
		return
	}
	as, err := s.arc.ArchivesPB(c, aids)
	if err != nil {
		log.Error("s.arc.ArchivesPB(%v) error(%v)", aids, err)
		return
	}
	for _, si := range sis {
		aid, _ := strconv.ParseInt(si.Param, 10, 64)
		if a, ok := as[aid]; ok && a != nil {
			si.Play = int(a.Stat.View)
			si.Danmaku = int(a.Stat.Danmaku)
			if si.Title == "" {
				si.Title = a.Title
			}
			if si.Cover == "" {
				si.Cover = model.CoverURL(a.Pic)
			}
		}
	}
	return
}


text:
<?php

$confDir = dirname(dirname(__DIR__)) . '/tests/conf';
var_dump($confDir);
$map = [
    'path' => 'name',
    'dbname' => 'name',
    'password' => 'pass',
    'driver' => 'adapter'
];
$defaults = require $confDir . '/defaults.php';

$contexts = array_filter(scandir($confDir . '/contexts'), function ($context) {
    if (strpos($context, '.php')) {
        return true;
    }
});

foreach($contexts as $key => &$file) {
    if (substr($file, 0, 1) == '.') {
        unset($contexts[$key]);
        continue;
    }

    $context         = substr($file, 0, -4);
    $contextOverride = (require $confDir . '/contexts/' . $file);

    $contextConf     = array_replace_recursive($defaults, $contextOverride);
    foreach ($contextConf['master_db'] as $key => $value) {
        if (isset($map[$key])) {
            $dbConf[$context][$map[$key]] = $value;
        } else {
            $dbConf[$context][$key] = $value;
        }
    }
    $dbConf[$context]['adapter'] = str_replace('pdo_', '', $dbConf[$context]['adapter']);
    $dbConf[$context]['name'] = str_replace('.sqlite3', '', $dbConf[$context]['name']);
}

$migrationConf = [

    'paths' => [
        'migrations' => dirname(dirname(__DIR__)) . '/data/migrations'
    ],
    'environments' => [
        'default_migration_table' => 'phinxlog',
        'default_database' => 'dev',
    ]
];

$migrationConf['environments'] += $dbConf;

return $migrationConf;


text:
NSString * const kMNTPullToReactKey = @"kMNTPullToReactKey";

@implementation UITableView (MNTPullToReact)

- (void)setReactControl:(MNTPullToReactControl *)reactControl
{
    MNTPullToReactControl *_reactControl = self.reactControl;
    [_reactControl removeFromScrollView];
    objc_setAssociatedObject(self, &kMNTPullToReactKey, reactControl, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [reactControl reactFromScrollView:self];
}

- (MNTPullToReactControl *)reactControl
{
    return (MNTPullToReactControl *)objc_getAssociatedObject(self, &kMNTPullToReactKey);
}

@end


text:
ConsoleAppLauncher is a Windows Console Application wrapper for .NET written in C#.

It captures all the output generated in the console and provides simple
interface to start and close console application. The ConsoleOutput
event is fired every time when a new line is written by the console to
standard/error output. The lines are queued and guaranteed to follow the
output order.

For rationale [see this SO question](http://stackoverflow.com/questions/186822/capturing-console-output-from-a-net-application-c).

# Samples

Usage samples are available in the ConsoleAppLauncher.Samples project.

        // Run simplest shell command and return its output.
        public static string GetWindowsVersion()
        {
            return ConsoleApp.Run("cmd", "/c ver").Output.Trim();
        }

        // Run ipconfig.exe and return matching line.
        public static string GetIpAddress()
        {
            var output = ConsoleApp.Run("ipconfig").Output;
            var match = Regex.Match(output, "IPv4 Address.*: (?<addr>.*)");
            return match.Success ? match.Groups["addr"].Value : "<undefined>";
        }

        // Run ping.exe asynchronously and return roundtrip times in a callback
	// sample call:
        //    Action<string> action = Console.WriteLine;
        //    PingUrl("google.com", action);
        public static void PingUrl(string url, Action<string> replyHandler)
        {
            var regex = new Regex("(time=|Average = )(?<time>.*?ms)", RegexOptions.Compiled);
            var app = new ConsoleApp("ping", url);
            app.ConsoleOutput += (o, args) =>
            {
                var match = regex.Match(args.Line);
                if (match.Success)
                {
                    var roundtripTime = match.Groups["time"].Value;
                    replyHandler(roundtripTime);
                }
            };
            app.Run();
            app.WaitForExit();
        }

        // Get Windows firewall rule
        public static string GetFirewallRule(string ruleName)
        {
            var cmdLine = string.Format("advfirewall firewall show rule \"{0}\" verbose", ruleName);
            return ConsoleApp.Run("netsh", cmdLine).Output.Trim();
        }

# License

This library is released under The MIT License (MIT).

	Copyright (c) 2013 Slava Guzenko

	Permission is hereby granted, free of charge, to any person obtaining a
	copy of this software and associated documentation files (the
	"Software"), to deal in the Software without restriction, including
	without limitation the rights to use, copy, modify, merge, publish,
	distribute, sublicense, and/or sell copies of the Software, and to
	permit persons to whom the Software is furnished to do so, subject to
	the following conditions:

	The above copyright notice and this permission notice shall be included
	in all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
	OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
	MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
	IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
	CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
	TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
	SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
package atomic

// Error is an atomic type-safe wrapper for error values.
type Error struct {
	_ nocmp // disallow non-atomic comparison

	v Value
}

var _zeroError error

// NewError creates a new Error.
func NewError(val error) *Error {
	x := &Error{}
	if val != _zeroError {
		x.Store(val)
	}
	return x
}

// Load atomically loads the wrapped error.
func (x *Error) Load() error {
	return unpackError(x.v.Load())
}

// Store atomically stores the passed error.
func (x *Error) Store(val error) {
	x.v.Store(packError(val))
}

// CompareAndSwap is an atomic compare-and-swap for error values.
func (x *Error) CompareAndSwap(old, new error) (swapped bool) {
	return x.v.CompareAndSwap(packError(old), packError(new))
}

// Swap atomically stores the given error and returns the old
// value.
func (x *Error) Swap(val error) (old error) {
	return unpackError(x.v.Swap(packError(val)))
}


text:
from flask import Flask, request
import json, requests, random, os
app = Flask(__name__)
with open('config.json', 'r') as f:
	config = json.loads(f.read())
def generate_name(length=5):
	chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
	return ''.join( random.choice(chars) for i in range(length))
def allowed_file(name):
    if '.' not in name:
    	return False
    ext = name.rsplit('.', 1)[1].lower()
    if ext in config['allowed_extensions']:
    	return ext
    else:
    	return False
@app.route(config['route'], methods=["POST"])
def index():
	urls = []
	filenames = []
	for attachment in request.files.values():
		ext = allowed_file(attachment.filename)
		if ext:
			newFilename = generate_name() + "." + ext
			attachment.save(config['images_folder'] + newFilename)
			urls.append(config['hosting_domain'] + newFilename)
			filenames.append(attachment.filename)
	if not urls:
		return 'ERROR'
	if not request.form.get('subject'):
		subject = ",".join(filenames)
	else:
		subject = "Re: " + request.form.get('subject')
	recipients = str(request.form.get("To")) + ',' + str(request.form.get("Cc"))
	recipients = recipients.replace(' ', '').split(',')
	filteredRecipients = []
	for r in recipients:
		if r and r != request.form.get("To") and r != request.form.get("from"):
			filteredRecipients.append(r)
	maildata = {"from": config['from_email'], "to": request.form["from"], "cc": filteredRecipients, "subject": subject}
	messageHTML = "Your images were successfully uploaded :
"
	messageTXT = "Your images were successfully uploaded : \r\n"
	for i in range(len(filenames)):
		messageHTML += filenames[i] + " : " + urls[i] + "
"
		messageTXT += filenames[i] + " : " + urls[i] + "\r\n"
	maildata['html'] = messageHTML
	maildata['text'] = messageTXT
	r = requests.post("https://api.mailgun.net/v3/" + config['mailgun_domain'] + "/messages", auth=("api", config["mailgun_api"]), data=maildata)
	return 'OK'

if __name__ == '__main__':
	app.run(host=config['ip'], port=config['port'])


text:
version=16
function circleci_test(){
    # install conda
    WORK=ambertools-binary-build
    bash $HOME/$WORK/amber$version/AmberTools/src/configure_python --prefix $HOME
    export PATH=$HOME/miniconda/bin:$PATH
    for tarfile in `ls $HOME/TMP/amber-conda-bld/linux-64/ambertools-*.tar.bz2`; do
        python $HOME/$WORK/amber$version/AmberTools/src/conda_tools/test_multiple_pythons.py $tarfile
    done
}

circleci_test


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('annotation', '0003_make_annotation_quote_and_text_optional'),
    ]

    operations = [
        migrations.AlterField(
            model_name='annotation',
            name='anchor_languages',
            field=models.ManyToManyField(blank=True, related_name='_annotation_anchor_languages_+', to='books.Language'),
        ),
        migrations.AlterField(
            model_name='annotation',
            name='languages',
            field=models.ManyToManyField(blank=True, to='books.Language'),
        ),
        migrations.AlterField(
            model_name='annotation',
            name='quote',
            field=models.TextField(),
        ),
        migrations.AlterField(
            model_name='annotation',
            name='subjects',
            field=models.ManyToManyField(blank=True, to='books.Subject'),
        ),

    ]


text:
package org.hbird.business.groundstation.base;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;

import org.hbird.business.groundstation.configuration.GroundStationDriverConfiguration;
import org.hbird.exchange.groundstation.Track;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

/**
 *
 */
@RunWith(MockitoJUnitRunner.class)
public class GroundStationCommandFilterTest {

    private static final String ID = "GS_ID";

    @Mock
    private GroundStationDriverConfiguration config;

    @Mock
    private Track track;

    private GroundStationCommandFilter groundStationCommandFilter;

    private InOrder inOrder;

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception {
        groundStationCommandFilter = new GroundStationCommandFilter(config);
        inOrder = inOrder(config, track);
        when(config.getGroundstationId()).thenReturn(ID);
    }

    @Test
    public void testAcceptTrack() throws Exception {
        when(track.getDestination()).thenReturn(ID);
        assertTrue(groundStationCommandFilter.acceptTrack(track));
        inOrder.verify(track, times(1)).getDestination();
        inOrder.verify(config, times(1)).getGroundstationId();
        inOrder.verifyNoMoreInteractions();
    }

    @Test
    public void testDenyTrack() throws Exception {
        when(track.getDestination()).thenReturn("!" + ID);
        assertFalse(groundStationCommandFilter.acceptTrack(track));
        inOrder.verify(track, times(1)).getDestination();
        inOrder.verify(config, times(1)).getGroundstationId();
        inOrder.verifyNoMoreInteractions();
    }
}


text:
#include <stdio.h>

#include "fann.h"

int main()
{
	const unsigned int num_layers = 3;
	const unsigned int num_neurons_hidden = 96;
	const float desired_error = (const float) 0.001;
	struct fann *ann;
	struct fann_train_data *train_data, *test_data;

	float momentum;

	train_data = fann_read_train_from_file("../../datasets/robot.train");
	test_data = fann_read_train_from_file("../../datasets/robot.test");

	for ( momentum = 0.0f; momentum < 0.7f; momentum += 0.1f )
	{
		printf("============= momentum = %f =============\n", momentum);

		ann = fann_create_standard(num_layers,
						train_data->num_input, num_neurons_hidden, train_data->num_output);

		fann_set_training_algorithm(ann, FANN_TRAIN_INCREMENTAL);

		fann_set_learning_momentum(ann, momentum);

		fann_train_on_data(ann, train_data, 2000, 500, desired_error);

		printf("MSE error on train data: %f\n", fann_test_data(ann, train_data));
		printf("MSE error on test data : %f\n", fann_test_data(ann, test_data));

		fann_destroy(ann);
	}

	fann_destroy_train(train_data);
	fann_destroy_train(test_data);
	return 0;
}


text:
//
//  NSObject+Model.m
//  RuntimeTest
//
//  Created by 赵宏亚 on 2017/10/13.
//  Copyright © 2017年 赵宏亚. All rights reserved.
//

#import "NSObject+Model.h"
#import <objc/runtime.h>

@implementation NSObject (Model)

/**
 可以进一步思考:
 如何识别基本数据类型的属性并处理空(nil,null)值的处理
 json中嵌套json(Dict或Array)的处理
 */

- (instancetype)initWithDict:(NSDictionary *)dict {

    if (self = [self init]) {
//        1. 获取类的属性即属性对应的类型
        NSMutableArray *keys = [NSMutableArray array];
        NSMutableArray *attributes = [NSMutableArray array];

        unsigned int outCount;
//        2. 获取属性列表
        objc_property_t *properties = class_copyPropertyList([self class], &outCount);

        for (int i = 0; i < outCount; i ++) {
            // 遍历出单一属性
            objc_property_t property = properties[i];
            // 获取属性名
            NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
            // 将所有的属性名放到key中
            [keys addObject:propertyName];
            // 通过property_getAttributes函数可以获得属性的名字和@endcode编码
            NSString *propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];

            // 将属性放入到属性数组中
            [attributes addObject:propertyAttribute];
        }
        // 立即释放properties指向的内存
        free(properties);

        // 根据类型给属性赋值
        for (NSString *key in keys) {
            if ([dict valueForKey:key] == nil) {
                continue;
            } else {
                [self setValue:[dict valueForKey:key] forKey:key];
            }
        }
    }
    return self;

}

@end


text:
//
//  NSDate+Extension.m
//
//  Created by liLei on 14-10-15.
//  Copyright (c) 2014年 liLei. All rights reserved.
//

#import "NSDate+Extension.h"

@implementation NSDate (Extension)
#pragma mark - 是否为今天
- (BOOL)isToday
{
    NSCalendar *canlendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear;
    // 1.获得当前时间的年、月、日
    NSDateComponents *nowComponents = [canlendar components:unit fromDate:[NSDate date]];

    // 2.获得self的年、月、日
    NSDateComponents *selfComponents = [canlendar components:unit fromDate:self];

    return (selfComponents.year == nowComponents.year)
        && (selfComponents.month == nowComponents.month)
        && (selfComponents.day == nowComponents.day);
}

#pragma mark - 是否为昨天
- (BOOL)isYesterday
{
    // 获取当前日期的年月日
    NSDate *nowDate = [[NSDate date] dateWithYMD];

    // 获取self的年月日
    NSDate *selfDate = [self dateWithYMD];

    // 计算nowDate和selfDate的差距
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [calendar components:NSCalendarUnitDay fromDate:selfDate toDate:nowDate options:0];

    return dateComponents.day == 1;
}

#pragma mark - 返回一个只有年月日的日期
- (NSDate *)dateWithYMD
{
    NSDateFormatter *dateFmt = [[NSDateFormatter alloc] init];
    dateFmt.dateFormat = @"yyyy-MM-dd";
    NSString *selfStr = [dateFmt stringFromDate:self];
    return [dateFmt dateFromString:selfStr];
}

#pragma mark - 是否为今年
- (BOOL)isThisYear
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitYear;

    // 1.获得当前日期的年
    NSDateComponents *nowComponents = [calendar components:unit fromDate:[NSDate date]];

    // 2.获得self时间的年
    NSDateComponents *selfComponents = [calendar components:unit fromDate:self];

    return nowComponents.year == selfComponents.year;
}

#pragma mark - 获得与当前日间的差距
- (NSDateComponents *)deltaWithNow
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    return [calendar components:unit fromDate:self toDate:[NSDate date] options:0];
}

#pragma mark - 友好显示日期
+ (NSString *)getFormatTime:(NSString *)dateStr
{
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:dateStr.doubleValue/1000];

    // 1.将服务器返回的时间格式化为NSDate
    // 创建时间格式化类
    NSDateFormatter *DateF = [[NSDateFormatter alloc] init];
    DateF.locale = [NSLocale currentLocale];
    // 设置时间格式化字符串
    DateF.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";
    // 利用时间格式化类将字符串格式化为NSDate
    NSDate *createdTime = [DateF dateFromString:[DateF stringFromDate:confromTimesp]];
    // 2.判断发布的时间
    if ([createdTime isThisYear]) {
        if ([createdTime isToday]) {
            NSDateComponents *cmps = [createdTime deltaWithNow];
            if (cmps.hour >= 1) {
                return [NSString stringWithFormat:@"%ld小时前",(long)cmps.hour];;
            } else if (cmps.minute > 1) {
                return [NSString stringWithFormat:@"%ld分钟前",(long)cmps.minute];
            } else {
                return @"刚刚";
            }
        } else if ([createdTime isYesterday]) {
            DateF.dateFormat = @"昨天";// @"昨天 HH时mm分";
            return [DateF stringFromDate:createdTime];
        } else {
            DateF.dateFormat = @"MM月dd日"; //@"MM月dd日 HH分mm秒";
            return [DateF stringFromDate:createdTime];
        }
    } else {
        DateF.dateFormat = @"yyyy年MM月dd日";// @"yyyy年MM月dd日 HH时mm分";
        return [DateF stringFromDate:createdTime];
    }
}
+ (NSString *)getContactFormatTime:(NSString *)dateStr
{
    // 1.将服务器返回的时间格式化为NSDate
    // 创建时间格式化类
    NSDateFormatter *DateF = [[NSDateFormatter alloc] init];
    DateF.locale = [NSLocale currentLocale];
    // 设置时间格式化字符串
    DateF.dateFormat = @"yyyy-MM-dd";
    // 利用时间格式化类将字符串格式化为NSDate
    NSDate *createdTime = [DateF dateFromString:dateStr];
    // 2.判断发布的时间
    if ([createdTime isThisYear]) {
        if ([createdTime isToday]) {
            return @"今天";
        } else if ([createdTime isYesterday]) {
//            DateF.dateFormat = @"昨天 HH时mm分";
            return @"昨天";//[DateF stringFromDate:createdTime];
        } else {
            DateF.dateFormat = @"MM月dd日";
            return [DateF stringFromDate:createdTime];
        }
    } else {
        DateF.dateFormat = @"yyyy年MM月dd日";
        return [DateF stringFromDate:createdTime];
    }

}

/**
 *  获取当前时间戳
 */
+ (NSString *)getNowTimeStamp
{
    // 获取当前时间
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh-Hant"];
    fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS Z";
    NSString *date = [fmt stringFromDate:[NSDate date]];
//    Log(@"OC当前时间:%@",date);

    // 将当前时间转时间戳
    NSString *timeStamp = [NSString stringWithFormat:@"%f",[[fmt dateFromString:date] timeIntervalSince1970]* 1000];

    // 截取字符串
    NSRange range = [timeStamp rangeOfString:@"."];
    return [timeStamp substringToIndex:range.location];
}

/**
 *  格式化日期(例:yyyy-MM-dd->yyyy年MM月dd)
 */
+ (NSString *)formatterDate1:(NSString *)dateStr
{
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh-hans"];
    fmt.dateFormat = @"yyyy-MM-dd";
    NSDate *date = [fmt dateFromString:dateStr];
    fmt.dateFormat = @"MM月dd日";

    return [fmt stringFromDate:date];
}

/**
 *  格式化日期(例:yyyy年MM月dd日->yyyyMMdd)
 */
+ (NSString *)formatterDate2:(NSString *)dateStr
{
    NSDateFormatter *dateFmt = [[NSDateFormatter alloc] init];
    dateFmt.locale = [NSLocale currentLocale];
    dateFmt.dateFormat = @"yyyy年MM月dd日";
    NSDate *date = [dateFmt dateFromString:dateStr];
    dateFmt.dateFormat = @"yyyyMMdd";

    return [dateFmt stringFromDate:date];
}

/**
 *  将服务器返回的字符型日期转为NSDate(例:20150412/2015-04-12 00:00:00)
 */
+ (NSDate *)formatterDateString:(NSString *)dateStr
{
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [NSLocale currentLocale];

    NSDate *date = nil;

    fmt.dateFormat = @"yyyyMMdd";
    date = [fmt dateFromString:dateStr];

    // 安全判断
    if (!date) {

        fmt.dateFormat = @"yyyy-MM-dd";
        date = [fmt dateFromString:dateStr];
    }

    if (!date) {

        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        date = [fmt dateFromString:dateStr];
    }

    return date;
}

//计算  距离现在的时间
+ (NSString *)getUTCFormateDate:(NSString *)newsDate
{
    //          newsDate = @"2015-08-15 11:01";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM月dd日 HH:mm"];

//    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
//    [dateFormatter setTimeZone:timeZone];

    NSDate* current_date = [NSDate date];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:newsDate.doubleValue/1000];

    NSTimeInterval time=[current_date timeIntervalSinceDate:confromTimesp];//间隔的秒数

//    NSString *confromTimespStr = [dateFormatter stringFromDate:confromTimesp];
//    Log(@"confromTimespStr =  %@",confromTimespStr);

    int month=((int)time)/(3600*24*30);
    int days=((int)time)/(3600*24);
    int hours=((int)time)%(3600*24)/3600;
    int minute=((int)time)%(3600*24)/60;
//    Log(@"time=%f",(double)time);

    NSString *dateContent;
//    NSArray *array = [confromTimespStr componentsSeparatedByString:@" "];

    if(month!=0){

        if ([confromTimesp isThisYear])
        {
            [dateFormatter setDateFormat:@"MM月d日"];
        }
        else
        {
            [dateFormatter setDateFormat:@"yyyy年MM月d日"];
        }
        NSString *dateStr = [dateFormatter stringFromDate:confromTimesp];

//        dateContent = [NSString  stringWithFormat:@"%@",[array objectAtIndex:0]];
        return dateStr;

    } else if (days!=0){

        if (days ==1) {

            dateContent = [NSString stringWithFormat:@"%@",@"昨天"];
            return dateContent;
        }else if (days ==2)
        {
            dateContent = [NSString stringWithFormat:@"%@",@"2天前"];
            return dateContent;

        }else
        {
            if ([confromTimesp isThisYear])
            {
                [dateFormatter setDateFormat:@"MM月d日"];
            }
            else
            {
                [dateFormatter setDateFormat:@"yyyy年MM月d日"];
            }
            NSString *dateStr = [dateFormatter stringFromDate:confromTimesp];
            return dateStr;
//            dateContent = [NSString  stringWithFormat:@"%@",[array objectAtIndex:0]];
//            return dateContent;

        }

    }if(hours!=0){
        dateContent = [NSString stringWithFormat:@"%@%i%@",@"",hours,@"小时前"];
        return dateContent;

    }else if(minute !=0){
        dateContent = [NSString stringWithFormat:@"%@%i%@",@"",minute,@"分钟前"];
        return dateContent;

    }else
    {
        dateContent =@"刚刚";
        return dateContent;
    }

    }

+ (NSString *)getYMDFromTimestamp:(NSString *)timestamp
                       isShowYear:(BOOL)show
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp.doubleValue/1000];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    if ([date isThisYear])
    {
        [dateFormatter setDateFormat:@"MM月d日"];
    }
    else
    {
        [dateFormatter setDateFormat:@"yyyy年MM月d日"];
    }

    if (show)
    {
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }

    NSString *dateStr = [dateFormatter stringFromDate:date];

    return dateStr;
}

/**
 *  格式化时间戳为年月日
 */
//+ (NSString *)getYMDFromTimestamp:(NSString *)timestamp
//{
//    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp.integerValue/1000];
//
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    if ([date isThisYear])
//    {
//        [dateFormatter setDateFormat:@"MM月dd日"];
//    }
//    else
//    {
//        [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
//    }
//
//    NSString *dateStr = [dateFormatter stringFromDate:date];
//
//    return dateStr;
//}

//计算  距离现在的时间 不显示昨天今天 明天 只显示日期和时间
+ (NSString *)getUTCFormateDateJustTime:(NSString *)newsDate
{
    //          newsDate = @"2015-08-15 11:01";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM月d日 HH:mm"];

    NSTimeInterval timeInterval = [newsDate doubleValue]/1000;
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timeInterval];

   if([confromTimesp isToday]){
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:newsDate.doubleValue/1000];

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm"];
        NSString *dateStr = [dateFormatter stringFromDate:date];
        return dateStr;
    }else{

        if ([confromTimesp isThisYear])
        {
            [dateFormatter setDateFormat:@"MM月dd日 HH:mm"];
        }
        else
        {
            [dateFormatter setDateFormat:@"yyyy年MM月d日 HH:mm"];
        }
        NSString *dateStr = [dateFormatter stringFromDate:confromTimesp];

        return dateStr;
    }

}

@end


text:
package com.opengamma.masterdb.security.hibernate.index;

import java.util.Map;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;

import com.opengamma.masterdb.security.hibernate.ExternalIdBean;
import com.opengamma.masterdb.security.hibernate.TenorBean;

/**
 * A Hibernate bean representation of {@link IborIndexBean}.
 */
@BeanDefinition
public class IborIndexBean extends IndexBean {
  @PropertyDefinition
  private TenorBean _tenor;
  @PropertyDefinition
  private ExternalIdBean _conventionId;

  @Override
  public boolean equals(final Object other) {
    if (!(other instanceof IborIndexBean)) {
      return false;
    }
    final IborIndexBean index = (IborIndexBean) other;
    return new EqualsBuilder()
      .append(getId(), index.getId())
      .append(getDescription(), index.getDescription())
      .append(getTenor(), index.getTenor())
      .append(getConventionId(), index.getConventionId())
      .isEquals();
  }

  @Override
  public int hashCode() {
    return new HashCodeBuilder()
      .append(getDescription())
      .append(getTenor())
      .append(getConventionId())
      .toHashCode();
  }
  //------------------------- AUTOGENERATED START -------------------------
  ///CLOVER:OFF
  /**
   * The meta-bean for {@code IborIndexBean}.
   * @return the meta-bean, not null
   */
  public static IborIndexBean.Meta meta() {
    return IborIndexBean.Meta.INSTANCE;
  }

  static {
    JodaBeanUtils.registerMetaBean(IborIndexBean.Meta.INSTANCE);
  }

  @Override
  public IborIndexBean.Meta metaBean() {
    return IborIndexBean.Meta.INSTANCE;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the tenor.
   * @return the value of the property
   */
  public TenorBean getTenor() {
    return _tenor;
  }

  /**
   * Sets the tenor.
   * @param tenor  the new value of the property
   */
  public void setTenor(TenorBean tenor) {
    this._tenor = tenor;
  }

  /**
   * Gets the the {@code tenor} property.
   * @return the property, not null
   */
  public final Property<TenorBean> tenor() {
    return metaBean().tenor().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the conventionId.
   * @return the value of the property
   */
  public ExternalIdBean getConventionId() {
    return _conventionId;
  }

  /**
   * Sets the conventionId.
   * @param conventionId  the new value of the property
   */
  public void setConventionId(ExternalIdBean conventionId) {
    this._conventionId = conventionId;
  }

  /**
   * Gets the the {@code conventionId} property.
   * @return the property, not null
   */
  public final Property<ExternalIdBean> conventionId() {
    return metaBean().conventionId().createProperty(this);
  }

  //-----------------------------------------------------------------------
  @Override
  public IborIndexBean clone() {
    return JodaBeanUtils.cloneAlways(this);
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(96);
    buf.append("IborIndexBean{");
    int len = buf.length();
    toString(buf);
    if (buf.length() > len) {
      buf.setLength(buf.length() - 2);
    }
    buf.append('}');
    return buf.toString();
  }

  @Override
  protected void toString(StringBuilder buf) {
    super.toString(buf);
    buf.append("tenor").append('=').append(JodaBeanUtils.toString(getTenor())).append(',').append(' ');
    buf.append("conventionId").append('=').append(JodaBeanUtils.toString(getConventionId())).append(',').append(' ');
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code IborIndexBean}.
   */
  public static class Meta extends IndexBean.Meta {
    /**
     * The singleton instance of the meta-bean.
     */
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code tenor} property.
     */
    private final MetaProperty<TenorBean> _tenor = DirectMetaProperty.ofReadWrite(
        this, "tenor", IborIndexBean.class, TenorBean.class);
    /**
     * The meta-property for the {@code conventionId} property.
     */
    private final MetaProperty<ExternalIdBean> _conventionId = DirectMetaProperty.ofReadWrite(
        this, "conventionId", IborIndexBean.class, ExternalIdBean.class);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
        this, (DirectMetaPropertyMap) super.metaPropertyMap(),
        "tenor",
        "conventionId");

    /**
     * Restricted constructor.
     */
    protected Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case 110246592:  // tenor
          return _tenor;
        case 1520979052:  // conventionId
          return _conventionId;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public BeanBuilder<? extends IborIndexBean> builder() {
      return new DirectBeanBuilder<IborIndexBean>(new IborIndexBean());
    }

    @Override
    public Class<? extends IborIndexBean> beanType() {
      return IborIndexBean.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return _metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code tenor} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<TenorBean> tenor() {
      return _tenor;
    }

    /**
     * The meta-property for the {@code conventionId} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<ExternalIdBean> conventionId() {
      return _conventionId;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case 110246592:  // tenor
          return ((IborIndexBean) bean).getTenor();
        case 1520979052:  // conventionId
          return ((IborIndexBean) bean).getConventionId();
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      switch (propertyName.hashCode()) {
        case 110246592:  // tenor
          ((IborIndexBean) bean).setTenor((TenorBean) newValue);
          return;
        case 1520979052:  // conventionId
          ((IborIndexBean) bean).setConventionId((ExternalIdBean) newValue);
          return;
      }
      super.propertySet(bean, propertyName, newValue, quiet);
    }

  }

  ///CLOVER:ON
  //-------------------------- AUTOGENERATED END --------------------------
}


text:
/**
 * Created by krause on 2016-07-06.
 */
"use strict";

var jkjs;
if(typeof module !== "undefined") {
  jkjs = {};
  module.exports = jkjs;
} else {
  window.jkjs = window.jkjs || {}; // init namespace
  jkjs = window.jkjs;
}

jkjs.Cell = function(_init) {
  var that = this;
  var value = null;
  var oldValue = null;

  var eq = function(a, b) {
    return Object.is(a, b);
  };
  this.equalFunction = function(_) {
    if(!arguments.length) return eq;
    eq = _;
  }; // equalFunction

  var changePs = {};
  var changePrimed = false;
  function primeChange() {
    if(changePrimed) return;
    setTimeout(function() {
      // gather listeners and reset values beforehand to
      // have defined behavior if some Cell methods are
      // called during execution of listeners
      changePrimed = false;
      var same = eq(oldValue, value);
      var listeners = Object.keys(changePs).filter(function(ix) {
        return !same || changePs[ix] > 1;
      }).map(function(ix) {
        return changeListeners[ix];
      });
      changePs = {};
      listeners.forEach(function(l) {
        l(value, oldValue, that);
      });
    }, 0);
    changePrimed = true;
  }

  var updatePs = {};
  var updatePrimed = false;
  function primeUpdate() {
    if(updatePrimed) return;
    setTimeout(function() {
      // gather listeners and reset values beforehand to
      // have defined behavior if some Cell methods are
      // called during execution of listeners
      updatePrimed = false;
      var listeners = Object.keys(updatePs).map(function(ix) {
        return updateListeners[ix];
      });
      updatePs = {};
      listeners.forEach(function(l) {
        l(value, that);
      });
    }, 0);
    updatePrimed = true;
  }

  this.silentSet = function(v) {
    value = v;
  };

  function set(v) {
    if(!changePrimed) {
      oldValue = value;
    }
    value = v;
    if(changeListeners.length && !eq(oldValue, value)) {
      changeListeners.forEach(function(_, ix) {
        changePs[ix] = changePs[ix] || 1;
      });
      primeChange();
    }
    updateListeners.forEach(function(_, ix) {
      updatePs[ix] = true;
    });
    primeUpdate();
  };

  function get() {
    return value;
  };

  var updateListeners = [];
  this.addUpdateListener = function(l) {
    updatePs[updateListeners.length] = true;
    updateListeners.push(l);
    primeUpdate();
    return l;
  };
  this.removeUpdateListener = function(l) {
    var pos = 0;
    var oldUpdatePs = updatePs;
    updatePs = {};
    updateListeners = updateListeners.filter(function(ll, ix) {
      var allow = !Object.is(ll, l);
      if(allow) {
        if(oldUpdatePs[ix]) {
          updatePs[pos] = true;
        }
        pos += 1;
      }
      return allow;
    });
  };

  var changeListeners = [];
  this.addChangeListener = function(l) {
    changePs[changeListeners.length] = 2;
    changeListeners.push(l);
    primeChange();
    return l;
  };
  this.removeChangeListener = function(l) {
    var pos = 0;
    var oldChangePs = changePs;
    changePs = {};
    changeListeners = changeListeners.filter(function(ll, ix) {
      var allow = !Object.is(ll, l);
      if(allow) {
        if(oldChangePs[ix]) {
          changePs[pos] = oldChangePs[ix];
        }
        pos += 1;
      }
      return allow;
    });
  };

  this.createAccessor = function() {
    return function(_) {
      if(!arguments.length) {
        return get();
      }
      set(_);
    };
  };

  Object.defineProperties(this, {
    "value": {
      get: function() { return get(); },
      set: function(v) { set(v); },
    }
  });

  if(arguments.length) {
    value = _init;
    oldValue = _init;
  }
}; // jkjs.Cell
jkjs.Cell.prototype.toString = function() {
  return "" + this.value;
};
jkjs.Cell.anyChange = function(list, cb) {
  list.forEach(function(c) {
    c.addChangeListener(function() {
      cb();
    });
  });
};
jkjs.Cell.allChange = function(list, cb) {
  var chgs = list.map(function(c, ix) {
    c.addChangeListener(function() {
      chgs[ix] = true;
      var all = chgs.every(function(b) {
        return b;
      });
      if(all) {
        for(var cix = 0;cix < chgs.length;cix += 1) {
          chgs[cix] = false;
        }
        cb();
      }
    });
    return false;
  });
};

jkjs.Event = function(_) {
  var that = this;
  var cell = new jkjs.Cell(false);
  this.emit = function() {
    cell.value = !cell.value;
  };
  this.emitter = function() {
    return function() {
      that.emit();
    };
  };
  this.addEventListener = function(cb) {
    cell.addUpdateListener(function() {
      cb();
    });
  };

  if(arguments.length) {
    that.addEventListener(_);
  }
}; // jkjs.Event


text:
<?php

use Illuminate\Database\Seeder;
use App\Models\Transaction;
use App\Models\Order;
use Faker\Factory as FakerFactory;

class TransactionTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // Generate a new data faker for this seeder.
        $faker = FakerFactory::create();

        // Create a concluded transaction (payment successful)
        $transaction = new Transaction();
        $transaction->order()->associate(Order::find(1));
        $transaction->amount_sterling = 8.00;
        $transaction->payment_gateway_sha256 = $faker->sha256;
        $transaction->status = 'paid';
        $transaction->save();

        // Create an unconcluded transaction (payment NOT successful)
        $transaction = new Transaction();
        $transaction->order()->associate(Order::find(2));
        $transaction->amount_sterling = 8.00;
        $transaction->payment_gateway_sha256 = $faker->sha256;
        $transaction->status = 'failed';
        $transaction->save();
    }
}


text:
"""ghaudit.py
Tools used for ad-hoc audit of GitHub accounts for Microsoft users.
"""
import configparser
import gzip
import json
import os
import sys

import gitdata as gd

def appendcollabs_org(filename, org=None): #---------------------------------<<<
    """Append collaborator info for an org to collabs.csv data file.

    Special case: if no org provided, initialize the data file.
    """
    if not org:
        open(filename, 'w').write('org,repo,collaborator\n')
        return

    headers_dict = {"Accept": "application/vnd.github.korra-preview"}
    endpoint = '/orgs/' + org + '/outside_collaborators?per_page=100'
    collabdata = gdwrapper(endpoint=endpoint, \
        filename=None, entity='collab', authuser='msftgits', \
        fields=['*'], headers=headers_dict)
    for collab in collabdata:
        line = org + ',,' + collab['login']
        open(filename, 'a').write(line + '\n')

def appendcollabs_repo(filename, org, repo): #-------------------------------<<<
    """Append collaborator info for an org/repo to collabs.csv data file.

    Org/repo required - assumes data file already initialized by appendcollab_org().
    """
    headers_dict = {"Accept": "application/vnd.github.korra-preview"}
    endpoint = '/repos/' + org + '/' + repo + '/collaborators?per_page=100&affiliation=outside'
    collabdata = gdwrapper(endpoint=endpoint, \
        filename=None, entity='collab', authuser='msftgits', \
        fields=['login', 'repo', 'id'], headers=headers_dict)
    for collab in collabdata:
        line = org + ',' + repo + ',' + collab['login']
        open(filename, 'a').write(line + '\n')

def appendorgmembers(filename, org=None): #----------------------------------<<<

    """Append member info for an organization to orgmembers.csv data file.

    Special case: if no org provided, initialize the data file.
    """
    if not org:
        open(filename, 'w').write('org,login,type,site_admin,linked\n')
        return

    memberdata = gdwrapper(endpoint='/orgs/' + org + '/members?per_page=100', filename=None, \
        entity='member', authuser='msftgits', \
        fields=['login', 'type', 'site_admin'], headers={})
    for member in memberdata:
        site_admin = 'True' if member['site_admin'] else 'False'
        linked = 'True' if islinked(member['login']) else 'False'
        open(filename, 'a').write(org + ',' + member['login'] + ',' + \
            member['type'] + ',' + site_admin + ',' + \
            linked + '\n')

def appendrepos(filename, org=None): #---------------------------------------<<<
    """Append repo info for an org to repos.csv data file.

    Special case: if no org provided, initialize the data file.
    """
    if not org:
        open(filename, 'w').write('org,repo,private,fork\n')
        return

    repodata = gdwrapper(endpoint='/orgs/' + org + '/repos', filename=None, \
        entity='repo', authuser='msftgits', \
        fields=['name', 'owner.login', 'private', 'fork'], headers={})
    for repo in repodata:
        open(filename, 'a').write(org + ',' + repo['name'] + ',' + \
            repo['private'] + ',' + str(repo['fork']) + '\n')

def appendrepoteams(filename, teamid=None): #--------------------------------<<<
    """Append teamp-repo info for a teamp to repoteams.csv data file.

    Special case: if no teamid provided, initialize the data file.
    """
    if not teamid:
        open(filename, 'w').write('org,repo,teamid,admin,push,pull\n')
        return

    repodata = gdwrapper(endpoint='/teams/' + teamid + '/repos?per_page=100',\
        filename=None, entity='repo', authuser='msftgits', \
        fields=['full_name','permissions.admin','permissions.push','permissions.pull'], \
        headers={})
    for repo in repodata:
        orgname, reponame = repo['full_name'].split('/')
        open(filename, 'a').write(orgname + ',' + reponame + ',' + teamid + ',' + \
            str(repo['permissions_admin']) + ',' + \
            str(repo['permissions_push']) + ',' + \
            str(repo['permissions_pull']) + '\n')

def appendteammembers(filename, team=None): #--------------------------------<<<
    """Append member info for a team to teammembers.csv data file.

    Special case: if no team provided, initialize the data file.
    """
    if not team:
        open(filename, 'w').write('teamid,login,type,site_admin,linked\n')
        return

    memberdata = gdwrapper(endpoint='/teams/' + team + '/members?per_page=100', \
        filename=None, entity='teammember', authuser='msftgits', \
        fields=['login', 'type', 'site_admin'], headers={})
    for member in memberdata:
        site_admin = 'True' if member['site_admin'] else 'False'
        linked = 'True' if islinked(member['login']) else 'False'
        open(filename, 'a').write(team + ',' + member['login'] + ',' + \
            member['type'] + ',' + site_admin + ',' + \
            linked + '\n')

def appendteams(filename, org=None): #---------------------------------------<<<
    """Append team info for an org to teams.csv data file.

    Special case: if no org provided, initialize the data file.
    """
    if not org:
        open(filename, 'w').write('org,name,id,privacy,permission\n')
        return

    teamdata = gdwrapper(endpoint='/orgs/' + org + '/teams', filename=None, \
        entity='team', authuser='msftgits', \
        fields=['name', 'id', 'privacy', 'permission'], headers={})
    for team in teamdata:
        open(filename, 'a').write(org + ',' + team['name'] + ',' + \
            str(team['id']) + ',' + team['privacy'] + ',' + \
            team['permission'] + '\n')

def audituser(username): #---------------------------------------------------<<<
    """Show which repos/orgs/teams a GitHub user is associated with.
    """
    print('\nGitHub username:'.ljust(80, '-'))
    print(username + \
        ' (linked to ' + linkedemail(username) + ')' if islinked(username) \
        else ' (not linked)')

    print('ORG memberships:'.ljust(80, '-'))
    for org in orgmemberships(username):
        print(org)

    print('TEAM memberships:'.ljust(80, '-'))
    lastline = '*none*' # used to avoid re-printing of an org after first time
    for teamid in teammemberships(username):
        thisline = teamdesc(teamid)
        if thisline.split('/')[0][26:] == lastline.split('/')[0][26:]:
            # repetition of same org, so remove org from printed line
            permpriv = thisline[:26]
            reponame = thisline.split('/')[1]
            print(permpriv.ljust(len(thisline) - len(reponame) - 1) + '/' + reponame, end='')
        else:
            print(thisline, end='')
        lastline = thisline
        repolist = teamrepos(teamid)
        print(' (' + str(len(repolist)) + ' repos)')

    print('COLLABORATOR relationships:'.ljust(80, '-'))
    for collab in collaborations(username):
        if '/' in collab:
            print('repo: ' + collab)
        else:
            print('org:  ' + collab)

    #/// for each repo: last update, readme, contributing, license, code of conduct

def authenticate(): #--------------------------------------------------------<<<
    """Set up gitdata authentication.
    Currently using msftgits for all auditing of Microsoft accounts.
    """
    gd.auth_config({'username': 'msftgits'})

def azure_setting(section, setting): #---------------------------------------<<<
    """Get Azure setting from private INI data.

    section = section within the INI file
    setting = the setting to return from within that section

    Returns the setting's value, or None if not found.
    """
    source_folder = os.path.dirname(os.path.realpath(__file__))
    datafile = os.path.join(source_folder, '../_private/azure.ini')
    config = configparser.ConfigParser()
    config.read(datafile)
    try:
        retval = config.get(section, setting)
    except configparser.NoSectionError:
        retval = None
    return retval

def collabapis(orgname, filename=None): #------------------------------------<<<
    """Testing/comparison of the repo-level and org-level collaborator APIs.

    If filename specified, appends the collaborators to that CSV file.
    """

    # REPO-level collaborators ...
    repodata = gdwrapper(endpoint='/orgs/' + orgname + '/repos?per_page=100', filename=None, \
        entity='repo', authuser='msftgits', \
        fields=['name', 'owner.login', 'private', 'fork'], headers={})
    for repo in repodata:
        if repo['private'] == 'private':
            continue # skip private repos
        reponame = repo['name']
        endpoint = '/repos/' + orgname + '/' + reponame + '/collaborators?per_page=100'
        collabdata = gdwrapper(endpoint=endpoint, \
            filename=None, entity='collab', authuser='msftgits', \
            fields=['login', 'repo', 'id'], headers={})
        for collab in collabdata:
            line = orgname + ',' + reponame + ',' + collab['login']
            print(line)
            if filename:
                open(filename, 'a').write(line + '\n')

    # ORG-level collaborators ...
    headers_dict = {"Accept": "application/vnd.github.korra-preview"}
    endpoint = '/orgs/' + orgname + '/outside_collaborators?per_page=100'
    collabdata = gdwrapper(endpoint=endpoint, \
        filename=None, entity='collab', authuser='msftgits', \
        fields=['*'], headers=headers_dict)
    for collab in collabdata:
        line = orgname + ',,' + collab['login']
        print(line)
        if filename:
            open(filename, 'a').write(line + '\n')

def collaborations(username): #----------------------------------------------<<<
    """Return list of orgs and/or repos that user has a collaborator
    relationship with.
    """
    collabs = []
    firstline = True
    for line in open('ghaudit/collabs.csv', 'r').readlines():
        if firstline:
            firstline = False
            continue
        org = line.split(',')[0]
        repo = line.split(',')[1]
        user = line.split(',')[2].strip()
        if username.lower() == user.lower():
            if repo:
                collabs.append(org + '/' + repo)
            else:
                collabs.append(org)
    return sorted(collabs)

def gdwrapper(*, endpoint, filename, entity, authuser, #---------------------<<<
              fields, headers, verbose=True):
    """gitdata wrapper for automating gitdata calls
    """
    gd._settings.display_data = False
    gd._settings.verbose = False
    gd._settings.datasource = 'a'
    gd.auth_config({'username': authuser})
    templist = gd.github_data(
        endpoint=endpoint, entity=entity, fields=fields,
        constants={"user": authuser}, headers=headers)
    sorted_data = sorted(templist, key=gd.data_sort)
    gd.data_display(sorted_data)
    gd.data_write(filename, sorted_data)

    if verbose:
        # display rate-limit status
        used = gd._settings.last_ratelimit - gd._settings.last_remaining
        print('Rate Limit: ' + str(gd._settings.last_remaining) +
                        ' available, ' + str(used) +
                        ' used, ' + str(gd._settings.last_ratelimit) + ' total')

    return sorted_data

def islinked(username): #----------------------------------------------------<<<
    """Returns True if passed GitHub username is a linked Microsoft account.
    """
    if not hasattr(gd._settings, 'linked'):
        gd._settings.linked = []
        firstline = True
        for line in open('ghaudit/linkdata.csv', 'r').readlines():
            if firstline:
                firstline = False
                continue
            gd._settings.linked.append(line.split(',')[0].lower())

    return (username.lower() in gd._settings.linked)

def latestlinkdata(): #------------------------------------------------------<<<
    """Returns the most recent filename for Azure blobs that contain linkdata.
    """
    azure_acct = azure_setting('linkingdata', 'account')
    azure_key = azure_setting('linkingdata', 'key')
    azure_container = azure_setting('linkingdata', 'container')

    from azure.storage.blob import BlockBlobService
    block_blob_service = BlockBlobService(account_name=azure_acct, account_key=azure_key)
    blobs = block_blob_service.list_blobs(azure_container)
    latest = ''
    for blob in blobs:
        latest = blob.name if blob.name > latest else latest
    return latest if latest else None

def linkedemail(username): #-------------------------------------------------<<<
    """Returned linked email address (if any) for specified GitHub username.
    """
    if not hasattr(gd._settings, 'linkedemail'):
        gd._settings.linkedemail = dict()
        firstline = True
        for line in open('ghaudit/linkdata.csv', 'r').readlines():
            if firstline:
                firstline = False
                continue
            gd._settings.linkedemail[line.split(',')[0].lower()] = line.split(',')[1].strip()

    return gd._settings.linkedemail.get(username.lower(), None)

def orgmemberships(username): #----------------------------------------------<<<
    """Return list of orgs that user is member of.
    """
    orgs = []
    firstline = True
    for line in open('ghaudit/orgmembers.csv', 'r').readlines():
        if firstline:
            firstline = False
            continue
        orgname = line.split(',')[0]
        user = line.split(',')[1]
        if username.lower() == user.lower():
            orgs.append(orgname)
    return orgs

def printhdr(acct, msg): #---------------------------------------------------<<<
    """Print a header for a section of the audit report.
    """
    ndashes = 65 - len(msg)
    print('>> ' + msg + ' <<' + ndashes*'-' + ' account: ' + acct.upper())

def teamdesc(teamid): #------------------------------------------------------<<<
    """Return a 1-liner description for specified team id.
    """
    if not hasattr(gd._settings, 'teamdescription'):
        gd._settings.teamdescription = dict()
        firstline = True
        for line in open('ghaudit/teams.csv', 'r').readlines():
            if firstline:
                firstline = False
                continue
            orgname = line.split(',')[0]
            teamname = line.split(',')[1]
            teamno = line.split(',')[2]
            privacy = line.split(',')[3]
            perms = line.split(',')[4].strip()
            gd._settings.teamdescription[teamno] = 'perm=' + perms.ljust(6) + \
                'privacy=' + privacy.ljust(7) + orgname + '/' + teamname

    return gd._settings.teamdescription.get(teamid, teamid + ' (unknown team id)')

def teammemberships(username): #---------------------------------------------<<<
    """Return list of teams that user is member of.
    """
    teams = []
    firstline = True
    for line in open('ghaudit/teammembers.csv', 'r').readlines():
        if firstline:
            firstline = False
            continue
        teamid = line.split(',')[0]
        user = line.split(',')[1]
        if username.lower() == user.lower():
            teams.append(teamid)
    return teams

def teamrepos(teamid): #-----------------------------------------------------<<<
    """Return list of repos that this team has rights to.
    """
    repos = []
    firstline = True
    for line in open('ghaudit/repoteams.csv', 'r').readlines():
        if firstline:
            firstline = False
            continue
        this_id = line.split(',')[2]
        if this_id == teamid:
            reponame = line.split(',')[1]
            repos.append(reponame)
    return repos

def updatelinkdata(): #------------------------------------------------------<<<
    """Retrieve the latest Microsoft linking data from Azure blob storage
    and store in the ghaudit folder.
    """
    azure_acct = azure_setting('linkingdata', 'account')
    azure_key = azure_setting('linkingdata', 'key')
    azure_container = azure_setting('linkingdata', 'container')
    azure_blobname = latestlinkdata()
    gzfile = 'ghaudit/' + azure_blobname
    print('retrieving link data: ' + azure_blobname)

    # download the Azure blob
    from azure.storage.blob import BlockBlobService
    block_blob_service = BlockBlobService(account_name=azure_acct, account_key=azure_key)
    block_blob_service.get_blob_to_path(azure_container, azure_blobname, gzfile)

    # decompress the JSON file and write to linkdata.csv
    outfile = 'ghaudit/linkdata.csv'
    with open(outfile, 'w') as fhandle:
        fhandle.write('githubuser,email\n')
        for line in gzip.open(gzfile).readlines():
            jsondata = json.loads(line.decode('utf-8'))
            outline = jsondata['ghu'] + ',' + jsondata['aadupn']
            fhandle.write(outline + '\n')

def updatemsdata(): #--------------------------------------------------------<<<
    """Retrieve/refresh all Microsoft data needed for audit reports.
    """
    orgfile = 'ghaudit/orgs.csv'
    teamfile = 'ghaudit/teams.csv'
    repofile = 'ghaudit/repos.csv'
    collabfile = 'ghaudit/collabs.csv'
    tmembersfile = 'ghaudit/teammembers.csv'
    omembersfile = 'ghaudit/orgmembers.csv'
    repoteamsfile = 'ghaudit/repoteams.csv'

    # these variables control which data files are generated (for testing, etc.)
    write_orgs = False
    write_teams = False
    write_repos = False
    write_collabs = False
    write_linkdata = False
    write_teammembers = False
    write_orgmembers = False
    write_repoteams = False

    if write_orgs:
        # create the ORG data file, list of organizations to be audited
        # Below is inline automation of this command:
        #   gitdata orgs -amsftgits -sa -nghaudit/orgs.csv -flogin/user/id
        gdwrapper(endpoint='/user/orgs', filename=orgfile, entity='org', \
            authuser='msftgits', fields=['login', 'user', 'id'], headers={})

    # create the TEAM and REPO data files, iterating over ORGs
    if write_teams:
        appendteams(teamfile) # initialize data file
    if write_repos:
        appendrepos(repofile) # initialize data file
    if write_collabs:
        appendcollabs_org(collabfile) # initialize data file
    if write_orgmembers:
        appendorgmembers(omembersfile) # initialize data file
    firstline = True
    for line in open(orgfile, 'r').readlines():
        if firstline:
            firstline = False
            continue
        orgname = line.split(',')[0]
        print('ORG = ' + orgname)
        if write_teams:
            appendteams(teamfile, orgname)
        if write_repos:
            appendrepos(repofile, orgname)
        if write_collabs:
            appendcollabs_org(collabfile, orgname)
        if write_orgmembers:
            appendorgmembers(omembersfile, orgname)

    if write_collabs:
        # iterate over REPOs to add repo-level collaborators
        firstline = True
        for line in open(repofile, 'r').readlines():
            if firstline:
                firstline = False
                continue
            orgname = line.split(',')[0]
            reponame = line.split(',')[1]
            print('REPO = ' + orgname + '/' + reponame)
            appendcollabs_repo(collabfile, orgname, reponame)

    if write_linkdata:
        updatelinkdata() # get latest Microsoft linking data

    if write_teammembers:
        appendteammembers(tmembersfile) # initialize data file
        firstline = True
        for line in open(teamfile, 'r').readlines():
            if firstline:
                firstline = False
                continue
            print(line.strip())
            teamid = line.split(',')[2]
            appendteammembers(tmembersfile, teamid)

    if write_repoteams:
        appendrepoteams(repoteamsfile) # initialize data file
        firstline = True
        for line in open(teamfile, 'r').readlines():
            if firstline:
                firstline = False
                continue
            teamid = line.split(',')[2]
            appendrepoteams(repoteamsfile, teamid)

def userrepos(acct): #-------------------------------------------------------<<<
    """Print summary of user repositories for an account.
    """
    printhdr(acct, 'user repositories')

    authenticate()
    endpoint = '/users/' + acct + '/repos'
    response = gd.github_api(endpoint=endpoint, auth=gd.auth_user())
    jsondata = json.loads(response.text)
    for repo in jsondata:
        owner = repo['owner']['login']
        reponame = repo['name']
        print(owner + '/' + reponame)

if __name__ == '__main__':
    sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1)
    #updatemsdata()

    updatelinkdata()

    #if len(sys.argv) < 2:
    #    audituser('meganbradley')
    #else:
    #    for username in sys.argv[1:]:
    #        audituser(username)


text:
package gomonitor

import (
	"fmt"

	mon "gopkg.in/mcuadros/go-monitor.v1"
	"gopkg.in/mcuadros/go-monitor.v1/aspects"
)

// Start function exposes metrics of
// https://github.com/mcuadros/go-monitor package of your
// https://github.com/gin-gonic/gin based webapp. Start() get a
// port number as parameter to expose monitoring data to and a slice
// of aspects.Aspect defined by the user.
//
// Example:
//    	router := gin.New()
//    	counterAspect := &ginmon.CounterAspect{0}
//    	asps := []aspects.Aspect{counterAspect}
//    	// curl http://localhost:9000/Counter
//    	router.Use(ginmon.CounterHandler(counterAspect))
//    	// curl http://localhost:9000/
//    	gomonitor.Start(9000, asps)
//    	// last middleware
//    	router.Use(gin.Recovery())
func Start(port int, asps []aspects.Aspect) {
	var monitor *mon.Monitor = mon.NewMonitor(fmt.Sprintf(":%d", port))
	for _, aspect := range asps {
		monitor.AddAspect(aspect)
	}

	go monitor.Start()
}


text:
//
//  PTBaseLoginViewController.h
//  PicTalk
//
//  Created by wangzhong on 15/7/8.
//  Copyright (c) 2015年 wangzhong. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface PTBaseLoginViewController : UIViewController

/**
 *
 *    供子类调用
 *
 *    author:wz
 **/
- (void)login;

@end


text:
cask 'little-snitch' do
  version '3.7.1'
  sha256 'e6332ee70385f459d9803b0a582d5344bb9dab28bcd56e247ae69866cc321802'

  url "https://www.obdev.at/downloads/littlesnitch/LittleSnitch-#{version}.dmg"
  appcast 'https://www.obdev.at/products/littlesnitch/releasenotes.html',
          checkpoint: '1f2ffae32b8f4cab5618c32d1f4d29f6b48554890398dce0467957d3c288936f'
  name 'Little Snitch'
  homepage 'https://www.obdev.at/products/littlesnitch/index.html'

  installer manual: 'Little Snitch Installer.app'

  zap delete: [
                '/Library/Application Support/Objective Development/Little Snitch',
                '~/Library/Application Support/Little Snitch',
                '~/Library/Caches/at.obdev.LittleSnitchAgent',
                '~/Library/Caches/at.obdev.LittleSnitchConfiguration',
                '~/Library/Caches/at.obdev.LittleSnitchSoftwareUpdate',
                '~/Library/Caches/com.apple.helpd/Generated/at.obdev.LittleSnitchConfiguration.help',
                '~/Library/Caches/com.apple.helpd/SDMHelpData/Other/English/HelpSDMIndexFile/at.obdev.LittleSnitchConfiguration.help',
                '~/Library/Logs/Little Snitch Agent.log',
                '~/Library/Logs/Little Snitch Installer.log',
                '~/Library/Logs/Little Snitch Network Monitor.log',
                '~/Library/Preferences/at.obdev.LittleSnitchAgent.plist',
                '~/Library/Preferences/at.obdev.LittleSnitchConfiguration.plist',
                '~/Library/Preferences/at.obdev.LittleSnitchInstaller.plist',
                '~/Library/Preferences/at.obdev.LittleSnitchNetworkMonitor.plist',
                '~/Library/Preferences/at.obdev.LittleSnitchSoftwareUpdate.plist',
                '~/Library/Saved Application State/at.obdev.LittleSnitchInstaller.savedState',
              ],
      rmdir:  [
                '/Library/Application Support/Objective Development',
              ]

  caveats do
    reboot
  end
end


text:
/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <stdint.h>
#include <stdbool.h>
#include <sched.h>
#include <debug.h>
#include <nuttx/arch.h>

#include "os_internal.h"
#include "up_internal.h"

/****************************************************************************
 * Private Definitions
 ****************************************************************************/

/****************************************************************************
 * Private Data
 ****************************************************************************/

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: up_reprioritize_rtr
 *
 * Description:
 *   Called when the priority of a running or
 *   ready-to-run task changes and the reprioritization will
 *   cause a context switch.  Two cases:
 *
 *   1) The priority of the currently running task drops and the next
 *      task in the ready to run list has priority.
 *   2) An idle, ready to run task's priority has been raised above the
 *      the priority of the current, running task and it now has the
 *      priority.
 *
 * Inputs:
 *   tcb: The TCB of the task that has been reprioritized
 *   priority: The new task priority
 *
 ****************************************************************************/

void up_reprioritize_rtr(struct tcb_s *tcb, uint8_t priority)
{
  /* Verify that the caller is sane */

  if (tcb->task_state < FIRST_READY_TO_RUN_STATE ||
      tcb->task_state > LAST_READY_TO_RUN_STATE
#if SCHED_PRIORITY_MIN > 0
      || priority < SCHED_PRIORITY_MIN
#endif
#if SCHED_PRIORITY_MAX < UINT8_MAX
      || priority > SCHED_PRIORITY_MAX
#endif
    )
    {
       PANIC();
    }
  else
    {
      struct tcb_s *rtcb = (struct tcb_s*)g_readytorun.head;
      bool switch_needed;

      slldbg("TCB=%p PRI=%d\n", tcb, priority);

      /* Remove the tcb task from the ready-to-run list.
       * sched_removereadytorun will return true if we just
       * remove the head of the ready to run list.
       */

      switch_needed = sched_removereadytorun(tcb);

      /* Setup up the new task priority */

      tcb->sched_priority = (uint8_t)priority;

      /* Return the task to the specified blocked task list.
       * sched_addreadytorun will return true if the task was
       * added to the new list.  We will need to perform a context
       * switch only if the EXCLUSIVE or of the two calls is non-zero
       * (i.e., one and only one the calls changes the head of the
       * ready-to-run list).
       */

      switch_needed ^= sched_addreadytorun(tcb);

      /* Now, perform the context switch if one is needed */

      if (switch_needed)
        {
          /* If we are going to do a context switch, then now is the right
           * time to add any pending tasks back into the ready-to-run list.
           * task list now
           */

          if (g_pendingtasks.head)
            {
              sched_mergepending();
            }

         /* Are we in an interrupt handler? */

          if (current_regs)
            {
              /* Yes, then we have to do things differently.
               * Just copy the current_regs into the OLD rtcb.
               */

               up_copystate(rtcb->xcp.regs, current_regs);

              /* Restore the exception context of the rtcb at the (new) head
               * of the g_readytorun task list.
               */

              rtcb = (struct tcb_s*)g_readytorun.head;
              slldbg("New Active Task TCB=%p\n", rtcb);

              /* Then switch contexts */

              current_regs = rtcb->xcp.regs;
            }

          /* Copy the exception context into the TCB at the (old) head of the
           * g_readytorun Task list. if up_saveusercontext returns a non-zero
           * value, then this is really the previously running task restarting!
           */

          else if (!up_saveusercontext(rtcb->xcp.regs))
            {
              /* Restore the exception context of the rtcb at the (new) head
               * of the g_readytorun task list.
               */

              rtcb = (struct tcb_s*)g_readytorun.head;
              slldbg("New Active Task TCB=%p\n", rtcb);

              /* Then switch contexts */

              up_fullcontextrestore(rtcb->xcp.regs);
            }
        }
    }
}