text:
/**
 * @file
 * TransportList is a factory for Transports
 */

/******************************************************************************
 * Copyright AllSeen Alliance. All rights reserved.
 *
 *    Permission to use, copy, modify, and/or distribute this software for any
 *    purpose with or without fee is hereby granted, provided that the above
 *    copyright notice and this permission notice appear in all copies.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *    WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ******************************************************************************/
#include <qcc/platform.h>
#include <qcc/String.h>

#include "Transport.h"
#include "TransportList.h"
#include "LocalTransport.h"

#define QCC_MODULE "ALLJOYN"

using namespace std;
using namespace qcc;

namespace ajn {

TransportList::TransportList(BusAttachment& bus, TransportFactoryContainer& factories, IODispatch* m_ioDispatch, uint32_t concurrency)
    : bus(bus), localTransport(new LocalTransport(bus, concurrency)), m_factories(factories), isStarted(false), isInitialized(false), m_ioDispatch(m_ioDispatch)
{
}

TransportList::~TransportList()
{
    Stop();
    Join();

    for (size_t i = 0; i < transportList.size(); ++i) {
        delete transportList[i];
    }

    transportList.clear();

    delete localTransport;
}

QStatus TransportList::NormalizeTransportSpec(const char* inSpec, qcc::String& outSpec, map<qcc::String, qcc::String>& argMap)
{
    QStatus status;
    qcc::String inSpecStr(inSpec);

    Transport* trans = GetTransport(inSpecStr);
    if (trans) {
        status = trans->NormalizeTransportSpec(inSpec, outSpec, argMap);
    } else {
        status = ER_BUS_TRANSPORT_NOT_AVAILABLE;
    }
    return status;
}

Transport* TransportList::GetTransport(const qcc::String& transportSpec)
{
    Transport* transport = NULL;

    if (isInitialized && isStarted) {

        /* Try to get existing transport */
        size_t colonOff = transportSpec.find_first_of(':');
        for (size_t i = 0; i < transportList.size(); ++i) {
            Transport*& trans = transportList[i];
            if (0 == transportSpec.compare(0, colonOff, trans->GetTransportName())) {
                transport = trans;
                break;
            }
        }
    }

    return transport;
}

QStatus TransportList::Start(const String& transportSpecs)
{
    QCC_DbgPrintf(("TransportList::Start(specs = %s)", transportSpecs.c_str()));

    if (!isInitialized) {
        /*
         * The container of transport factories is used to do the actual
         * creation of the transports.  This is done in order to allow the
         * code at the highest level that knows if it is a daemon or a
         * client/service to specify what flavor of transport it wants.  For
         * example, a client will want the lightweight client version of the
         * TCPTransport, but a daemon will want to get the version that supports
         * inbound connections.
         *
         * The higher level code then provides a container of objects that
         * knows how to create transports.  We get a string abstractly
         * describing the kind of object here, for example "tcp" or "unix".
         * We look to the factory container for objects that can do the actual
         * creation.  The objects created when the string, "tcp" is found will
         * differ depending on the factories.  Since the factories are templated,
         * code will not be instantiated if particular specializations are not
         * used, so it is not necessary to link all flavors of transports in
         * all cases.
         */
        String specs = transportSpecs;
        size_t startPos = 0;

        /*
         * Add the default transports.  The defaults are also specified by the
         * TransportFactory settings, so different programs or samples can
         * specify different defaults.
         */
        for (uint32_t i = 0; i < m_factories.Size(); ++i) {
            TransportFactoryBase* factory = m_factories.Get(i);
            if (factory->IsDefault()) {
                transportList.push_back(factory->Create(bus));
            }
        }

        /*
         * The transport factory container provides some number of factories,
         * but only automatically creates instances of the default transports.
         * Other transports are created on-demand by specifying them in the
         * transportSpecs parameter provided to this method.
         */
        do {
            size_t endPos = specs.find_first_of(';', startPos);
            String spec = (String::npos == endPos) ? specs.substr(startPos) : specs.substr(startPos, endPos - startPos);
            size_t colonOff = spec.find_first_of(':');
            if (String::npos != colonOff) {
                String ttype = spec.substr(0, colonOff);
                Transport* exists = NULL;
                /*
                 * Check if transport has already been created
                 */
                for (size_t i = 0; i < transportList.size(); ++i) {
                    if (ttype == transportList[i]->GetTransportName()) {
                        exists = transportList[i];
                        break;
                    }
                }
                if (exists) {
                    QCC_DbgHLPrintf(("Transport %s already created", ttype.c_str()));
                } else {
                    for (uint32_t i = 0; i < m_factories.Size(); ++i) {
                        TransportFactoryBase* factory = m_factories.Get(i);
                        if (factory->GetType() == ttype && factory->IsDefault() == false) {
                            transportList.push_back(factory->Create(bus));
                        }
                    }
                }
            }
            startPos = ((String::npos == endPos) || (specs.size() <= (endPos + 1))) ? String::npos : specs.find_first_not_of(";", endPos);
        } while (startPos != String::npos);
        isInitialized = true;
    }

    /*
     * Start all of the transports we determined we selected above.
     */
    QStatus status = localTransport->Start();
    for (size_t i = 0; i < transportList.size(); ++i) {
        transportList[i]->SetListener(this);
        QStatus s = transportList[i]->Start();
        if (ER_OK == status) {
            status = s;
        }
    }

    /* Start the iodispatch */
    QStatus s = m_ioDispatch->Start();
    if (ER_OK == status) {
        status = s;
    }
    isStarted = (ER_OK == status);
    return status;
}

QStatus TransportList::Stop()
{
    QCC_DbgPrintf(("TransportList::Stop()"));
    isStarted = false;
    QStatus status = localTransport->Stop();
    for (size_t i = 0; i < transportList.size(); ++i) {
        QStatus s = transportList[i]->Stop();
        if (ER_OK == status) {
            status = s;
        }
    }
    /* Stop the iodispatch */
    QStatus s = m_ioDispatch->Stop();
    if (ER_OK == status) {
        status = s;
    }

    return status;
}

QStatus TransportList::Join()
{
    QStatus status = localTransport->Join();

    for (size_t i = 0; i < transportList.size(); ++i) {
        QStatus s = transportList[i]->Join();
        if (ER_OK == status) {
            status = s;
        }
    }
    /* Join the iodispatch */
    QStatus s = m_ioDispatch->Join();
    if (ER_OK == status) {
        status = s;
    }
    return status;
}

QStatus TransportList::RegisterListener(TransportListener* listener)
{
    listeners.push_back(listener);
    return ER_OK;
}

void TransportList::FoundNames(const qcc::String& busAddr,
                               const qcc::String& guid,
                               TransportMask transport,
                               const vector<qcc::String>* names,
                               uint32_t ttl)
{
    if (isStarted) {
        for (size_t i = 0; i < listeners.size(); ++i) {
            listeners[i]->FoundNames(busAddr, guid, transport, names, ttl);
        }
    }
}

}

redpajama_set_name: RedPajamaGithub


text:
__author__ = 'SmileyBarry'

from .core import APIConnection, SteamObject, store
from .decorators import cached_property, INFINITE

class SteamApp(SteamObject):
    def __init__(self, appid, name=None, owner=None):
        self._id = appid
        if name is not None:
            import time
            self._cache = dict()
            self._cache['name'] = (name, time.time())
        # Normally, the associated userid is also the owner.
        # That would not be the case if the game is borrowed, though. In that case, the object creator
        # usually defines attributes accordingly. However, at this time we can't ask the API "is this
        # game borrowed?", unless it's the actively-played game, so this distinction isn't done in the
        # object's context, but in the object creator's context.
        self._owner = owner
        self._userid = self._owner

    @cached_property(ttl=INFINITE)
    def _schema(self):
        return APIConnection().call("ISteamUserStats", "GetSchemaForGame", "v2", appid=self._id)

    @property
    def appid(self):
        return self._id

    @cached_property(ttl=INFINITE)
    def achievements(self):
        global_percentages = APIConnection().call("ISteamUserStats", "GetGlobalAchievementPercentagesForApp", "v0002",
                                                  gameid=self._id)
        if self._userid is not None:
            # Ah-ha, this game is associated to a user!
            userid = self._userid
            unlocks = APIConnection().call("ISteamUserStats",
                                           "GetUserStatsForGame",
                                           "v2",
                                           appid=self._id,
                                           steamid=userid)
            if 'achievements' in unlocks.playerstats:
                unlocks = [associated_achievement.name
                           for associated_achievement in unlocks.playerstats.achievements
                           if associated_achievement.achieved != 0]
        else:

            userid = None
            unlocks = None
        achievements_list = []
        for achievement in self._schema.game.availableGameStats.achievements:
            achievement_obj = SteamAchievement(self._id, achievement.name, achievement.displayName, userid)
            achievement_obj._cache = {}
            if achievement.hidden == 0:
                store(achievement_obj, "is_hidden", False)
            else:
                store(achievement_obj, "is_hidden", True)
            for global_achievement in global_percentages.achievementpercentages.achievements:
                if global_achievement.name == achievement.name:
                    achievement_obj.unlock_percentage = global_achievement.percent
            achievements_list += [achievement_obj]
        if unlocks is not None:
            for achievement in achievements_list:
                if achievement.apiname in unlocks:
                    store(achievement, "is_achieved", True)
                else:
                    store(achievement, "is_achieved", False)
        return achievements_list

    @cached_property(ttl=INFINITE)
    def name(self):
        return self._schema.game.gameName

    @cached_property(ttl=INFINITE)
    def owner(self):
        if self._owner is None:
            return self._userid
        else:
            return self._owner

    def __str__(self):
        return self.name

class SteamAchievement(SteamObject):
    def __init__(self, linked_appid, apiname, displayname, linked_userid=None):
        self._appid = linked_appid
        self._id = apiname
        self._displayname = displayname
        self._userid = linked_userid
        self.unlock_percentage = 0.0

    @property
    def appid(self):
        return self._appid

    @property
    def name(self):
        return self._displayname

    @property
    def apiname(self):
        return self._id

    @property
    def id(self):
        return self._id

    @cached_property(ttl=INFINITE)
    def is_hidden(self):
        response = APIConnection().call("ISteamUserStats",
                                        "GetSchemaForGame",
                                        "v2",
                                        appid=self._appid)
        for achievement in response.game.availableGameStats.achievements:
            if achievement.name == self._id:
                if achievement.hidden == 0:
                    return False
                else:
                    return True

    @cached_property(ttl=INFINITE)
    def is_unlocked(self):
        if self._userid is None:
            raise ValueError("No Steam ID linked to this achievement!")
        response = APIConnection().call("ISteamUserStats",
                                        "GetPlayerAchievements",
                                        "v1",
                                        steamid=self._userid,
                                        appid=self._appid,
                                        l="English")
        for achievement in response.playerstats.achievements:
            if achievement.apiname == self._id:
                if achievement.achieved == 1:
                    return True
                else:
                    return False
        # Cannot be found.
        return False


text:
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/jacobsa/comeback/internal/blob"
	"github.com/jacobsa/comeback/internal/restore"
	"github.com/jacobsa/comeback/internal/wiring"
)

var cmdRestore = &Command{
	Name: "restore",
	Run:  runRestore,
}

func runRestore(ctx context.Context, args []string) (err error) {
	// Extract and parse arguments.
	if len(args) != 2 {
		err = fmt.Errorf("Usage: %s restore dst_dir score", os.Args[0])
		return
	}

	dstDir := args[0]
	score, err := blob.ParseHexScore(args[1])
	if err != nil {
		err = fmt.Errorf("ParseHexScore(%q): %v", args[1], err)
		return
	}

	// Grab dependencies.
	bucket := getBucket(ctx)
	crypter := getCrypter(ctx)

	// Make sure the target doesn't exist.
	err = os.RemoveAll(dstDir)
	if err != nil {
		err = fmt.Errorf("os.RemoveAll: %v", err)
		return
	}

	// Create the destination.
	err = os.Mkdir(dstDir, 0700)
	if err != nil {
		err = fmt.Errorf("os.Mkdir: %v", err)
		return
	}

	// Attempt a restore.
	err = restore.Restore(
		ctx,
		dstDir,
		score,
		bucket,
		wiring.BlobObjectNamePrefix,
		crypter,
		log.New(os.Stderr, "Restore progress: ", 0),
	)

	if err != nil {
		err = fmt.Errorf("Restoring: %v", err)
		return
	}

	log.Printf("Successfully restored to %s", dstDir)
	return
}


text:
namespace Medusa.CoreProto
{
  [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ServerConfigItem")]
  public partial class ServerConfigItem : global::ProtoBuf.IExtensible
  {
    public ServerConfigItem() {}

    private uint _Id;
    [global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"Id", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
    public uint Id
    {
      get { return _Id; }
      set { _Id = value; }
    }
    private string _Address;
    [global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"Address", DataFormat = global::ProtoBuf.DataFormat.Default)]
    public string Address
    {
      get { return _Address; }
      set { _Address = value; }
    }
    private uint _Port;
    [global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"Port", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
    public uint Port
    {
      get { return _Port; }
      set { _Port = value; }
    }
    private Medusa.CoreProto.ServerConfigItem.ServerStatus _Status;
    [global::ProtoBuf.ProtoMember(4, IsRequired = true, Name=@"Status", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
    public Medusa.CoreProto.ServerConfigItem.ServerStatus Status
    {
      get { return _Status; }
      set { _Status = value; }
    }
    private Medusa.CoreProto.ServerConfigItem.ServerType _Type;
    [global::ProtoBuf.ProtoMember(5, IsRequired = true, Name=@"Type", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
    public Medusa.CoreProto.ServerConfigItem.ServerType Type
    {
      get { return _Type; }
      set { _Type = value; }
    }
    [global::ProtoBuf.ProtoContract(Name=@"ServerStatus")]
    public enum ServerStatus
    {

      [global::ProtoBuf.ProtoEnum(Name=@"OK", Value=0)]
      OK = 0,

      [global::ProtoBuf.ProtoEnum(Name=@"Maintain", Value=1)]
      Maintain = 1,

      [global::ProtoBuf.ProtoEnum(Name=@"Error", Value=2)]
      Error = 2
    }

    [global::ProtoBuf.ProtoContract(Name=@"ServerType")]
    public enum ServerType
    {

      [global::ProtoBuf.ProtoEnum(Name=@"TcpServer", Value=0)]
      TcpServer = 0,

      [global::ProtoBuf.ProtoEnum(Name=@"MockServer", Value=1)]
      MockServer = 1
    }

    private global::ProtoBuf.IExtension extensionObject;
    global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
      { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
  }

  [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ServerConfig")]
  public partial class ServerConfig : global::ProtoBuf.IExtensible
  {
    public ServerConfig() {}

    private readonly global::System.Collections.Generic.List<Medusa.CoreProto.ServerConfigItem> _Items = new global::System.Collections.Generic.List<Medusa.CoreProto.ServerConfigItem>();
    [global::ProtoBuf.ProtoMember(1, Name=@"Items", DataFormat = global::ProtoBuf.DataFormat.Default)]
    public global::System.Collections.Generic.List<Medusa.CoreProto.ServerConfigItem> Items
    {
      get { return _Items; }
    }

    private global::ProtoBuf.IExtension extensionObject;
    global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
      { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
  }

}


text:
package org.homeautomation.doormanager.plugin.impl.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.internal.DoorManagerManagementDataHolder;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import org.wso2.carbon.event.output.adapter.core.MessageType;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration;
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Contains utility methods used by doormanager plugin.
 */
public class DoorManagerUtils {

    private static Log log = LogFactory.getLog(org.homeautomation.doormanager.plugin.impl.util.DoorManagerUtils.class);

    public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.warn("Error occurred while closing result set", e);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                log.warn("Error occurred while closing prepared statement", e);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                log.warn("Error occurred while closing database connection", e);
            }
        }
    }

    public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
        cleanupResources(null, stmt, rs);
    }

    public static void setupDeviceManagementSchema() throws DoorManagerDeviceMgtPluginException {
        DeviceManagementConfiguration deviceManagementConfiguration = DoorManagerManagementDataHolder.getInstance()
                .getDeviceTypeConfigService().getConfiguration(DoorManagerConstants.DEVICE_TYPE,
                        DoorManagerConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
        String datasource = deviceManagementConfiguration.getDeviceManagementConfigRepository().getDataSourceConfig()
                .getJndiLookupDefinition().getJndiName();
        try {
            Context ctx = new InitialContext();
            DataSource dataSource = (DataSource) ctx.lookup(datasource);
            DeviceSchemaInitializer initializer = new DeviceSchemaInitializer(dataSource);
            log.info("Initializing device management repository database schema");
            initializer.createRegistryDatabase();
        } catch (NamingException e) {
            log.error("Error while looking up the data source: " + datasource, e);
        } catch (Exception e) {
            throw new DoorManagerDeviceMgtPluginException("Error occurred while initializing Iot Device " +
                    "Management database schema", e);
        }
    }
}


text:
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#import <UIKit/UIKit.h>

/**
 *  A overlay "cling" that describes how to use Cast for new users.
 *  Generally shown the first time the Cast icon appears in the application.
 */
@interface CastInstructionsViewController : UIViewController

/**
 *  Helper class method for deciding whether to show instructions or not
 *
 *  @param viewController The UIViewController to overlay.
 */
+ (void)showIfFirstTimeOverViewController:(UIViewController *)viewController;

/**
 *  Whether the instructions cling will appear or not.
 *
 *  @return YES if the user has seen the cling.
 */
+ (BOOL)hasSeenInstructions;

/**
 *  Represents the entire overlay with instructions for first time Cast users.
 */
@property(nonatomic, strong) IBOutlet UIView *overlayView;

/**
 *  Dismisses the entire overlay
 *
 *  @param sender Message sender
 */
- (IBAction)dismissOverlay:(id)sender;

@end


text:
require_relative "helpers"
require "liquid/drop/str"

module Jekyll
  module Post
    module Tags
      class Drop < Liquid::Drop::Str
        attr_reader :weight, :site
        extend Forwardable::Extended
        rb_delegate :name, to: :@tag, alias_of: :to_s
        include Helpers

        # --
        # New instance.
        # @return [nil]
        # --
        def initialize(tag, site:, weight: 1)
          super(tag)

          @site = site
          @weight = weight
          @tag = tag
        end

        # --
        # The url of the tag.
        # @return [String]
        # --
        def url
          File.join(*tag_path)
        end

        # --
        # Loop through, and return tags.
        # @param site [Jekyll::Site] the site.
        # @note These should return drops?
        # @return [[]] the tags.
        # --
        def self.to_tags(site:)
          div = 4.0 / site.tags.values.max_by(&:size).size
          site.tags.each_with_object([]) do |(k, v), o|
            weight = format("%.2f", div * v.size)

            o << new(k, {
              weight: weight.to_f,
              site: site,
            })
          end
        end
      end
    end
  end
end


text:
from setuptools import setup, find_packages
import sys, os

setup(name='django-responsive-dfp',
      version="0.1.2.4",
      description="Responsive ads using mediaquery for dfp.",
      long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(),
      classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Framework :: Django',
        ], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
      keywords='django dfp ads responsive',
      author='David Charbonnier',
      author_email='d.charbonnier@oxys.net',
      url='http://github.com/dcharbonnier/django-responsive-dfp',
      license='License :: OSI Approved :: MIT License',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      install_requires=[
          'django >= 1.3',
      ],
      )


text:
var app 	= require('express')()
var server 	= require('http').Server(app)
var bodyParser = require('body-parser')
var Datastore = require('nedb')
var async = require('async')

app.use(bodyParser.json())

module.exports = app

// Database stuff
var inventoryDB = new Datastore({
	filename: './server/databases/inventory.db',
	autoload: true
})

// GET inventory
app.get('/', function (req, res) {
	res.send('Inventory API')
})

// GET a product from inventory by _id
app.get('/product/:productId', function (req, res) {

	if (!req.params.productId) {
		res.status(500).send('ID field is required.')
	}
	else {
		inventoryDB.findOne({_id: req.params.productId }, function (err, product) {
			res.send(product)
		});
	}

})

// GET all inventory items
app.get('/products', function (req, res) {

	inventoryDB.find({}, function (err, docs) {
		res.send(docs)
	})
})

// Create inventory product
app.post('/product', function (req, res) {

	var newProduct = req.body

	inventoryDB.insert(newProduct, function (err, product) {
		if (err)
			res.status(500).send(err)
		else
			res.send(product)
	})
})

app.delete('/product/:productId', function (req, res) {

	inventoryDB.remove({ _id: req.params.productId }, function (err, numRemoved) {
		if (err)
			res.status(500).send(err)
		else
			res.sendStatus(200)
	})
})

// Update inventory product
app.put('/product', function (req, res) {

	var productId = req.body._id

	inventoryDB.update({ _id: productId }, req.body, {}, function (err, numReplaced, product) {

		if (err)
			res.status(500).send(err)
		else
			res.sendStatus(200)

	});

})

app.decrementInventory = function (products) {

	async.eachSeries(products, function (transactionProduct, callback) {

		inventoryDB.findOne({_id: transactionProduct._id }, function (err, product) {

			// catch manually added items (don't exist in inventory)
			if (!product || !product.quantity_on_hand) {
				callback();
			}

			else {
				var updatedQuantity = parseInt(product.quantity_on_hand) - parseInt(transactionProduct.quantity)

				inventoryDB.update({ _id: product._id }, { $set: { quantity_on_hand: updatedQuantity } }, {}, callback)
			}

		});

	});
};


text:
package org.apache.jmeter.gui;

import java.util.List;

/**
 * Interface for nodes that are searchable
 */
public interface Searchable {
    /**
     * @return List<String> of searchable tokens
     * @throws Exception
     */
    List<String> getSearchableTokens()
        throws Exception;
}


text:
function callbackCaller2(cb: Function): void {
    cb();
}


text:
分享接口
============

.. module:: teambition.api.posts

.. autoclass:: Posts
   :members:


text:
import java.io.{File, PrintWriter}
import javax.imageio.ImageIO

object WolframCells {

  val TEXT_WIDTH = 120
  val TEXT_HEIGHT = 50
  val BITMAP_WIDTH = 1000
  val BITMAP_HEIGHT = 500
  val INPUT = ""
  val OUTPUT = "-"
  val RULE_NO = 118
  val RULE_LENGTH = 7
  val PIXEL_SIZE = 1
  val BACKGROUND = 0
  val FOREGROUND = 255
  val INPUT_BACKGROUND = 0

  /*
 * Random rules:
 * 1111000 = 1101010 mirrored -> no 20
 * 0111110 = 1110110 mirrored -> halved with a path
 */

	def main(args: Array[String]) {
		val cmd = Cli.getCommandLine(args)
		val (bitmap, only_developed, rule_number, input, output, width, height, help, pixelSize, background, foreground) = Cli.setParameters(cmd)
		if (help) { Cli.printHelp; return }
		val matrixIn = obtainMatrix(input, width, height)
		val matrixOut = transformMatrix(matrixIn, rule_number)
		val matrixIsNotDeveloped = !isDeveloped(matrixOut)
		if (only_developed && matrixIsNotDeveloped) return
		dispatchMatrix(matrixOut, bitmap, output, pixelSize, background, foreground)
	}

	/*
	 * 1. OBTAIN MATRIX
	 */

	private def obtainMatrix(input: String, width: Int, height: Int): Array[Array[Boolean]] = {
		val inputTroughStdin = (input == "-")
		val inputTroughFile = (input != "")
		if (inputTroughStdin) {
			val stdin = WcUtil.stdinToString
			WcUtil.stringToMatrix(stdin)
		} else if (inputTroughFile) {
			getMatrixFromFile(input)
		} else {
			// Empty matrix with seed at top center
			WcUtil.getNewMatrix(height, width)
		}
	}

	private def getMatrixFromFile(input: String): Array[Array[Boolean]] = {
		val fileIsImage = input.toLowerCase.endsWith(".png")
		if (fileIsImage) {
			val image = ImageIO.read(new File(input))
			WcUtil.imageToMatrix(image)
		} else {
			val source = scala.io.Source.fromFile(input)
			val matrixStr = source.mkString
			source.close()
			WcUtil.stringToMatrix(matrixStr)
		}
	}

	/*
	 * 2. TRANSFORM MATRIX
	 */

	def transformMatrix(matrix: Array[Array[Boolean]], ruleNo: Int): Array[Array[Boolean]] = {
		val ruleBinary = WcUtil.getBinary(ruleNo, RULE_LENGTH)
		val ruleArray = WcUtil.stringToBoolArray("0" + ruleBinary)
		val rule = new Rule(ruleArray)
		println(ruleNo + " " + ruleBinary + " " + ruleArray + " " + rule)
		processMatrix(matrix, rule)
		matrix
	}

	class Rule(rules: Array[Boolean]) {
		def getCell(neighbours: Array[Boolean]): Boolean = {
			val index = toInt(neighbours(0), neighbours(1), neighbours(2))
			rules(index)
		}
		def toInt(b1: Boolean, b2: Boolean, b3: Boolean): Int = toInt(b1) * 4 + toInt(b2) * 2 + toInt(b3)
		def toInt(b: Boolean): Int = if (b) 1 else 0
	}

	def processMatrix(matrix: Array[Array[Boolean]], rule: Rule) {
		for (y <- 0 to matrix.size - 2) {
			for (x <- 0 to matrix(0).size - 3) {
				val slice = matrix(y).slice(x, x + 3)
				val newCell = rule.getCell(slice)
				matrix(y + 1)(x + 1) = newCell
			}
		}
	}

	/*
	 * 3. IS DEVELOPED
	 */

	def isDeveloped(matrix: Array[Array[Boolean]]): Boolean = {
		val noOfTrues = WcUtil.countTrues(matrix)
		val matrixHeight = matrix.size
		noOfTrues > matrixHeight * 2
	}

	/*
	 * 4. DISPATCH MATRIX
	 */

	def dispatchMatrix(matrix: Array[Array[Boolean]], bitmap: Boolean, output: String, pixelSize: Int, background: Int, foreground: Int) {
		if (bitmap) {
			dispatchBitmap(matrix, output, pixelSize, background, foreground)
		} else {
			dispatchText(matrix, output)
		}
	}

	private def dispatchBitmap(matrix: Array[Array[Boolean]], output: String, pixelSize: Int, background: Int, foreground: Int): Unit = {
		val imgIn = WcUtil.matrixToImage(matrix, background, foreground)
		val img = WcUtil.magnifyImage(imgIn, pixelSize)
		if (output == "-") {
			ImageIO.write(img, "png", System.out)
		} else {
			ImageIO.write(img, "png", new File(output))
		}
	}

	private def dispatchText(matrix: Array[Array[Boolean]], output: String): Unit = {
		if (output == "-") {
			WcUtil.printMatrix(matrix)
		} else {
			val matrixStr = WcUtil.matrixToString(matrix, "#", " ")
			val out = new PrintWriter(output)
			out.println(matrixStr)
			out.close
		}
	}

}


text:
require 'rubygems'
require 'i18n'

module I18n
  module Backend
    class Simple
      public :translations, :init_translations
    end
  end
end

class KeyStructure
  PLURALIZATION_KEYS = ['zero', 'one', 'two', 'few', 'many', 'other']

  class << self
    def check(locale, version)
      missing_keys = []
      broken_keys = []

      init_backend(locale, version)

      I18n.locale = locale.to_sym
      translations = flatten_hash(I18n.backend.translations[:'en'])
      translations.keys.sort.each do |key|
        begin
          case key
          when /^date\.formats\.(\w+)/
            I18n.l Date.today, :format => $1.to_sym, :raise => true
          when /^time\.formats\.(\w+)/
            I18n.l Time.now, :format => $1.to_sym, :raise => true
          else
            I18n.t key, :raise => true
          end
        rescue I18n::MissingTranslationData
          missing_keys << key
        rescue Exception
          broken_keys << key
        end
      end

      return missing_keys, broken_keys
    end

    private
      def flatten_hash(data, prefix = '', result = {})
        data.each do |key, value|
          current_prefix = prefix.empty? ? key.to_s : "#{prefix}.#{key}"

          if !value.is_a?(Hash) || pluralization_data?(value)
            result[current_prefix] = value
          else
            flatten_hash(value, current_prefix, result)
          end
        end

        result
      end

      def pluralization_data?(data)
        keys = data.keys.map(&:to_s)
        keys.all? {|k| PLURALIZATION_KEYS.include?(k) }
      end

      def init_backend(locale, version)
        I18n.load_path = []
        I18n.reload!

        case version.to_i
        when 2
          I18n.load_path += Dir[File.dirname(__FILE__) + "/../../rails/*.yml"]
        when 3
          I18n.load_path += Dir[File.dirname(__FILE__) + "/../../rails3/*.yml"]
        end

        path = File.dirname(__FILE__) + "/../../locale/#{locale}.rb"

        unless File.exist?(path)
          path = File.dirname(__FILE__) + "/../../locale/#{locale}.yml"
        end

        unless File.exist?(path)
          raise "No locale file exist for :#{locale}."
        end

        I18n.load_path += [path]
        I18n.backend.init_translations
      end
  end
end


text:
package nl.rivm.cib.epidemes.geodb.infra;

/**
 * {@link NWBRoadSectionDao} see also
 * http://nationaalgeoregister.nl/geonetwork/srv/dut/search?#|2e5f0f60-0f2f-4e17-96af-c913fe305ecb
 *
 * @version $Id$
 * @author Rick van Krevelen
 */
public class NWBRoadSectionDao
{
//	TABLE nl.infra_nwb_wegvakken_2016_04
//	(
//	  objectid integer NOT NULL,
//	  wvk_id numeric(38,8),
//	  wvk_begdat timestamp without time zone,
//	  jte_id_beg numeric(38,8),
//	  jte_id_end numeric(38,8),
//	  wegbehsrt character varying(1),
//	  wegnummer character varying(5),
//	  wegdeelltr character varying(1),
//	  hecto_lttr character varying(1),
//	  rpe_code character varying(2),
//	  bst_code character varying(3),
//	  admrichtng character varying(1),
//	  rijrichtng character varying(1),
//	  stt_naam character varying(29),
//	  wpsnaamnen character varying(24),
//	  gme_id integer,
//	  gme_naam character varying(24),
//	  hnrstrlnks character varying(1),
//	  hnrstrrhts character varying(1),
//	  e_hnr_lnks integer,
//	  e_hnr_rhts integer,
//	  l_hnr_lnks integer,
//	  l_hnr_rhts integer,
//	  begafstand integer,
//	  endafstand integer,
//	  beginkm numeric(38,8),
//	  eindkm numeric(38,8),
//	  pos_tv_wol character varying(1),
//	  wegbehcode character varying(4),
//	  wegbehnaam character varying(35),
//	  distrcode smallint,
//	  distrnaam character varying(40),
//	  dienstcode character varying(2),
//	  dienstnaam character varying(40),
//	  wegtype character varying(2),
//	  wgtype_oms character varying(40),
//	  routeltr character varying(1),
//	  routenr smallint,
//	  routeltr2 character varying(1),
//	  routenr2 smallint,
//	  routeltr3 character varying(1),
//	  routenr3 smallint,
//	  routeltr4 character varying(1),
//	  routenr4 smallint,
//	  wegnr_aw character varying(7),
//	  shape geometry,
//	  CONSTRAINT enforce_srid_shape CHECK (srid(shape) = 28992)
//	)
}