text:
TA-sendcef provides a custom Splunk search command, `sendcef`, for creating and sending CEF-formatted events over TCP or UDP. The underlying command uses the Splunk Custom Search Command protocol, version 2.

The specification for CEF, Common Event Format, is available in [PDF](https://kc.mcafee.com/resources/sites/MCAFEE/content/live/CORP_KNOWLEDGEBASE/78000/KB78712/en_US/CEF_White_Paper_20100722.pdf) from McAfee.

## Supported Splunk Versions

The `sendcef` custom command will only work with 6.4.x or higher versions of Splunk. Version 2 of the Splunk Custom Search Command protocol was introduced as a technology preview with Splunk 6.4.

## System Requirements

The `sendcef` command is a binary application written in [Go](https://golang.org). The TA has binaries included for the following platforms:
 * Darwin (OS X) 64-bit
 * Linux 64-bit
 * Windows 64-bit

## Installation

Use normal Splunk installation procedures to install the TA. This includes installation through the Splunk UI or "unzipping" and copying to `$SPLUNK_HOME/etc/apps`. The application is a Splunk .spl file, which can be renamed to .tgz and decompressed.

Released versions are available on GitHub: [`TA-sendcef`](https://github.com/triddell/TA-sendcef/releases)

## Configuration

Configuration of `sendcef` is made through a custom conf file, specifically `sendcef.conf`. This file *must* be available in `$SPLUNK_HOME/etc/apps/TA-sendcef/local`. The `local` directory will need to be created after installing the application.

In the `local` directory, create the `sendcef.conf` file.

Here is an example configuration file:

```
[general]
#logLevel = debug
#timeout = 5s

[ceftarget:tcp]
server = your_server_ip:10522
protocol = tcp

[ceftarget:udp]
server = your_server_ip:10523
protocol = udp
```

### General Stanza

The `[general]` stanza above is not required but it does include some commented configurations that can be used to modify the behavior of `sendcef`.

Valid values for `logLevel` include `debug`, `info`, `warn`, and `error`. The default is `warn`. Most log messages are either `debug` or `error`.

The default `timeout` is `10s` (ten seconds). Valid, but not necessarily good, values are available from the Go `time.ParseDuration` function [documentation](https://golang.org/pkg/time/#ParseDuration).

### "Target" Stanzas

The "target" stanzas can be named anything. The examples append `:tcp` and `:udp` but a stanza could just as easily be `[foobar]`.

Within a target stanza, it's pretty basic. Name the stanza what you want. Then add a `server` value which includes a hostname or IP address followed by a port number (separated by a colon). For `protocol`, choose either `tcp` or `udp`.

### Usage

`sendcef` is a custom Splunk search command, so it's usually appended to a Splunk search. Here's a full example of a search command using `sendcef`:

```
index=_internal sourcetype=splunkd ERROR
| convert timeformat="%m-%d-%Y %H:%M:%S.%3N" ctime(_time) AS cef_time
| eval cef_host = host,
    cef_device_vendor = "Vendor",
    cef_device_product = "Product",
    cef_device_version = "Version",
    cef_event_class = "Class",
    cef_name = "Name",
    cef_severity = "10",
    cef_extension = "message, source"
| sendcef ceftarget:tcp
```

The base search, `index=_internal sourcetype=splunkd ERROR`, is simple and should work on nearly any Splunk system. If the search returns either zero records or many thousands, you may want to refine it to a managable number for your initial testing.

The next portion of the search sets up all of the CEF record format fields:

```
| convert timeformat="%m-%d-%Y %H:%M:%S.%3N" ctime(_time) AS cef_time
| eval cef_host = host,
    cef_device_vendor = "Vendor",
    cef_device_product = "Product",
    cef_device_version = "Version",
    cef_event_class = "Class",
    cef_name = "Name",
    cef_severity = "10",
    cef_extension = "message, source"
```

These should become self-explanatory once we look at a sample output record.

The final portion of the search, `| sendcef ceftarget:tcp`, is what calls the `sendcef` custom search command. A configured stanza name is the sole command argument.

Here is an example record that would get sent to the target host and port over either TCP or UDP:

```
06-05-2017 10:09:26.392 Tims-MBP CEF:0|Vendor|Product|Version|Class|Name|10|message=File too small to check seekcrc, probably truncated.  Will re-read entire file\='/Users/tim/opt/splunk-sendtest/var/log/splunk/django_error.log'. source=/Users/tim/opt/splunk-sendtest/var/log/splunk/splunkd.log
```

In the search command, notice how full control of the event formatting is handled by using `convert` and `eval` to set key fields prior to calling `sendcef`. The full power of the Splunk Search Processing Language (SPL) is available to set these fields.

`sendcef` uses these fields when processing:
 * cef_time
 * cef_host
 * cef_device_product
 * cef_device_vendor
 * cef_event_class
 * cef_name
 * cef_severity
 * cef_extension

This example hard-codes the CEF header fields but these values could just as easily be dynamic and based on the underlying Splunk event (using any SPL commands.)

The `cef_extension` field is handled differently. `cef_extension` takes a comma-separated list of fields from the underlying Splunk event and formats these name/value pairs (with escapes where necessary) before appending them to the end of the CEF message. Notice in the example output message above how `message` and `source` are handled as CEF extension fields.

**Note:** Don't rely on the order of these extension fields. `sendcef` randomizes the order of these extension fields in the output.

`sendcef` can be used as an ad hoc search command but it will often be used to automate data integration with third-party servers using Splunk saved/scheduled searches.

**Note:** The output of a command using `sendcef` will return the *unformatted, original* events to the browser as search results. A future version of `sendcef` may return the formatted CEF messages to the browser. Also, this custom command only *asks* Splunk for the `cef_*` fields and any fields within `cef_extension`. This could mean that additional extracted fields are not available in the search results.

### Testing

To faciliate testing using a local Splunk instance, a related TA has been developed. `TA-sendtest` provides test target indexes, TCP and UDP Splunk inputs, and a `sendcef.conf.sample` similar to what was used in this documentation.

Further information on this application is available on GitHub: [`TA-sendtest`](https://github.com/triddell/TA-sendtest)

### Troubleshooting

`sendcef` logs events at: `$SPLUNK_HOME/var/log/splunk/sendcef.log`

These events can be searched with Splunk using: `index=_internal source=*sendcef.log`

### Related Application

A similar application has been developed for sending "raw" Splunk events to third-party servers. Further information on this application is available on both [Splunk Base](https://splunkbase.splunk.com/app/3624/) and [GitHub](https://github.com/triddell/TA-sendraw).


text:
$MatEdDblUpdate = false;

//==============================================================================
// Helper functions to help load and update the preview and active material
//------------------------------------------------------------------------------
//==============================================================================
// Finds the selected line in the material list, then makes it active in the editor.
function MaterialEditorTools::prepareActiveMaterial(%this, %material, %override) {
	// If were not valid, grab the first valid material out of the materialSet
	if( !isObject(%material) ) {
		%material = MaterialSet.getObject(0);
		%isNew = true;
	}

	// Check made in order to avoid loading the same material. Overriding
	// made in special cases
	if(%material $= MaterialEditorTools.lastMaterial && !%override) {
		return;
	} else {
		if(MaterialEditorTools.materialDirty ) {
			MaterialEditorTools.showSaveDialog( %material );
			return;
		}

		MaterialEditorTools.setActiveMaterial(%material,%isNew);
	}
}
//------------------------------------------------------------------------------
//==============================================================================
// Updates the preview material to use the same properties as the selected material,
// and makes that material active in the editor.
//MaterialEditorTools.setActiveMaterial(test_cuboidTestF);
function MaterialEditorTools::setActiveMaterial( %this, %material,%isNew ) {
	// Warn if selecting a CustomMaterial (they can't be properly previewed or edited)
	if ( isObject( %material ) && %material.isMemberOfClass( "CustomMaterial" ) ) {
		LabMsgOK( "Warning", "The selected Material (" @ %material.getName() @
					 ") is a CustomMaterial, and cannot be edited using the Material Editor." );
		return;
	}

	if (strFind(%material.getFilename(),"tlab/materialEditor") || %material.getFilename() $= "") {
		%material.setFilename($Pref::MaterialEditorTools::DefaultMaterialFile);
	}

	MaterialEditorTools.currentMaterial = %material;
	MaterialEditorTools.lastMaterial = %material;
	%this.setActiveMaterialFile(%material);
	// we create or recreate a material to hold in a pristine state
	singleton Material(notDirtyMaterial) {
		mapTo = "matEd_previewMat";
		diffuseMap[0] = "tlab/materialEditor/assets/matEd_mappedMat";
	};
	// Converts the texture files into absolute paths.
	MaterialEditorTools.convertTextureFields();
	// If we're allowing for name changes, make sure to save the name seperately
	%this.originalName = MaterialEditorTools.currentMaterial.name;
	// Copy materials over to other references
	MaterialEditorTools.copyMaterials( MaterialEditorTools.currentMaterial, materialEd_previewMaterial );
	MaterialEditorTools.copyMaterials( MaterialEditorTools.currentMaterial, notDirtyMaterial );
	MaterialEditorTools.guiSync( materialEd_previewMaterial );
	// Necessary functionality in order to render correctly
	materialEd_previewMaterial.flush();
	materialEd_previewMaterial.reload();
	MaterialEditorTools.currentMaterial.flush();
	MaterialEditorTools.currentMaterial.reload();
	MaterialEditorTools.setMaterialNotDirty();

	if (%isNew)
		MaterialEditorTools.currentMaterial.metalness[0] = "0";
}
//------------------------------------------------------------------------------
//==============================================================================
function MaterialEditorTools::setActiveMaterialFile( %this, %material ) {
	MatEdTargetMode-->selMaterialFile.setText(%material.getFilename());
	MatEdMaterialMode-->selMaterialFile.setText(%material.getFilename());
}
//------------------------------------------------------------------------------
// Accumulation
function MaterialEditorTools::updateAccuCheckbox(%this, %value) {
	MaterialEditorTools.updateActiveMaterial("accuEnabled[" @ MaterialEditorTools.currentLayer @ "]", %value);
	%mat = MaterialEditorTools.currentMaterial;
	MaterialEditorTools.guiSync( materialEd_previewMaterial );
}

//==============================================================================
function MaterialEditorTools::updateMaterialPBR(%this, %propertyField,%value, %isSlider, %onMouseUp) {
	devLog(" MaterialEditorTools::updateMaterialPBR(%this, %propertyField, %value, %isSlider, %onMouseUp)", %this, %propertyField, %value, %isSlider, %onMouseUp);
	%mat = MaterialEditorTools.currentMaterial;
	%layer = MaterialEditorTools.currentLayer;
	%isDirty = LabObj.set(%mat,%propertyField,%value,%layer);

	if (%isDirty)
		MaterialEditorTools.setMaterialDirty();

	%field = %propertyField@"[" @%layer @ "]";
	eval("materialEd_previewMaterial." @ %field @ " = " @ %value @ ";");
	materialEd_previewMaterial.flush();
	materialEd_previewMaterial.reload();

	if ($MatEdDblUpdate)
		%this.updateActiveMaterial(%field,%value, %isSlider, %onMouseUp);
}
//==============================================================================
function MaterialEditorTools::updateActiveMaterial(%this, %propertyField, %value, %isSlider, %onMouseUp) {
	logc(" MaterialEditorTools::updateActiveMaterial(%this, %propertyField, %value, %isSlider, %onMouseUp)", %this, %propertyField, %value, %isSlider, %onMouseUp);
	MaterialEditorTools.setMaterialDirty();

	if(%value $= "")
		%value = "\"\"";

	// Here is where we handle undo actions with slider controls. We want to be able to
	// undo every onMouseUp; so we overrite the same undo action when necessary in order
	// to achieve this desired effect.
	%last = Editor.getUndoManager().getUndoAction(Editor.getUndoManager().getUndoCount() - 1);

	if((%last != -1) && (%last.isSlider) && (!%last.onMouseUp)) {
		%last.field = %propertyField;
		%last.isSlider = %isSlider;
		%last.onMouseUp = %onMouseUp;
		%last.newValue = %value;
	} else {
		%action = %this.createUndo(ActionUpdateActiveMaterial, "Update Active Material");
		%action.material = MaterialEditorTools.currentMaterial;
		%action.object = MaterialEditorTools.currentObject;
		%action.field = %propertyField;
		%action.isSlider = %isSlider;
		%action.onMouseUp = %onMouseUp;
		%action.newValue = %value;
		eval( "%action.oldValue = " @ MaterialEditorTools.currentMaterial @ "." @ %propertyField @ ";");
		%action.oldValue = "\"" @ %action.oldValue @ "\"";
		MaterialEditorTools.submitUndo( %action );
	}

	if (!isObject(materialEd_previewMaterial))
		MaterialEditorTools.establishMaterials();

	eval("materialEd_previewMaterial." @ %propertyField @ " = " @ %value @ ";");
	materialEd_previewMaterial.flush();
	materialEd_previewMaterial.reload();

	if (MaterialEditorTools.livePreview == true) {
		eval("MaterialEditorTools.currentMaterial." @ %propertyField @ " = " @ %value @ ";");
		MaterialEditorTools.currentMaterial.flush();
		MaterialEditorTools.currentMaterial.reload();
	}

	if(strFind(%propertyField,"diffuseMap") && %autoUpdateNormal) {
		%diffuseSuffix = MaterialEditorPlugin.getCfg("DiffuseSuffix");
		%cleanValue = strreplace(%value,%diffuseSuffix,"");
		%autoUpdateNormal = MaterialEditorPlugin.getCfg("AutoAddNormal");

		if (%autoUpdateNormal) {
			%normalMap = strreplace(%propertyField,"diffuse","normal");
			%normalFile = MaterialEditorTools.currentMaterial.getFieldValue(%normalMap);
			%isFileNormal = isImageFile(%normalFile);

			if (!%isFileNormal) {
				%normalSuffix = MaterialEditorPlugin.getCfg("NormalSuffix");
				%fileBase = fileBase(%cleanValue);
				%filePath = filePath(%cleanValue);
				%testNormal = %filePath@"/"@%fileBase@%normalSuffix;
				%isFileNew = isImageFile(%testNormal);

				if (%isFileNew)
					%this.updateTextureMapImage("normal",%testNormal,0);
			}
		}

		%autoUpdateSpecular = MaterialEditorPlugin.getCfg("AutoAddSpecular");

		if (%autoUpdateSpecular) {
			%specMap = strreplace(%propertyField,"diffuse","specular");
			%specFile = MaterialEditorTools.currentMaterial.getFieldValue(%specMap);
			%isFileSpec = isImageFile(%specFile);

			if (!%isFileSpec) {
				%specSuffix = MaterialEditorPlugin.getCfg("SpecularSuffix");
				%fileBase = fileBase(%cleanValue);
				%filePath = filePath(%cleanValue);
				%testSpec = %filePath@"/"@%fileBase@%specSuffix;
				//%testSpec = strreplace(%testSpec,"\"","");
				%isFileNew = isImageFile(%testSpec);

				if (%isFileNew)
					%this.updateTextureMapImage("spec",%testSpec,0);
			}
		}
	}
}
//------------------------------------------------------------------------------
//==============================================================================
function MaterialEditorTools::updateActiveMaterialName(%this, %name) {
	%action = %this.createUndo(ActionUpdateActiveMaterialName, "Update Active Material Name");
	%action.material =  MaterialEditorTools.currentMaterial;
	%action.object = MaterialEditorTools.currentObject;
	%action.oldName = MaterialEditorTools.currentMaterial.getName();
	%action.newName = %name;
	MaterialEditorTools.submitUndo( %action );
	MaterialEditorTools.currentMaterial.setName(%name);
	// Some objects (ConvexShape, DecalRoad etc) reference Materials by name => need
	// to find and update all these references so they don't break when we rename the
	// Material.
	MaterialEditorTools.updateMaterialReferences( MissionGroup, %action.oldName, %action.newName );
}

redpajama_set_name: RedPajamaGithub


text:
import { mediaOverlayDriverFactory as publicDriverFactory } from '../MediaOverlay.uni.driver';

export const mediaOverlayPrivateDriverFactory = base => {
  return {
    ...publicDriverFactory(base),
    getContentChildren: async () =>
      await base.$$(`[data-hook="content-area"] > *`),
  };
};


text:
"""
The temp module provides a NamedTemporaryFile that can be reopened in the same
process on any platform. Most platforms use the standard Python
tempfile.NamedTemporaryFile class, but Windows users are given a custom class.

This is needed because the Python implementation of NamedTemporaryFile uses the
O_TEMPORARY flag under Windows, which prevents the file from being reopened
if the same flag is not provided [1][2]. Note that this does not address the
more general issue of opening a file for writing and reading in multiple
processes in a manner that works across platforms.

The custom version of NamedTemporaryFile doesn't support the same keyword
arguments available in tempfile.NamedTemporaryFile.

1: https://mail.python.org/pipermail/python-list/2005-December/336957.html
2: http://bugs.python.org/issue14243
"""

import os
import tempfile

from django.core.files.utils import FileProxyMixin

__all__ = ('NamedTemporaryFile', 'gettempdir',)

if os.name == 'nt':
    class TemporaryFile(FileProxyMixin):
        """
        Temporary file object constructor that supports reopening of the
        temporary file in Windows.

        Unlike tempfile.NamedTemporaryFile from the standard library,
        __init__() doesn't support the 'delete', 'buffering', 'encoding', or
        'newline' keyword arguments.
        """
        def __init__(self, mode='w+b', bufsize=-1, suffix='', prefix='', dir=None):
            fd, name = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)
            self.name = name
            self.file = os.fdopen(fd, mode, bufsize)
            self.close_called = False

        # Because close can be called during shutdown
        # we need to cache os.unlink and access it
        # as self.unlink only
        unlink = os.unlink

        def close(self):
            if not self.close_called:
                self.close_called = True
                try:
                    self.file.close()
                except (OSError, IOError):
                    pass
                try:
                    self.unlink(self.name)
                except OSError:
                    pass

        def __del__(self):
            self.close()

        def __enter__(self):
            self.file.__enter__()
            return self

        def __exit__(self, exc, value, tb):
            self.file.__exit__(exc, value, tb)

    NamedTemporaryFile = TemporaryFile
else:
    NamedTemporaryFile = tempfile.NamedTemporaryFile

gettempdir = tempfile.gettempdir


text:
/*!
	@file
	@author		Albert Semenov
	@date		11/2007
*/
/*
	This file is part of MyGUI.

	MyGUI is free software: you can redistribute it and/or modify
	it under the terms of the GNU Lesser General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	MyGUI is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public License
	along with MyGUI.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_FONT_MANAGER_H__
#define __MYGUI_FONT_MANAGER_H__

#include "MyGUI_Prerequest.h"
#include "MyGUI_Enumerator.h"
#include "MyGUI_IFont.h"
#include "MyGUI_Singleton.h"
#include "MyGUI_XmlDocument.h"
#include "MyGUI_ResourceManager.h"
#include "MyGUI_BackwardCompatibility.h"

namespace MyGUI
{

	class MYGUI_EXPORT FontManager :
		public Singleton<FontManager>,
		public MemberObsolete<FontManager>
	{
	public:
		FontManager();

		void initialise();
		void shutdown();

		/** Get default font name.
			Default skin also used when creating widget with skin that doesn't exist.
		*/
		const std::string& getDefaultFont() const;
		/** Get default font name.
			Default skin also used when creating widget with skin that doesn't exist.
		*/
		void setDefaultFont(const std::string& _value);

		/** Get font resource */
		IFont* getByName(const std::string& _name) const;

	private:
		void _load(xml::ElementPtr _node, const std::string& _file, Version _version);

	private:
		std::string mDefaultName;

		bool mIsInitialise;
	};

} // namespace MyGUI

#endif // __MYGUI_FONT_MANAGER_H__


text:
from django.db import models
from django.utils.text import slugify

from committees.models import Committee
from legislators.models import Chamber, Legislator

BILL_TYPES = {
    'HB': 'House Bill',
    'SB': 'Senate Bill',
    'HR': 'House Resolution',
    'SR': 'Senate Resolution',
    'HJR': 'House Joint Resolution',
    'SJR': 'Senate Joint Resolution',
    'HCR': 'House Concurrent Resolution',
    'SCR': 'Senate Concurrent Resolution',
}

class Subject(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField()

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.name)[:50]

        super(Subject, self).save(*args, **kwargs)

    def get_absolute_url(self):
        from django.core.urlresolvers import reverse
        return reverse('category-detail', args=(self.slug,))

class Bill(models.Model):
    name = models.CharField(max_length=10)
    bill_number = models.IntegerField(null=True, blank=True)
    description = models.TextField()
    chamber = models.ForeignKey(Chamber, related_name='bills')
    sponsors = models.ManyToManyField(Legislator, through='Sponsorship')
    subjects = models.ManyToManyField(Subject, related_name='bills')
    openstates_id = models.CharField(max_length=11, unique=True)
    bill_type = models.CharField(max_length=21)
    slug = models.SlugField()

    first_action_date = models.DateField(null=True, blank=True)
    last_action_date = models.DateField(null=True, blank=True)
    passed_senate = models.DateField(null=True, blank=True)
    passed_house = models.DateField(null=True, blank=True)
    became_law = models.DateField(null=True, blank=True)
    vetoed = models.DateField(null=True, blank=True)

    class Meta:
        ordering = ('chamber__name', 'bill_type', 'bill_number',)

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = self.name.replace(' ', '')

        super(Bill, self).save(*args, **kwargs)

    @property
    def house_committee(self):
        try:
            return self.actions.reverse().exclude(
                related_committee__isnull=True).filter(
                acting_chamber__name='Texas House')[0].related_committee
        except IndexError:
            return None

    @property
    def senate_committee(self):
        try:
            return self.actions.reverse().exclude(
                related_committee__isnull=True).filter(
                acting_chamber__name='Texas Senate')[0].related_committee
        except IndexError:
            return None

    @property
    def long_name(self):
        split_name = self.name.split(' ')

        return '{0} {1}'.format(
            BILL_TYPES[split_name[0]], split_name[1])

    @property
    def authors(self):
        return self.sponsorships.filter(role='author')

    @property
    def coauthors(self):
        return self.sponsorships.filter(role='coauthor')

    @property
    def sponsors(self):
        return self.sponsorships.filter(role='sponsor')

    @property
    def cosponsors(self):
        return self.sponsorships.filter(role='cosponsor')

    def get_absolute_url(self):
        from django.core.urlresolvers import reverse
        return reverse('bill-detail', args=(self.slug,))

class Action(models.Model):
    number = models.CharField(max_length=4)
    text = models.CharField(max_length=100)
    date = models.DateField()
    acting_chamber = models.ForeignKey(Chamber, related_name='actions')
    related_committee = models.ForeignKey(
        Committee, related_name='actions', null=True, blank=True)
    bill = models.ForeignKey(Bill, related_name='actions')

    class Meta:
        ordering = ['date', 'pk']

class Sponsorship(models.Model):
    legislator = models.ForeignKey(Legislator, related_name='sponsorships')
    bill = models.ForeignKey(Bill, related_name='sponsorships')
    role = models.CharField(max_length=20)
    ordering = models.PositiveIntegerField(default=0)

    def __unicode__(self):
        return u'{0} as {1} of {2}'.format(
            self.legislator.full_name, self.role, self.bill)

    class Meta:
        ordering = ['ordering']


text:
=================================
The Node.JS MongoDB Driver Manual
=================================

Usage
-----

.. toctree::
  :maxdepth: 1

  markdown-docs/index

Driver Updates
--------------

.. toctree::
  :maxdepth: 3

  driver-articles/index

Tutorials
---------

.. toctree::
  :maxdepth: 3

  api-articles/index

API Documentation
-----------------

.. toctree::
  :maxdepth: 2

  api-generated/index
  api-bson-generated/index

External Tutorials
------------------

  * http://howtonode.org/express-mongodb, Blog rolling with mongoDB, express and Node.js
  * http://nodetuts.com/tutorials/18-mongodb-and-mongoose.html, Node Tuts - episode 18 - Node.js, MongoDB and Mongoose from Pedro Teixeira on Vimeo.
  * http://howtonode.org/node-js-and-mongodb-getting-started-with-mongojs, Node.js and MongoDB - Getting started with MongoJS

Video Presentations about different topics around the MongoDB and Node.js
-------------------------------------------------------------------------

.. toctree::
  :maxdepth: 3

  content/nodejsvideo
  content/awesomeappsvideo
  content/tutorials

Projects and Libraries using the driver
---------------------------------------

.. toctree::
  :maxdepth: 1

  github/github

MongoDB in General
------------------
There are two main places to learn about MongoDB itself. I've included links below.

  * http://www.mongodb.org, all the documentation for the database
  * http://www.10gen.com/presentations, lots of presentations and slides about using the database.

There are also some very good books out these days

  * `MongoDB: The Definitive Guide <http://www.amazon.com/MongoDB-Definitive-Guide-Kristina-Chodorow/dp/1449381561/ref=sr_1_1?ie=UTF8&qid=1329392515&sr=8-1>`_
  * `MongoDB in Action <http://www.amazon.com/MongoDB-Action-Kyle-Banker/dp/1935182870/ref=sr_1_2?ie=UTF8&qid=1329392515&sr=8-2>`_
  * `The Definitive Guide to MongoDB: The NoSQL Database for Cloud and Desktop Computing <http://www.amazon.com/Definitive-Guide-MongoDB-Database-Computing/dp/1430230517/ref=sr_1_3?ie=UTF8&qid=1329392515&sr=8-3>`_
  * `50 Tips and Tricks for MongoDB Developers <http://www.amazon.com/50-Tips-Tricks-MongoDB-Developers/dp/1449304613/ref=sr_1_4?ie=UTF8&qid=1329392515&sr=8-4>`_
  * `Scaling MongoDB <http://www.amazon.com/Scaling-MongoDB-Kristina-Chodorow/dp/1449303218/ref=sr_1_6?ie=UTF8&qid=1329392515&sr=8-6>`_
  * `MongoDB and Python: Patterns and processes for the popular document-oriented database <http://www.amazon.com/MongoDB-Python-Patterns-processes-document-oriented/dp/1449310370/ref=sr_1_7?ie=UTF8&qid=1329392515&sr=8-7>`_
  * `MongoDB and PHP <http://www.amazon.com/MongoDB-PHP-Steve-Francia/dp/1449314368/ref=sr_1_8?ie=UTF8&qid=1329392515&sr=8-8>`_
  * `PHP and MongoDB Web Development Beginner's Guide <http://www.amazon.com/PHP-MongoDB-Development-Beginners-Guide/dp/1849513627/ref=sr_1_10?ie=UTF8&qid=1329392515&sr=8-10>`_
  * `Node Web Development <http://www.amazon.com/Node-Web-Development-David-Herron/dp/184951514X/ref=sr_1_11?ie=UTF8&qid=1329392515&sr=8-11>`_
  * `Document Design for MongoDB <http://www.amazon.com/Document-Design-MongoDB-Jeremy-McAnally/dp/1449303412/ref=sr_1_12?ie=UTF8&qid=1329392515&sr=8-12>`_

Changelog
---------

.. toctree::
  :maxdepth: 1

  changelog/changelog

Indices
-------

- :ref:`genindex`
- :ref:`search`


text:
This guide covers your first look and can be used even before installing software.

## Overview

This project is a kit for developing interactive applications in JavaScript centered
around React and Redux.  Like all JavaScript kits, it includes a large number of configured
modules and a sample, or Demo App, from which to start your application.  This guide walks
through that Demo App to show some features and code.

### Open the demo in your browser

The project hosts a running demo on Heroku, a hosting company.  Open
[https://react-redux.herokuapp.com/](https://react-redux.herokuapp.com/) in your browser to see this page:

![Screenshot](frontpage.png)

Much of the text is cut-and-paste from the project's
[README.md](https://github.com/lordakshaya/pages/blob/master/README.md) file into
the code for this page [./src/containers/Home/Home.js](https://github.com/lordakshaya/pages/blob/master/src/containers/Home/Home.js).

The text provides a one line overview of about twenty of the main
modules of hundreds shown during installation.   The selection
and configuration of all these modules is the value of using a kit.   When you run across
a module you have never heard of and want to get a quick overview, the fastest way is
to google for 'slideshare theModuleName' and skim someone's presentation.

The page is rendered from HTML including React components coded as custom HTML tags.
The components use properties to alter appearance and sets of data.  Notice some of the components on the page:

![Screenshot with Annotations](frontpage_markup.png)

### Explore the Widgets Page

Click on *Widgets* link on the top of the screen.   You come to a page with some arbitrary widgets and more logic
in the form.  Notice how much state affects the display and formatting of buttons:

![Screenshot with Annotations](widgets_markup.png)

### Explore the Survey Page

Click on the *Survey* link.  Following the programming style of this kit, the code for this page is
spread over a [Survey container][scont], a [SurveyForm component][scomp], mentioned in the
[container][conlist] and [component][complist] lists,
mentioned in the [routes][routes] function and the navigation of the main [App][app].  The code also uses
various libraries for React, Redux, validation, memoize and other functions.   Learn to use [ack](http://beyondgrep.com)
or the project wide search built into your editor.

Try clicking on the 'Initialize Form' button and then hitting Submit.  You will see just an error under
'Little Bobby Tables'.  Now click in the email field then the name field.   You now see errors in both
the name and the email.  Even with a good kit, forms can be difficult to code.

![Screenshot with Annotations](survey_markup.png)
[scont]: https://github.com/lordakshaya/pages/tree/master/src/containers/Survey
[scomp]: https://github.com/lordakshaya/pages/tree/master/src/components/SurveyForm
[conlist]: https://github.com/lordakshaya/pages/blob/master/src/containers/index.js
[complist]: https://github.com/lordakshaya/pages/blob/master/src/components/index.js
[routes]: https://github.com/lordakshaya/pages/blob/master/src/routes.js
[app]: https://github.com/lordakshaya/pages/tree/master/src/containers/App/App.js

### Explore the About Page

Click on the *About* link.   The source for this page
[./src/containers/About/About.js](https://github.com/lordakshaya/pages/blob/master/src/containers/About/About.js)
uses a casual mix of HTML, ECMA7 JavaScript, and React components.   This translates into
simple JavaScript code for the browser.   Notice how the local state `showKitten` being false causes no
`div` or `img` tag in the output.

![Screenshot with Annotations](about_markup.png)

### Explore the Login Page

Finally, click on the *Login* page and explore.   Looking at the styling for this page
[./src/containers/Login/Login.scss]](https://github.com/lordakshaya/pages/blob/master/src/containers/Login/Login.scss)
will show an example of how the using styling files litters the code base with extra files.
Consider the alternative of using
[Inline Styles](https://github.com/lordakshaya/pages/blob/master/docs/InlineStyles.md).

# The Take Away

Looking through each page of the DemoApp will lead you to more questions which will keep you
searching and learning and you will slowly master this technology.

Here are some additional quests you could undertake:

* How do the About page MiniBar and the status bar share data about the time last loaded?
* How would you add a fourth counter that incremented by two?   How many files would you need
  to touch?
* What order are calls made when you click "Reload Widgets" on the widgets page?
* Why does surveyValidation use memoize?

Install, hack, explore!

*All guides are works in progress, and pull requests are always welcome.  If you make an
accepted pull request and live in Silicon Valley, I'll treat you to coffee.  -- Charles*


text:
from __future__ import unicode_literals

from django.conf import settings

DEBUG = getattr(settings, 'DEBUG', False)

PIPELINE_ROOT = getattr(settings, 'PIPELINE_ROOT', settings.STATIC_ROOT)
PIPELINE_URL = getattr(settings, 'PIPELINE_URL', settings.STATIC_URL)

PIPELINE_STORAGE = getattr(settings, 'PIPELINE_STORAGE',
                           'pipeline.storage.PipelineFinderStorage')

PIPELINE_CSS_COMPRESSOR = getattr(settings, 'PIPELINE_CSS_COMPRESSOR',
                                  'pipeline.compressors.yuglify.YuglifyCompressor')
PIPELINE_JS_COMPRESSOR = getattr(settings, 'PIPELINE_JS_COMPRESSOR',
                                 'pipeline.compressors.yuglify.YuglifyCompressor')
PIPELINE_COMPILERS = getattr(settings, 'PIPELINE_COMPILERS', [])

PIPELINE_CSS = getattr(settings, 'PIPELINE_CSS', {})
PIPELINE_JS = getattr(settings, 'PIPELINE_JS', {})

PIPELINE_TEMPLATE_NAMESPACE = getattr(settings, 'PIPELINE_TEMPLATE_NAMESPACE', "window.JST")
PIPELINE_TEMPLATE_EXT = getattr(settings, 'PIPELINE_TEMPLATE_EXT', ".jst")
PIPELINE_TEMPLATE_FUNC = getattr(settings, 'PIPELINE_TEMPLATE_FUNC', "template")

PIPELINE_DISABLE_WRAPPER = getattr(settings, 'PIPELINE_DISABLE_WRAPPER', False)

PIPELINE_CSSTIDY_BINARY = getattr(settings, 'PIPELINE_CSSTIDY_BINARY', '/usr/bin/env csstidy')
PIPELINE_CSSTIDY_ARGUMENTS = getattr(settings, 'PIPELINE_CSSTIDY_ARGUMENTS', '--template=highest')

PIPELINE_YUGLIFY_BINARY = getattr(settings, 'PIPELINE_YUGLIFY_BINARY', '/usr/bin/env yuglify')
PIPELINE_YUGLIFY_CSS_ARGUMENTS = getattr(settings, 'PIPELINE_YUGLIFY_CSS_ARGUMENTS', '--terminal')
PIPELINE_YUGLIFY_JS_ARGUMENTS = getattr(settings, 'PIPELINE_YUGLIFY_JS_ARGUMENTS', '--terminal')

PIPELINE_YUI_BINARY = getattr(settings, 'PIPELINE_YUI_BINARY', '/usr/bin/env yuicompressor')
PIPELINE_YUI_CSS_ARGUMENTS = getattr(settings, 'PIPELINE_YUI_CSS_ARGUMENTS', '')
PIPELINE_YUI_JS_ARGUMENTS = getattr(settings, 'PIPELINE_YUI_JS_ARGUMENTS', '')

PIPELINE_CLOSURE_BINARY = getattr(settings, 'PIPELINE_CLOSURE_BINARY', '/usr/bin/env closure')
PIPELINE_CLOSURE_ARGUMENTS = getattr(settings, 'PIPELINE_CLOSURE_ARGUMENTS', '')

PIPELINE_UGLIFYJS_BINARY = getattr(settings, 'PIPELINE_UGLIFYJS_BINARY', '/usr/bin/env uglifyjs')
PIPELINE_UGLIFYJS_ARGUMENTS = getattr(settings, 'PIPELINE_UGLIFYJS_ARGUMENTS', '')

PIPELINE_CSSMIN_BINARY = getattr(settings, 'PIPELINE_CSSMIN_BINARY', '/usr/bin/env cssmin')
PIPELINE_CSSMIN_ARGUMENTS = getattr(settings, 'PIPELINE_CSSMIN_ARGUMENTS', '')

PIPELINE_COFFEE_SCRIPT_BINARY = getattr(settings, 'PIPELINE_COFFEE_SCRIPT_BINARY', '/usr/bin/env coffee')
PIPELINE_COFFEE_SCRIPT_ARGUMENTS = getattr(settings, 'PIPELINE_COFFEE_SCRIPT_ARGUMENTS', '')

PIPELINE_LIVE_SCRIPT_BINARY = getattr(settings, 'PIPELINE_LIVE_SCRIPT_BINARY', '/usr/bin/env lsc')
PIPELINE_LIVE_SCRIPT_ARGUMENTS = getattr(settings, 'PIPELINE_LIVE_SCRIPT_ARGUMENTS', '')

PIPELINE_SASS_BINARY = getattr(settings, 'PIPELINE_SASS_BINARY', '/usr/bin/env sass')
PIPELINE_SASS_ARGUMENTS = getattr(settings, 'PIPELINE_SASS_ARGUMENTS', '')

PIPELINE_STYLUS_BINARY = getattr(settings, 'PIPELINE_STYLUS_BINARY', '/usr/bin/env stylus')
PIPELINE_STYLUS_ARGUMENTS = getattr(settings, 'PIPELINE_STYLUS_ARGUMENTS', '')

PIPELINE_LESS_BINARY = getattr(settings, 'PIPELINE_LESS_BINARY', '/usr/bin/env lessc')
PIPELINE_LESS_ARGUMENTS = getattr(settings, 'PIPELINE_LESS_ARGUMENTS', '')

PIPELINE_MIMETYPES = getattr(settings, 'PIPELINE_MIMETYPES', (
    ('text/coffeescript', '.coffee'),
    ('text/less', '.less'),
    ('text/javascript', '.js'),
    ('text/x-sass', '.sass'),
    ('text/x-scss', '.scss')
))

PIPELINE_EMBED_MAX_IMAGE_SIZE = getattr(settings, 'PIPELINE_EMBED_MAX_IMAGE_SIZE', 32700)
PIPELINE_EMBED_PATH = getattr(settings, 'PIPELINE_EMBED_PATH', r'[/]?embed/')

if PIPELINE_COMPILERS is None:
    PIPELINE_COMPILERS = []


text:
package ta4jexamples.analysis;

import eu.verdelhan.ta4j.Indicator;
import eu.verdelhan.ta4j.Strategy;
import eu.verdelhan.ta4j.Decimal;
import eu.verdelhan.ta4j.Tick;
import eu.verdelhan.ta4j.TimeSeries;
import eu.verdelhan.ta4j.TradingRecord;
import eu.verdelhan.ta4j.analysis.CashFlow;
import eu.verdelhan.ta4j.indicators.simple.ClosePriceIndicator;
import java.awt.Color;
import java.awt.Dimension;
import java.text.SimpleDateFormat;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
import org.jfree.data.time.Minute;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
import ta4jexamples.loaders.CsvTradesLoader;
import ta4jexamples.strategies.MovingMomentumStrategy;

/**
 * This class builds a graphical chart showing the cash flow of a strategy.
 */
public class CashFlowToChart {

    /**
     * Builds a JFreeChart time series from a Ta4j time series and an indicator.
     * @param tickSeries the ta4j time series
     * @param indicator the indicator
     * @param name the name of the chart time series
     * @return the JFreeChart time series
     */
    private static org.jfree.data.time.TimeSeries buildChartTimeSeries(TimeSeries tickSeries, Indicator<Decimal> indicator, String name) {
        org.jfree.data.time.TimeSeries chartTimeSeries = new org.jfree.data.time.TimeSeries(name);
        for (int i = 0; i < tickSeries.getTickCount(); i++) {
            Tick tick = tickSeries.getTick(i);
            chartTimeSeries.add(new Minute(tick.getEndTime().toDate()), indicator.getValue(i).toDouble());
        }
        return chartTimeSeries;
    }

    /**
     * Adds the cash flow axis to the plot.
     * @param plot the plot
     * @param dataset the cash flow dataset
     */
    private static void addCashFlowAxis(XYPlot plot, TimeSeriesCollection dataset) {
        final NumberAxis cashAxis = new NumberAxis("Cash Flow Ratio");
        cashAxis.setAutoRangeIncludesZero(false);
        plot.setRangeAxis(1, cashAxis);
        plot.setDataset(1, dataset);
        plot.mapDatasetToRangeAxis(1, 1);
        final StandardXYItemRenderer cashFlowRenderer = new StandardXYItemRenderer();
        cashFlowRenderer.setSeriesPaint(0, Color.blue);
        plot.setRenderer(1, cashFlowRenderer);
    }

    /**
     * Displays a chart in a frame.
     * @param chart the chart to be displayed
     */
    private static void displayChart(JFreeChart chart) {
        // Chart panel
        ChartPanel panel = new ChartPanel(chart);
        panel.setFillZoomRectangle(true);
        panel.setMouseWheelEnabled(true);
        panel.setPreferredSize(new Dimension(1024, 400));
        // Application frame
        ApplicationFrame frame = new ApplicationFrame("Ta4j example - Cash flow to chart");
        frame.setContentPane(panel);
        frame.pack();
        RefineryUtilities.centerFrameOnScreen(frame);
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        // Getting the time series
        TimeSeries series = CsvTradesLoader.loadBitstampSeries();
        // Building the trading strategy
        Strategy strategy = MovingMomentumStrategy.buildStrategy(series);
        // Running the strategy
        TradingRecord tradingRecord = series.run(strategy);
        // Getting the cash flow of the resulting trades
        CashFlow cashFlow = new CashFlow(series, tradingRecord);

        /**
         * Building chart datasets
         */
        TimeSeriesCollection datasetAxis1 = new TimeSeriesCollection();
        datasetAxis1.addSeries(buildChartTimeSeries(series, new ClosePriceIndicator(series), "Bitstamp Bitcoin (BTC)"));
        TimeSeriesCollection datasetAxis2 = new TimeSeriesCollection();
        datasetAxis2.addSeries(buildChartTimeSeries(series, cashFlow, "Cash Flow"));

        /**
         * Creating the chart
         */
        JFreeChart chart = ChartFactory.createTimeSeriesChart(
                "Bitstamp BTC", // title
                "Date", // x-axis label
                "Price", // y-axis label
                datasetAxis1, // data
                true, // create legend?
                true, // generate tooltips?
                false // generate URLs?
                );
        XYPlot plot = (XYPlot) chart.getPlot();
        DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(new SimpleDateFormat("MM-dd HH:mm"));

        /**
         * Adding the cash flow axis (on the right)
         */
        addCashFlowAxis(plot, datasetAxis2);

        /**
         * Displaying the chart
         */
        displayChart(chart);
    }
}


text:
from cfn_sphere.cli import get_first_account_alias_or_account_id
from cfn_sphere.exceptions import CfnSphereException

try:
    from unittest2 import TestCase
    from mock import patch, Mock
except ImportError:
    from unittest import TestCase
    from mock import patch, Mock

class CliTests(TestCase):
    @patch("boto3.client")
    def test_get_first_account_alias_or_account_id_returns_first_account_alias(self, boto_mock):
        boto_mock.return_value.list_account_aliases.return_value = {"AccountAliases": ["a", "b", "c"]}

        result = get_first_account_alias_or_account_id()
        self.assertEqual("a", result)

    @patch("boto3.client")
    def test_get_first_account_alias_or_account_id_returns_account_id_if_no_alias_found(self, boto_mock):
        boto_mock.return_value.list_account_aliases.return_value = {"AccountAliases": []}
        boto_mock.return_value.get_caller_identity.return_value = {"Arn": "arn:aws:iam::ACCOUNT_ID:user/USERNAME"}

        result = get_first_account_alias_or_account_id()
        self.assertEqual("ACCOUNT_ID", result)


text:
ServerException::ServerException()
{

}

ServerException::ServerException(const int err)
{
	m_msg = Errno::ToStr(err);
}

ServerException::ServerException(const int err, const std::string Message)
{
	m_errno = err;
	m_msg = Message;
}

ServerException::~ServerException() throw()
{

}

const char *ServerException::what() const throw()
{
	return m_msg.c_str();
}

int ServerException::GetErrorNo() const
{
	return m_errno;
}

std::string ServerException::GetErrorMessage() const
{
	return m_msg;
}


text:
package com.yuzhouwan.hacker.security;

import com.yuzhouwan.common.util.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;

import static com.yuzhouwan.hacker.security.SecurityClassLoader.ALGORITHM;

class EncryptClasses {

    private static final Logger _log = LoggerFactory.getLogger(EncryptClasses.class);

    /**
     * @param clazz key.data UnsafeApp.class UnsafeClass.class
     */
    static void encrypt(String... clazz) throws Exception {
        String keyFilename = clazz[0];
        SecureRandom sr = new SecureRandom();
        byte[] rawKey = FileUtils.readFile(keyFilename);
        assert rawKey != null;
        DESKeySpec dks = new DESKeySpec(rawKey);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); // lgtm [java/weak-cryptographic-algorithm]
        SecretKey key = keyFactory.generateSecret(dks);

        Cipher cipher = Cipher.getInstance(ALGORITHM); // lgtm [java/weak-cryptographic-algorithm]
        cipher.init(Cipher.ENCRYPT_MODE, key, sr);

        String filename;
        byte[] classData, encryptedClassData;
        for (int i = 1; i < clazz.length; ++i) {
            filename = clazz[i];

            classData = FileUtils.readFile(filename);
            assert classData != null;
            encryptedClassData = cipher.doFinal(classData);
            FileUtils.writeFile(filename, encryptedClassData);

            _log.debug("Encrypted {}", filename);
        }
    }
}


text:
<?php

namespace yii\caching;

/**
 * TagDependency associates a cached data item with one or multiple [[tags]].
 *
 * By calling [[invalidate()]], you can invalidate all cached data items that are associated with the specified tag name(s).
 *
 * ```php
 * // setting multiple cache keys to store data forever and tagging them with "user-123"
 * Yii::$app->cache->set('user_42_profile', '', 0, new TagDependency(['tags' => 'user-123']));
 * Yii::$app->cache->set('user_42_stats', '', 0, new TagDependency(['tags' => 'user-123']));
 *
 * // invalidating all keys tagged with "user-123"
 * TagDependency::invalidate(Yii::$app->cache, 'user-123');
 * ```
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class TagDependency extends Dependency
{
    /**
     * @var string|array a list of tag names for this dependency. For a single tag, you may specify it as a string.
     */
    public $tags = [];

    /**
     * Generates the data needed to determine if dependency has been changed.
     * This method does nothing in this class.
     * @param Cache $cache the cache component that is currently evaluating this dependency
     * @return mixed the data needed to determine if dependency has been changed.
     */
    protected function generateDependencyData($cache)
    {
        $timestamps = $this->getTimestamps($cache, (array) $this->tags);

        $newKeys = [];
        foreach ($timestamps as $key => $timestamp) {
            if ($timestamp === false) {
                $newKeys[] = $key;
            }
        }
        if (!empty($newKeys)) {
            $timestamps = array_merge($timestamps, static::touchKeys($cache, $newKeys));
        }

        return $timestamps;
    }

    /**
     * Performs the actual dependency checking.
     * @param Cache $cache the cache component that is currently evaluating this dependency
     * @return boolean whether the dependency is changed or not.
     */
    public function getHasChanged($cache)
    {
        $timestamps = $this->getTimestamps($cache, (array) $this->tags);
        return $timestamps !== $this->data;
    }

    /**
     * Invalidates all of the cached data items that are associated with any of the specified [[tags]].
     * @param Cache $cache the cache component that caches the data items
     * @param string|array $tags
     */
    public static function invalidate($cache, $tags)
    {
        $keys = [];
        foreach ((array) $tags as $tag) {
            $keys[] = $cache->buildKey([__CLASS__, $tag]);
        }
        static::touchKeys($cache, $keys);
    }

    /**
     * Generates the timestamp for the specified cache keys.
     * @param Cache $cache
     * @param string[] $keys
     * @return array the timestamp indexed by cache keys
     */
    protected static function touchKeys($cache, $keys)
    {
        $items = [];
        $time = microtime();
        foreach ($keys as $key) {
            $items[$key] = $time;
        }
        $cache->multiSet($items);
        return $items;
    }

    /**
     * Returns the timestamps for the specified tags.
     * @param Cache $cache
     * @param string[] $tags
     * @return array the timestamps indexed by the specified tags.
     */
    protected function getTimestamps($cache, $tags)
    {
        if (empty($tags)) {
            return [];
        }

        $keys = [];
        foreach ($tags as $tag) {
            $keys[] = $cache->buildKey([__CLASS__, $tag]);
        }

        return $cache->multiGet($keys);
    }
}


text:
import json
import threading
import time
from datetime import datetime

import pandas as pd
import redis
from flask import Flask
from flask_cors import CORS
from flask_restful import Api, Resource

import util
from train import TrainCenter
from util.config import config
from util.log import log
from util.singleton import SingletonMixin

app = Flask(__name__)
CORS(app)
api = Api(app)

LOOP_INTERVAL_SEC = 5

class LogCollector(SingletonMixin):
    def __init__(self):
        super(LogCollector, self).__init__()
        info = config['pubsub']
        self.host = info[0]
        self.port = int(info[1])
        self.r = redis.StrictRedis(host=self.host, port=self.port, db=0)
        self.p = self.r.pubsub()
        self.p.psubscribe('*')

    def collect(self):
        # TODO: get message from pub/sub server
        while True:
            raw_message = self.p.get_message()
            if not raw_message:
                break
            # log.warn('raw_message: %s' % raw_message)
            self._handle(raw_message)

    def _handle(self, raw_message):
        data = util.extract_json2(raw_message)
        if data is None or 'key' not in data:
            return

        key = data['key']
        # if key == 'START_ML_WORKER':
        #     worker_id = data['worker_id']
        #     Center().connect_ml_worker(worker_id)
        # elif key == 'START_ML_TRAIN':
        #     worker_id = data['worker_id']
        #     code_name = data['code_name']
        #     train_id = data['train_id']
        #     Center().start_train(worker_id, code_name, train_id)
        # elif key == 'FINISH_ML_TRAIN':
        #     worker_id = data['worker_id']
        #     code_name = data['code_name']
        #     train_id = data['train_id']
        #     Center().finish_train(worker_id, code_name, train_id)
        # elif key == 'REGISTER_TRAIN':
        #     Center().register_train(data)
        if key == 'UPDATE_PS':
            Center().update_ps(data)
        elif key == 'UPDATE_PS_DETAIL':
            Center().update_ps_detail(data)
        elif key == 'MEASUREMENT':
            Center().update_measurement(data)
        elif key == 'TRAIN_NOW':
            TrainCenter().train_now(data)
        elif key == 'set_variable':
            pass
        elif key == 'average':
            pass
        else:
            log.error('IMPME: %s' % key)

def start_sub_log_and_command():
    log.warn('START THREAD: admin / subscribe log and command')
    while True:
        LogCollector().collect()
        # time.sleep(0.001)
        Center().loop_count += 1
        time.sleep(LOOP_INTERVAL_SEC)

def start_train_center():
    log.warn('START THREAD: admin / train-center')
    while True:
        TrainCenter().update()
        time.sleep(LOOP_INTERVAL_SEC)

class MeasureContainer(object):
    def __init__(self):
        self.train_ids = set([])
        self.group_ids = set([])
        self.ps_dict = {}  # group_id: { worker_id: data }
        self.controller_dict = {}  # group_id: data

        self.df = pd.DataFrame(
            columns=[
                'train_id', 'group_id', 'worker_id', 'parallel_count',
                'load_rtt', 'save_rtt', 'controller_rtt',
                'data_size', 'success', 'cal',
            ],
            dtype='float')

    def _to_list(self, data):
        load_end = int(data['num_01_after_load_variables'])
        load_start = int(data['num_01_before_load_variables'])
        load_rtt = load_end - load_start

        save_end = int(data['num_02_after_save_variables'])
        save_start = int(data['num_02_before_save_variables'])
        save_rtt = save_end - save_start
        controller_rtt = int(data['num_05_after_pub_on_controller']) - int(
            data['num_03_after_get_on_controller'])
        cal = int(data['cal'])
        success = 1
        return [
            data['train_id'],
            data['group_id'],
            data['worker_id'],
            data['parallel_count'],
            load_rtt,
            save_rtt,
            controller_rtt,
            data['data_size'],
            success,
            cal,
        ]

    def update(self, data):
        node_type = data['node_type']
        group_id = data['group_id']
        if node_type == 'ps':
            self._update_ps(group_id, data)
        else:
            self._update_controller(group_id, data)

    def get_stat_of_train(self):
        d = json.loads(self.get_train_stat_json())
        d2 = json.loads(
            self.df.groupby(['train_id'])['group_id'].count().to_json(
                orient='index'))
        for k, v in d.iteritems():
            v['count'] = d2[k]
        return d

    def get_train_stat_json(self):
        df = self.df
        return df.groupby(['train_id']).mean().to_json(orient='index')

    def get_group_stat_json(self):
        df = self.df
        return df.groupby(['group_id']).mean().to_json(orient='index')

    def _update_ps(self, group_id, raw):
        worker_id = raw['worker_id']
        raw['merged'] = False

        if group_id in self.controller_dict:
            controller_data = self.controller_dict[group_id]
            merged_data = self._merge(raw, controller_data)
            self._append(merged_data)
        else:
            d = self.ps_dict
            if group_id not in d:
                d[group_id] = {}
            group = d[group_id]
            group[worker_id] = raw

    def _merge(self, ps_data, controller_data):
        return util.merge_two_dicts(ps_data, controller_data)

    def _append(self, merged_data):
        l = self._to_list(merged_data)
        df = self.df
        df.loc[len(df)] = l

    def _update_controller(self, group_id, data):
        self.controller_dict[group_id] = data

        psd = self.ps_dict
        if group_id in psd:
            group_dict = psd[group_id]
            for ps in group_dict.itervalues():
                merged_data = self._merge(ps, data)
                self._append(merged_data)
            del psd[group_id]

class Center(SingletonMixin):
    def __init__(self):
        super(Center, self).__init__()
        self.loop_count = 0
        self.ml_worker = {}
        self.ps = {}
        self.ps_detail = []
        self.measure_container = MeasureContainer()

    # def start_train(self, worker_id, code_name, train_id):
    #     msg = 'Start (%s:%s)' % (code_name, train_id)
    #     w = self.ml_worker[worker_id]
    #     w['description'] = msg

    # def finish_train(self, worker_id, code_name, train_id):
    #     msg = 'Finish (%s:%s)' % (code_name, train_id)
    #     w = self.ml_worker[worker_id]
    #     w['description'] = msg

    # def connect_ml_worker(self, worker_id):
    #     self.ml_worker[worker_id] = {
    #         'worker_id': worker_id,
    #         'description': 'connected',
    #     }

    def update_ps_detail(self, data):
        group_id = data['group_id']
        msg = data['msg']
        worker_id = data['worker_id']
        now = datetime.now()
        now_str = now.strftime('%H:%M:%S.%f')
        self.ps_detail.append({
            'group_id': group_id,
            'worker_id': worker_id,
            'msg': msg,
            'time': now_str})

    def update_ps(self, data):
        v = data['value']
        group_id = v['group_id']
        self.ps[group_id] = v

    def update_measurement(self, data):
        self.measure_container.update(data)

    def get_data(self):
        return {
            'loop_count': self.loop_count,
            'train': TrainCenter().get_info(),
            'worker': [v for k, v in self.ml_worker.iteritems()],
            'ps': [v for k, v in self.ps.iteritems()],
            'ps_detail': self.ps_detail,
            'stat_of_group': json.loads(
                self.measure_container.get_group_stat_json()),
            'stat_of_train': self.measure_container.get_stat_of_train(),
        }

class DefaultRoute(Resource):
    def get(self):
        return Center().get_data()

api.add_resource(DefaultRoute, '/')

def run():
    t1 = threading.Thread(target=start_sub_log_and_command)
    t1.daemon = True
    t1.start()

    t2 = threading.Thread(target=start_train_center)
    t2.daemon = True
    t2.start()

    admin_config = config['admin']
    app.run(host='0.0.0.0', port=int(admin_config['port']), debug=False)
    # app.run(port=int(admin_config['port']), debug=True)

if __name__ == '__main__':
    run()


text:
/*
 * PHY driver for mv88e61xx ethernet switches.
 *
 * This driver configures the mv88e61xx for basic use as a PHY.  The switch
 * supports a VLAN configuration that determines how traffic will be routed
 * between the ports.  This driver uses a simple configuration that routes
 * traffic from each PHY port only to the CPU port, and from the CPU port to
 * any PHY port.
 *
 * The configuration determines which PHY ports to activate using the
 * CONFIG_MV88E61XX_PHY_PORTS bitmask.  Setting bit 0 will activate port 0, bit
 * 1 activates port 1, etc.  Do not set the bit for the port the CPU is
 * connected to unless it is connected over a PHY interface (not MII).
 *
 * This driver was written for and tested on the mv88e6176 with an SGMII
 * connection.  Other configurations should be supported, but some additions or
 * changes may be required.
 */

#include <common.h>

#include <bitfield.h>
#include <errno.h>
#include <malloc.h>
#include <miiphy.h>
#include <netdev.h>

#define PHY_AUTONEGOTIATE_TIMEOUT	5000

#define PORT_COUNT			11
#define PORT_MASK			((1 << PORT_COUNT) - 1)

/* Device addresses */
#define DEVADDR_PHY(p)			(p)
#define DEVADDR_PORT(p)			(0x10 + (p))
#define DEVADDR_SERDES			0x0F
#define DEVADDR_GLOBAL_1		0x1B
#define DEVADDR_GLOBAL_2		0x1C

/* SMI indirection registers for multichip addressing mode */
#define SMI_CMD_REG			0x00
#define SMI_DATA_REG			0x01

/* Global registers */
#define GLOBAL1_STATUS			0x00
#define GLOBAL1_CTRL			0x04
#define GLOBAL1_MON_CTRL		0x1A

/* Global 2 registers */
#define GLOBAL2_REG_PHY_CMD		0x18
#define GLOBAL2_REG_PHY_DATA		0x19

/* Port registers */
#define PORT_REG_STATUS			0x00
#define PORT_REG_PHYS_CTRL		0x01
#define PORT_REG_SWITCH_ID		0x03
#define PORT_REG_CTRL			0x04
#define PORT_REG_VLAN_MAP		0x06
#define PORT_REG_VLAN_ID		0x07

/* Phy registers */
#define PHY_REG_CTRL1			0x10
#define PHY_REG_STATUS1			0x11
#define PHY_REG_PAGE			0x16

/* Serdes registers */
#define SERDES_REG_CTRL_1		0x10

/* Phy page numbers */
#define PHY_PAGE_COPPER			0
#define PHY_PAGE_SERDES			1

/* Register fields */
#define GLOBAL1_CTRL_SWRESET		BIT(15)

#define GLOBAL1_MON_CTRL_CPUDEST_SHIFT	4
#define GLOBAL1_MON_CTRL_CPUDEST_WIDTH	4

#define PORT_REG_STATUS_LINK		BIT(11)
#define PORT_REG_STATUS_DUPLEX		BIT(10)

#define PORT_REG_STATUS_SPEED_SHIFT	8
#define PORT_REG_STATUS_SPEED_WIDTH	2
#define PORT_REG_STATUS_SPEED_10	0
#define PORT_REG_STATUS_SPEED_100	1
#define PORT_REG_STATUS_SPEED_1000	2

#define PORT_REG_STATUS_CMODE_MASK		0xF
#define PORT_REG_STATUS_CMODE_100BASE_X		0x8
#define PORT_REG_STATUS_CMODE_1000BASE_X	0x9
#define PORT_REG_STATUS_CMODE_SGMII		0xa

#define PORT_REG_PHYS_CTRL_PCS_AN_EN	BIT(10)
#define PORT_REG_PHYS_CTRL_PCS_AN_RST	BIT(9)
#define PORT_REG_PHYS_CTRL_FC_VALUE	BIT(7)
#define PORT_REG_PHYS_CTRL_FC_FORCE	BIT(6)
#define PORT_REG_PHYS_CTRL_LINK_VALUE	BIT(5)
#define PORT_REG_PHYS_CTRL_LINK_FORCE	BIT(4)
#define PORT_REG_PHYS_CTRL_DUPLEX_VALUE	BIT(3)
#define PORT_REG_PHYS_CTRL_DUPLEX_FORCE	BIT(2)
#define PORT_REG_PHYS_CTRL_SPD1000	BIT(1)
#define PORT_REG_PHYS_CTRL_SPD_MASK	(BIT(1) | BIT(0))

#define PORT_REG_CTRL_PSTATE_SHIFT	0
#define PORT_REG_CTRL_PSTATE_WIDTH	2

#define PORT_REG_VLAN_ID_DEF_VID_SHIFT	0
#define PORT_REG_VLAN_ID_DEF_VID_WIDTH	12

#define PORT_REG_VLAN_MAP_TABLE_SHIFT	0
#define PORT_REG_VLAN_MAP_TABLE_WIDTH	11

#define SERDES_REG_CTRL_1_FORCE_LINK	BIT(10)

#define PHY_REG_CTRL1_ENERGY_DET_SHIFT	8
#define PHY_REG_CTRL1_ENERGY_DET_WIDTH	2

/* Field values */
#define PORT_REG_CTRL_PSTATE_DISABLED	0
#define PORT_REG_CTRL_PSTATE_FORWARD	3

#define PHY_REG_CTRL1_ENERGY_DET_OFF	0
#define PHY_REG_CTRL1_ENERGY_DET_SENSE_ONLY	2
#define PHY_REG_CTRL1_ENERGY_DET_SENSE_XMIT	3

/* PHY Status Register */
#define PHY_REG_STATUS1_SPEED		0xc000
#define PHY_REG_STATUS1_GBIT		0x8000
#define PHY_REG_STATUS1_100		0x4000
#define PHY_REG_STATUS1_DUPLEX		0x2000
#define PHY_REG_STATUS1_SPDDONE		0x0800
#define PHY_REG_STATUS1_LINK		0x0400
#define PHY_REG_STATUS1_ENERGY		0x0010

/*
 * Macros for building commands for indirect addressing modes.  These are valid
 * for both the indirect multichip addressing mode and the PHY indirection
 * required for the writes to any PHY register.
 */
#define SMI_BUSY			BIT(15)
#define SMI_CMD_CLAUSE_22		BIT(12)
#define SMI_CMD_CLAUSE_22_OP_READ	(2 << 10)
#define SMI_CMD_CLAUSE_22_OP_WRITE	(1 << 10)

#define SMI_CMD_READ			(SMI_BUSY | SMI_CMD_CLAUSE_22 | \
					 SMI_CMD_CLAUSE_22_OP_READ)
#define SMI_CMD_WRITE			(SMI_BUSY | SMI_CMD_CLAUSE_22 | \
					 SMI_CMD_CLAUSE_22_OP_WRITE)

#define SMI_CMD_ADDR_SHIFT		5
#define SMI_CMD_ADDR_WIDTH		5
#define SMI_CMD_REG_SHIFT		0
#define SMI_CMD_REG_WIDTH		5

/* Check for required macros */
#ifndef CONFIG_MV88E61XX_PHY_PORTS
#error Define CONFIG_MV88E61XX_PHY_PORTS to indicate which physical ports \
	to activate
#endif
#ifndef CONFIG_MV88E61XX_CPU_PORT
#error Define CONFIG_MV88E61XX_CPU_PORT to the port the CPU is attached to
#endif

/*
 *  These are ports without PHYs that may be wired directly
 * to other serdes interfaces
 */
#ifndef CONFIG_MV88E61XX_FIXED_PORTS
#define CONFIG_MV88E61XX_FIXED_PORTS 0
#endif

/* ID register values for different switch models */
#define PORT_SWITCH_ID_6096		0x0980
#define PORT_SWITCH_ID_6097		0x0990
#define PORT_SWITCH_ID_6172		0x1720
#define PORT_SWITCH_ID_6176		0x1760
#define PORT_SWITCH_ID_6240		0x2400
#define PORT_SWITCH_ID_6352		0x3520

struct mv88e61xx_phy_priv {
	struct mii_dev *mdio_bus;
	int smi_addr;
	int id;
};

static inline int smi_cmd(int cmd, int addr, int reg)
{
	cmd = bitfield_replace(cmd, SMI_CMD_ADDR_SHIFT, SMI_CMD_ADDR_WIDTH,
			       addr);
	cmd = bitfield_replace(cmd, SMI_CMD_REG_SHIFT, SMI_CMD_REG_WIDTH, reg);
	return cmd;
}

static inline int smi_cmd_read(int addr, int reg)
{
	return smi_cmd(SMI_CMD_READ, addr, reg);
}

static inline int smi_cmd_write(int addr, int reg)
{
	return smi_cmd(SMI_CMD_WRITE, addr, reg);
}

__weak int mv88e61xx_hw_reset(struct phy_device *phydev)
{
	return 0;
}

/* Wait for the current SMI indirect command to complete */
static int mv88e61xx_smi_wait(struct mii_dev *bus, int smi_addr)
{
	int val;
	u32 timeout = 100;

	do {
		val = bus->read(bus, smi_addr, MDIO_DEVAD_NONE, SMI_CMD_REG);
		if (val >= 0 && (val & SMI_BUSY) == 0)
			return 0;

		mdelay(1);
	} while (--timeout);

	puts("SMI busy timeout\n");
	return -ETIMEDOUT;
}

/*
 * The mv88e61xx has three types of addresses: the smi bus address, the device
 * address, and the register address.  The smi bus address distinguishes it on
 * the smi bus from other PHYs or switches.  The device address determines
 * which on-chip register set you are reading/writing (the various PHYs, their
 * associated ports, or global configuration registers).  The register address
 * is the offset of the register you are reading/writing.
 *
 * When the mv88e61xx is hardware configured to have address zero, it behaves in
 * single-chip addressing mode, where it responds to all SMI addresses, using
 * the smi address as its device address.  This obviously only works when this
 * is the only chip on the SMI bus.  This allows the driver to access device
 * registers without using indirection.  When the chip is configured to a
 * non-zero address, it only responds to that SMI address and requires indirect
 * writes to access the different device addresses.
 */
static int mv88e61xx_reg_read(struct phy_device *phydev, int dev, int reg)
{
	struct mv88e61xx_phy_priv *priv = phydev->priv;
	struct mii_dev *mdio_bus = priv->mdio_bus;
	int smi_addr = priv->smi_addr;
	int res;

	/* In single-chip mode, the device can be addressed directly */
	if (smi_addr == 0)
		return mdio_bus->read(mdio_bus, dev, MDIO_DEVAD_NONE, reg);

	/* Wait for the bus to become free */
	res = mv88e61xx_smi_wait(mdio_bus, smi_addr);
	if (res < 0)
		return res;

	/* Issue the read command */
	res = mdio_bus->write(mdio_bus, smi_addr, MDIO_DEVAD_NONE, SMI_CMD_REG,
			 smi_cmd_read(dev, reg));
	if (res < 0)
		return res;

	/* Wait for the read command to complete */
	res = mv88e61xx_smi_wait(mdio_bus, smi_addr);
	if (res < 0)
		return res;

	/* Read the data */
	res = mdio_bus->read(mdio_bus, smi_addr, MDIO_DEVAD_NONE, SMI_DATA_REG);
	if (res < 0)
		return res;

	return bitfield_extract(res, 0, 16);
}

/* See the comment above mv88e61xx_reg_read */
static int mv88e61xx_reg_write(struct phy_device *phydev, int dev, int reg,
			       u16 val)
{
	struct mv88e61xx_phy_priv *priv = phydev->priv;
	struct mii_dev *mdio_bus = priv->mdio_bus;
	int smi_addr = priv->smi_addr;
	int res;

	/* In single-chip mode, the device can be addressed directly */
	if (smi_addr == 0) {
		return mdio_bus->write(mdio_bus, dev, MDIO_DEVAD_NONE, reg,
				val);
	}

	/* Wait for the bus to become free */
	res = mv88e61xx_smi_wait(mdio_bus, smi_addr);
	if (res < 0)
		return res;

	/* Set the data to write */
	res = mdio_bus->write(mdio_bus, smi_addr, MDIO_DEVAD_NONE,
				SMI_DATA_REG, val);
	if (res < 0)
		return res;

	/* Issue the write command */
	res = mdio_bus->write(mdio_bus, smi_addr, MDIO_DEVAD_NONE, SMI_CMD_REG,
				smi_cmd_write(dev, reg));
	if (res < 0)
		return res;

	/* Wait for the write command to complete */
	res = mv88e61xx_smi_wait(mdio_bus, smi_addr);
	if (res < 0)
		return res;

	return 0;
}

static int mv88e61xx_phy_wait(struct phy_device *phydev)
{
	int val;
	u32 timeout = 100;

	do {
		val = mv88e61xx_reg_read(phydev, DEVADDR_GLOBAL_2,
					 GLOBAL2_REG_PHY_CMD);
		if (val >= 0 && (val & SMI_BUSY) == 0)
			return 0;

		mdelay(1);
	} while (--timeout);

	return -ETIMEDOUT;
}

static int mv88e61xx_phy_read_indirect(struct mii_dev *smi_wrapper, int dev,
		int devad, int reg)
{
	struct phy_device *phydev;
	int res;

	phydev = (struct phy_device *)smi_wrapper->priv;

	/* Issue command to read */
	res = mv88e61xx_reg_write(phydev, DEVADDR_GLOBAL_2,
				  GLOBAL2_REG_PHY_CMD,
				  smi_cmd_read(dev, reg));

	/* Wait for data to be read */
	res = mv88e61xx_phy_wait(phydev);
	if (res < 0)
		return res;

	/* Read retrieved data */
	return mv88e61xx_reg_read(phydev, DEVADDR_GLOBAL_2,
				  GLOBAL2_REG_PHY_DATA);
}

static int mv88e61xx_phy_write_indirect(struct mii_dev *smi_wrapper, int dev,
		int devad, int reg, u16 data)
{
	struct phy_device *phydev;
	int res;

	phydev = (struct phy_device *)smi_wrapper->priv;

	/* Set the data to write */
	res = mv88e61xx_reg_write(phydev, DEVADDR_GLOBAL_2,
				  GLOBAL2_REG_PHY_DATA, data);
	if (res < 0)
		return res;
	/* Issue the write command */
	res = mv88e61xx_reg_write(phydev, DEVADDR_GLOBAL_2,
				  GLOBAL2_REG_PHY_CMD,
				  smi_cmd_write(dev, reg));
	if (res < 0)
		return res;

	/* Wait for command to complete */
	return mv88e61xx_phy_wait(phydev);
}

/* Wrapper function to make calls to phy_read_indirect simpler */
static int mv88e61xx_phy_read(struct phy_device *phydev, int phy, int reg)
{
	return mv88e61xx_phy_read_indirect(phydev->bus, DEVADDR_PHY(phy),
					   MDIO_DEVAD_NONE, reg);
}

/* Wrapper function to make calls to phy_read_indirect simpler */
static int mv88e61xx_phy_write(struct phy_device *phydev, int phy,
		int reg, u16 val)
{
	return mv88e61xx_phy_write_indirect(phydev->bus, DEVADDR_PHY(phy),
					    MDIO_DEVAD_NONE, reg, val);
}

static int mv88e61xx_port_read(struct phy_device *phydev, u8 port, u8 reg)
{
	return mv88e61xx_reg_read(phydev, DEVADDR_PORT(port), reg);
}

static int mv88e61xx_port_write(struct phy_device *phydev, u8 port, u8 reg,
								u16 val)
{
	return mv88e61xx_reg_write(phydev, DEVADDR_PORT(port), reg, val);
}

static int mv88e61xx_set_page(struct phy_device *phydev, u8 phy, u8 page)
{
	return mv88e61xx_phy_write(phydev, phy, PHY_REG_PAGE, page);
}

static int mv88e61xx_get_switch_id(struct phy_device *phydev)
{
	int res;

	res = mv88e61xx_port_read(phydev, 0, PORT_REG_SWITCH_ID);
	if (res < 0)
		return res;
	return res & 0xfff0;
}

static bool mv88e61xx_6352_family(struct phy_device *phydev)
{
	struct mv88e61xx_phy_priv *priv = phydev->priv;

	switch (priv->id) {
	case PORT_SWITCH_ID_6172:
	case PORT_SWITCH_ID_6176:
	case PORT_SWITCH_ID_6240:
	case PORT_SWITCH_ID_6352:
		return true;
	}
	return false;
}

static int mv88e61xx_get_cmode(struct phy_device *phydev, u8 port)
{
	int res;

	res = mv88e61xx_port_read(phydev, port, PORT_REG_STATUS);
	if (res < 0)
		return res;
	return res & PORT_REG_STATUS_CMODE_MASK;
}

static int mv88e61xx_parse_status(struct phy_device *phydev)
{
	unsigned int speed;
	unsigned int mii_reg;

	mii_reg = phy_read(phydev, MDIO_DEVAD_NONE, PHY_REG_STATUS1);

	if ((mii_reg & PHY_REG_STATUS1_LINK) &&
	    !(mii_reg & PHY_REG_STATUS1_SPDDONE)) {
		int i = 0;

		puts("Waiting for PHY realtime link");
		while (!(mii_reg & PHY_REG_STATUS1_SPDDONE)) {
			/* Timeout reached ? */
			if (i > PHY_AUTONEGOTIATE_TIMEOUT) {
				puts(" TIMEOUT !\n");
				phydev->link = 0;
				break;
			}

			if ((i++ % 1000) == 0)
				putc('.');
			udelay(1000);
			mii_reg = phy_read(phydev, MDIO_DEVAD_NONE,
					PHY_REG_STATUS1);
		}
		puts(" done\n");
		udelay(500000);	/* another 500 ms (results in faster booting) */
	} else {
		if (mii_reg & PHY_REG_STATUS1_LINK)
			phydev->link = 1;
		else
			phydev->link = 0;
	}

	if (mii_reg & PHY_REG_STATUS1_DUPLEX)
		phydev->duplex = DUPLEX_FULL;
	else
		phydev->duplex = DUPLEX_HALF;

	speed = mii_reg & PHY_REG_STATUS1_SPEED;

	switch (speed) {
	case PHY_REG_STATUS1_GBIT:
		phydev->speed = SPEED_1000;
		break;
	case PHY_REG_STATUS1_100:
		phydev->speed = SPEED_100;
		break;
	default:
		phydev->speed = SPEED_10;
		break;
	}

	return 0;
}

static int mv88e61xx_switch_reset(struct phy_device *phydev)
{
	int time;
	int val;
	u8 port;

	/* Disable all ports */
	for (port = 0; port < PORT_COUNT; port++) {
		val = mv88e61xx_port_read(phydev, port, PORT_REG_CTRL);
		if (val < 0)
			return val;
		val = bitfield_replace(val, PORT_REG_CTRL_PSTATE_SHIFT,
				       PORT_REG_CTRL_PSTATE_WIDTH,
				       PORT_REG_CTRL_PSTATE_DISABLED);
		val = mv88e61xx_port_write(phydev, port, PORT_REG_CTRL, val);
		if (val < 0)
			return val;
	}

	/* Wait 2 ms for queues to drain */
	udelay(2000);

	/* Reset switch */
	val = mv88e61xx_reg_read(phydev, DEVADDR_GLOBAL_1, GLOBAL1_CTRL);
	if (val < 0)
		return val;
	val |= GLOBAL1_CTRL_SWRESET;
	val = mv88e61xx_reg_write(phydev, DEVADDR_GLOBAL_1,
				     GLOBAL1_CTRL, val);
	if (val < 0)
		return val;

	/* Wait up to 1 second for switch reset complete */
	for (time = 1000; time; time--) {
		val = mv88e61xx_reg_read(phydev, DEVADDR_GLOBAL_1,
					    GLOBAL1_CTRL);
		if (val >= 0 && ((val & GLOBAL1_CTRL_SWRESET) == 0))
			break;
		udelay(1000);
	}
	if (!time)
		return -ETIMEDOUT;

	return 0;
}

static int mv88e61xx_serdes_init(struct phy_device *phydev)
{
	int val;

	val = mv88e61xx_set_page(phydev, DEVADDR_SERDES, PHY_PAGE_SERDES);
	if (val < 0)
		return val;

	/* Power up serdes module */
	val = mv88e61xx_phy_read(phydev, DEVADDR_SERDES, MII_BMCR);
	if (val < 0)
		return val;
	val &= ~(BMCR_PDOWN);
	val = mv88e61xx_phy_write(phydev, DEVADDR_SERDES, MII_BMCR, val);
	if (val < 0)
		return val;

	return 0;
}

static int mv88e61xx_port_enable(struct phy_device *phydev, u8 port)
{
	int val;

	val = mv88e61xx_port_read(phydev, port, PORT_REG_CTRL);
	if (val < 0)
		return val;
	val = bitfield_replace(val, PORT_REG_CTRL_PSTATE_SHIFT,
			       PORT_REG_CTRL_PSTATE_WIDTH,
			       PORT_REG_CTRL_PSTATE_FORWARD);
	val = mv88e61xx_port_write(phydev, port, PORT_REG_CTRL, val);
	if (val < 0)
		return val;

	return 0;
}

static int mv88e61xx_port_set_vlan(struct phy_device *phydev, u8 port,
							u16 mask)
{
	int val;

	/* Set VID to port number plus one */
	val = mv88e61xx_port_read(phydev, port, PORT_REG_VLAN_ID);
	if (val < 0)
		return val;
	val = bitfield_replace(val, PORT_REG_VLAN_ID_DEF_VID_SHIFT,
			       PORT_REG_VLAN_ID_DEF_VID_WIDTH,
			       port + 1);
	val = mv88e61xx_port_write(phydev, port, PORT_REG_VLAN_ID, val);
	if (val < 0)
		return val;

	/* Set VID mask */
	val = mv88e61xx_port_read(phydev, port, PORT_REG_VLAN_MAP);
	if (val < 0)
		return val;
	val = bitfield_replace(val, PORT_REG_VLAN_MAP_TABLE_SHIFT,
			       PORT_REG_VLAN_MAP_TABLE_WIDTH,
			       mask);
	val = mv88e61xx_port_write(phydev, port, PORT_REG_VLAN_MAP, val);
	if (val < 0)
		return val;

	return 0;
}

static int mv88e61xx_read_port_config(struct phy_device *phydev, u8 port)
{
	int res;
	int val;
	bool forced = false;

	val = mv88e61xx_port_read(phydev, port, PORT_REG_STATUS);
	if (val < 0)
		return val;
	if (!(val & PORT_REG_STATUS_LINK)) {
		/* Temporarily force link to read port configuration */
		u32 timeout = 100;
		forced = true;

		val = mv88e61xx_port_read(phydev, port, PORT_REG_PHYS_CTRL);
		if (val < 0)
			return val;
		val |= (PORT_REG_PHYS_CTRL_LINK_FORCE |
				PORT_REG_PHYS_CTRL_LINK_VALUE);
		val = mv88e61xx_port_write(phydev, port, PORT_REG_PHYS_CTRL,
					   val);
		if (val < 0)
			return val;

		/* Wait for status register to reflect forced link */
		do {
			val = mv88e61xx_port_read(phydev, port,
						  PORT_REG_STATUS);
			if (val < 0) {
				res = -EIO;
				goto unforce;
			}
			if (val & PORT_REG_STATUS_LINK)
				break;
		} while (--timeout);

		if (timeout == 0) {
			res = -ETIMEDOUT;
			goto unforce;
		}
	}

	if (val & PORT_REG_STATUS_DUPLEX)
		phydev->duplex = DUPLEX_FULL;
	else
		phydev->duplex = DUPLEX_HALF;

	val = bitfield_extract(val, PORT_REG_STATUS_SPEED_SHIFT,
			       PORT_REG_STATUS_SPEED_WIDTH);
	switch (val) {
	case PORT_REG_STATUS_SPEED_1000:
		phydev->speed = SPEED_1000;
		break;
	case PORT_REG_STATUS_SPEED_100:
		phydev->speed = SPEED_100;
		break;
	default:
		phydev->speed = SPEED_10;
		break;
	}

	res = 0;

unforce:
	if (forced) {
		val = mv88e61xx_port_read(phydev, port, PORT_REG_PHYS_CTRL);
		if (val < 0)
			return val;
		val &= ~(PORT_REG_PHYS_CTRL_LINK_FORCE |
				PORT_REG_PHYS_CTRL_LINK_VALUE);
		val = mv88e61xx_port_write(phydev, port, PORT_REG_PHYS_CTRL,
					   val);
		if (val < 0)
			return val;
	}

	return res;
}

static int mv88e61xx_set_cpu_port(struct phy_device *phydev)
{
	int val;

	/* Set CPUDest */
	val = mv88e61xx_reg_read(phydev, DEVADDR_GLOBAL_1, GLOBAL1_MON_CTRL);
	if (val < 0)
		return val;
	val = bitfield_replace(val, GLOBAL1_MON_CTRL_CPUDEST_SHIFT,
			       GLOBAL1_MON_CTRL_CPUDEST_WIDTH,
			       CONFIG_MV88E61XX_CPU_PORT);
	val = mv88e61xx_reg_write(phydev, DEVADDR_GLOBAL_1,
				     GLOBAL1_MON_CTRL, val);
	if (val < 0)
		return val;

	/* Allow CPU to route to any port */
	val = PORT_MASK & ~(1 << CONFIG_MV88E61XX_CPU_PORT);
	val = mv88e61xx_port_set_vlan(phydev, CONFIG_MV88E61XX_CPU_PORT, val);
	if (val < 0)
		return val;

	/* Enable CPU port */
	val = mv88e61xx_port_enable(phydev, CONFIG_MV88E61XX_CPU_PORT);
	if (val < 0)
		return val;

	val = mv88e61xx_read_port_config(phydev, CONFIG_MV88E61XX_CPU_PORT);
	if (val < 0)
		return val;

	/* If CPU is connected to serdes, initialize serdes */
	if (mv88e61xx_6352_family(phydev)) {
		val = mv88e61xx_get_cmode(phydev, CONFIG_MV88E61XX_CPU_PORT);
		if (val < 0)
			return val;
		if (val == PORT_REG_STATUS_CMODE_100BASE_X ||
		    val == PORT_REG_STATUS_CMODE_1000BASE_X ||
		    val == PORT_REG_STATUS_CMODE_SGMII) {
			val = mv88e61xx_serdes_init(phydev);
			if (val < 0)
				return val;
		}
	}

	return 0;
}

static int mv88e61xx_switch_init(struct phy_device *phydev)
{
	static int init;
	int res;

	if (init)
		return 0;

	res = mv88e61xx_switch_reset(phydev);
	if (res < 0)
		return res;

	res = mv88e61xx_set_cpu_port(phydev);
	if (res < 0)
		return res;

	init = 1;

	return 0;
}

static int mv88e61xx_phy_enable(struct phy_device *phydev, u8 phy)
{
	int val;

	val = mv88e61xx_phy_read(phydev, phy, MII_BMCR);
	if (val < 0)
		return val;
	val &= ~(BMCR_PDOWN);
	val = mv88e61xx_phy_write(phydev, phy, MII_BMCR, val);
	if (val < 0)
		return val;

	return 0;
}

static int mv88e61xx_phy_setup(struct phy_device *phydev, u8 phy)
{
	int val;

	/*
	 * Enable energy-detect sensing on PHY, used to determine when a PHY
	 * port is physically connected
	 */
	val = mv88e61xx_phy_read(phydev, phy, PHY_REG_CTRL1);
	if (val < 0)
		return val;
	val = bitfield_replace(val, PHY_REG_CTRL1_ENERGY_DET_SHIFT,
			       PHY_REG_CTRL1_ENERGY_DET_WIDTH,
			       PHY_REG_CTRL1_ENERGY_DET_SENSE_XMIT);
	val = mv88e61xx_phy_write(phydev, phy, PHY_REG_CTRL1, val);
	if (val < 0)
		return val;

	return 0;
}

static int mv88e61xx_fixed_port_setup(struct phy_device *phydev, u8 port)
{
	int val;

	val = mv88e61xx_port_read(phydev, port, PORT_REG_PHYS_CTRL);
	if (val < 0)
		return val;

	val &= ~(PORT_REG_PHYS_CTRL_SPD_MASK |
		 PORT_REG_PHYS_CTRL_FC_VALUE);
	val |= PORT_REG_PHYS_CTRL_PCS_AN_EN |
	       PORT_REG_PHYS_CTRL_PCS_AN_RST |
	       PORT_REG_PHYS_CTRL_FC_FORCE |
	       PORT_REG_PHYS_CTRL_DUPLEX_VALUE |
	       PORT_REG_PHYS_CTRL_DUPLEX_FORCE |
	       PORT_REG_PHYS_CTRL_SPD1000;

	return mv88e61xx_port_write(phydev, port, PORT_REG_PHYS_CTRL,
				   val);
}

static int mv88e61xx_phy_config_port(struct phy_device *phydev, u8 phy)
{
	int val;

	val = mv88e61xx_port_enable(phydev, phy);
	if (val < 0)
		return val;

	val = mv88e61xx_port_set_vlan(phydev, phy,
			1 << CONFIG_MV88E61XX_CPU_PORT);
	if (val < 0)
		return val;

	return 0;
}

static int mv88e61xx_probe(struct phy_device *phydev)
{
	struct mii_dev *smi_wrapper;
	struct mv88e61xx_phy_priv *priv;
	int res;

	res = mv88e61xx_hw_reset(phydev);
	if (res < 0)
		return res;

	priv = malloc(sizeof(*priv));
	if (!priv)
		return -ENOMEM;

	memset(priv, 0, sizeof(*priv));

	/*
	 * This device requires indirect reads/writes to the PHY registers
	 * which the generic PHY code can't handle.  Make a wrapper MII device
	 * to handle reads/writes
	 */
	smi_wrapper = mdio_alloc();
	if (!smi_wrapper) {
		free(priv);
		return -ENOMEM;
	}

	/*
	 * Store the mdio bus in the private data, as we are going to replace
	 * the bus with the wrapper bus
	 */
	priv->mdio_bus = phydev->bus;

	/*
	 * Store the smi bus address in private data.  This lets us use the
	 * phydev addr field for device address instead, as the genphy code
	 * expects.
	 */
	priv->smi_addr = phydev->addr;

	/*
	 * Store the phy_device in the wrapper mii device. This lets us get it
	 * back when genphy functions call phy_read/phy_write.
	 */
	smi_wrapper->priv = phydev;
	strncpy(smi_wrapper->name, "indirect mii", sizeof(smi_wrapper->name));
	smi_wrapper->read = mv88e61xx_phy_read_indirect;
	smi_wrapper->write = mv88e61xx_phy_write_indirect;

	/* Replace the bus with the wrapper device */
	phydev->bus = smi_wrapper;

	phydev->priv = priv;

	priv->id = mv88e61xx_get_switch_id(phydev);

	return 0;
}

static int mv88e61xx_phy_config(struct phy_device *phydev)
{
	int res;
	int i;
	int ret = -1;

	res = mv88e61xx_switch_init(phydev);
	if (res < 0)
		return res;

	for (i = 0; i < PORT_COUNT; i++) {
		if ((1 << i) & CONFIG_MV88E61XX_PHY_PORTS) {
			phydev->addr = i;

			res = mv88e61xx_phy_enable(phydev, i);
			if (res < 0) {
				printf("Error enabling PHY %i\n", i);
				continue;
			}
			res = mv88e61xx_phy_setup(phydev, i);
			if (res < 0) {
				printf("Error setting up PHY %i\n", i);
				continue;
			}
			res = mv88e61xx_phy_config_port(phydev, i);
			if (res < 0) {
				printf("Error configuring PHY %i\n", i);
				continue;
			}

			res = genphy_config_aneg(phydev);
			if (res < 0) {
				printf("Error setting PHY %i autoneg\n", i);
				continue;
			}
			res = phy_reset(phydev);
			if (res < 0) {
				printf("Error resetting PHY %i\n", i);
				continue;
			}

			/* Return success if any PHY succeeds */
			ret = 0;
		} else if ((1 << i) & CONFIG_MV88E61XX_FIXED_PORTS) {
			res = mv88e61xx_fixed_port_setup(phydev, i);
			if (res < 0) {
				printf("Error configuring port %i\n", i);
				continue;
			}
		}
	}

	return ret;
}

static int mv88e61xx_phy_is_connected(struct phy_device *phydev)
{
	int val;

	val = mv88e61xx_phy_read(phydev, phydev->addr, PHY_REG_STATUS1);
	if (val < 0)
		return 0;

	/*
	 * After reset, the energy detect signal remains high for a few seconds
	 * regardless of whether a cable is connected.  This function will
	 * return false positives during this time.
	 */
	return (val & PHY_REG_STATUS1_ENERGY) == 0;
}

static int mv88e61xx_phy_startup(struct phy_device *phydev)
{
	int i;
	int link = 0;
	int res;
	int speed = phydev->speed;
	int duplex = phydev->duplex;

	for (i = 0; i < PORT_COUNT; i++) {
		if ((1 << i) & CONFIG_MV88E61XX_PHY_PORTS) {
			phydev->addr = i;
			if (!mv88e61xx_phy_is_connected(phydev))
				continue;
			res = genphy_update_link(phydev);
			if (res < 0)
				continue;
			res = mv88e61xx_parse_status(phydev);
			if (res < 0)
				continue;
			link = (link || phydev->link);
		}
	}
	phydev->link = link;

	/* Restore CPU interface speed and duplex after it was changed for
	 * other ports */
	phydev->speed = speed;
	phydev->duplex = duplex;

	return 0;
}

static struct phy_driver mv88e61xx_driver = {
	.name = "Marvell MV88E61xx",
	.uid = 0x01410eb1,
	.mask = 0xfffffff0,
	.features = PHY_GBIT_FEATURES,
	.probe = mv88e61xx_probe,
	.config = mv88e61xx_phy_config,
	.startup = mv88e61xx_phy_startup,
	.shutdown = &genphy_shutdown,
};

static struct phy_driver mv88e609x_driver = {
	.name = "Marvell MV88E609x",
	.uid = 0x1410c89,
	.mask = 0xfffffff0,
	.features = PHY_GBIT_FEATURES,
	.probe = mv88e61xx_probe,
	.config = mv88e61xx_phy_config,
	.startup = mv88e61xx_phy_startup,
	.shutdown = &genphy_shutdown,
};

int phy_mv88e61xx_init(void)
{
	phy_register(&mv88e61xx_driver);
	phy_register(&mv88e609x_driver);

	return 0;
}

/*
 * Overload weak get_phy_id definition since we need non-standard functions
 * to read PHY registers
 */
int get_phy_id(struct mii_dev *bus, int smi_addr, int devad, u32 *phy_id)
{
	struct phy_device temp_phy;
	struct mv88e61xx_phy_priv temp_priv;
	struct mii_dev temp_mii;
	int val;

	/*
	 * Buid temporary data structures that the chip reading code needs to
	 * read the ID
	 */
	temp_priv.mdio_bus = bus;
	temp_priv.smi_addr = smi_addr;
	temp_phy.priv = &temp_priv;
	temp_mii.priv = &temp_phy;

	val = mv88e61xx_phy_read_indirect(&temp_mii, 0, devad, MII_PHYSID1);
	if (val < 0)
		return -EIO;

	*phy_id = val << 16;

	val = mv88e61xx_phy_read_indirect(&temp_mii, 0, devad, MII_PHYSID2);
	if (val < 0)
		return -EIO;

	*phy_id |= (val & 0xffff);

	return 0;
}


text:
package com.lqg.dao;

import com.lqg.base.DaoSupport;
import com.lqg.model.Student;

public interface StudentDao extends DaoSupport<Student> {

}


text:
package ca.intelliagent.replayparser;

import ca.intelliagent.replayparser.packets.RawPacket;
import ca.intelliagent.replayparser.reader.BasicPacketReader;
import ca.intelliagent.replayparser.reader.PacketReader;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;

public class BasicPacketReaderTest {

    private static ByteBuffer buffer;
    private PacketReader packetReader;

    @BeforeClass
    public static void setUpClass() {
        buffer = getReplayRawData();
    }

    private static ByteBuffer getReplayRawData() {
        byte[] data = null;
        try {
            Path path = Paths.get(System.getProperty("user.dir") + "/src/test/resources/decompressedData.wia");
            data = Files.readAllBytes(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ByteBuffer.wrap(data);
    }

    @Before
    public void setUp() {
        packetReader = new BasicPacketReader(buffer);
    }

    @After
    public void tearDown() {
        buffer.rewind();
    }

    @Test
    public void rawDataSizeShouldNotBeZero() {
        assertTrue("Should be greater than 0", packetReader.getRawData().limit() > 0);
    }

    @Test
    public void lengthAndRawDataSizeShouldBeTheSameSize() {
        RawPacket next = packetReader.next();
        int payloadLength = next.getPayloadLength();

        assertEquals("Should have equal length", payloadLength, next.getPayload().limit());
    }
}


text:
using System.Collections.Generic;

namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
    internal partial class ExpressionBinder
    {
        // ----------------------------------------------------------------------------
        // This class takes an EXPRMEMGRP and a set of arguments and binds the arguments
        // to the best applicable method in the group.
        // ----------------------------------------------------------------------------

        internal class GroupToArgsBinderResult
        {
            public MethPropWithInst BestResult;
            public MethPropWithInst GetBestResult() { return BestResult; }
            public MethPropWithInst AmbiguousResult;
            public MethPropWithInst GetAmbiguousResult() { return AmbiguousResult; }
            public MethPropWithInst InaccessibleResult;
            public MethPropWithInst GetInaccessibleResult() { return InaccessibleResult; }
            public MethPropWithInst UninferrableResult;
            public MethPropWithInst GetUninferrableResult() { return UninferrableResult; }
            public MethPropWithInst InconvertibleResult;
            public GroupToArgsBinderResult()
            {
                BestResult = new MethPropWithInst();
                AmbiguousResult = new MethPropWithInst();
                InaccessibleResult = new MethPropWithInst();
                UninferrableResult = new MethPropWithInst();
                InconvertibleResult = new MethPropWithInst();
                _inconvertibleResults = new List<MethPropWithInst>();
            }

            private List<MethPropWithInst> _inconvertibleResults;

            /////////////////////////////////////////////////////////////////////////////////

            public void AddInconvertibleResult(
                MethodSymbol method,
                AggregateType currentType,
                TypeArray currentTypeArgs)
            {
                if (InconvertibleResult.Sym == null)
                {
                    // This is the first one, so set it for error reporting usage.
                    InconvertibleResult.Set(method, currentType, currentTypeArgs);
                }
                _inconvertibleResults.Add(new MethPropWithInst(method, currentType, currentTypeArgs));
            }

            /////////////////////////////////////////////////////////////////////////////////

            private static int NumberOfErrorTypes(TypeArray pTypeArgs)
            {
                int nCount = 0;
                for (int i = 0; i < pTypeArgs.Size; i++)
                {
                    if (pTypeArgs.Item(i).IsErrorType())
                    {
                        nCount++;
                    }
                }
                return nCount;
            }

            private static bool IsBetterThanCurrent(TypeArray pTypeArgs1, TypeArray pTypeArgs2)
            {
                int leftErrors = NumberOfErrorTypes(pTypeArgs1);
                int rightErrors = NumberOfErrorTypes(pTypeArgs2);

                if (leftErrors == rightErrors)
                {
                    int max = pTypeArgs1.Size > pTypeArgs2.Size ? pTypeArgs2.Size : pTypeArgs1.Size;

                    // If we dont have a winner yet, go through each element's type args.
                    for (int i = 0; i < max; i++)
                    {
                        if (pTypeArgs1.Item(i).IsAggregateType())
                        {
                            leftErrors += NumberOfErrorTypes(pTypeArgs1.Item(i).AsAggregateType().GetTypeArgsAll());
                        }
                        if (pTypeArgs2.Item(i).IsAggregateType())
                        {
                            rightErrors += NumberOfErrorTypes(pTypeArgs2.Item(i).AsAggregateType().GetTypeArgsAll());
                        }
                    }
                }
                return rightErrors < leftErrors;
            }

            public bool IsBetterUninferrableResult(TypeArray pTypeArguments)
            {
                if (UninferrableResult.Sym == null)
                {
                    // If we dont even have a result, then its definitely better.
                    return true;
                }
                if (pTypeArguments == null)
                {
                    return false;
                }
                return IsBetterThanCurrent(UninferrableResult.TypeArgs, pTypeArguments);
            }
        }
    }
}


text:
Please use the contact form below to get in touch. Or If you prefer to email please click here

  Loading...


text:
GoDeploy - [www.godeploy.com](http://www.godeploy.com/)

[![Build Status](https://secure.travis-ci.org/asgrim/godeploy.png?branch=master)](https://travis-ci.org/asgrim/godeploy)

Requirements
------------

* Linux
* PHP 5.5
* Composer
* Bower

Install
-------

```bash
$ git clone git@github.com:asgrim/godeploy.git
$ cd godeploy
$ git checkout [version]
$ composer install --no-dev
$ bower install
```

Replace `[version]` with the version you wish to use (just use `master` for latest).

Then copy `config/autoload/local.php.dist` to `config/autoload/local.php` and configure as you please (documentation does not exist for the structure yet...).

You'll need to create a MySQL database using `data/schema.sql` and override the database settings by copy `config/autoload/database.local.php.dist` to `config/autoload/database.local.php` and configuring your MySQL settings.

Generate the SSH private/public key to use, and put them in `data/ssh/id_rsa` and `data/ssh/id_rsa.pub` - if you put them elsewhere or use existing SSH keys, make sure to update the path in `config/autoload/local.php` - make sure they are accessible to PHP process.

Create cron job (note must run under www-data user):

```bash
$ sudo -u www-data crontab -e
* * * * * /usr/bin/php /home/godeploy-new/public/index.php update-repositories >/dev/null
```

Upgrade
-------

```bash
$ git fetch origin
$ git checkout [version]
$ composer install --no-dev
$ bower install
```


text:
const routers = [{
  name: 'userInfo',
  path: '/user/info',
  component: () => import('@/views/user/info.vue')
}, {
  name: 'modPwd',
  path: '/user/pwd',
  component: () => import('@/views/user/pwdmod.vue')
}]

export default routers


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Enum WhiteBalance
   | Picturepark.SDK.V1 API </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Enum WhiteBalance
   | Picturepark.SDK.V1 API ">
    <meta name="generator" content="docfx 2.16.7.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">
    <meta property="docfx:rel" content="../">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Enum WhiteBalance

Corresponds to crs.WhiteBalanceChoice

Namespace: Picturepark.SDK.V1.Contract

Syntax

public enum WhiteBalance

AsShot

Auto

Cloudy

Custom

Daylight

Flash

Fluorescent

Shade

Tungsten

              Back to top

            Copyright © 2015-2017 Microsoft
Generated by DocFX


text:
class SessionsController < Devise::SessionsController
    layout 'catarse_bootstrap'
    before_filter :force_https

    private

    def force_https
        if action_name == 'new' && !test_environment? && request.subdomain.nil?
            redirect_to request.url.sub!('http', 'https') if not request.ssl?
        end
    end
end


text:
<!-- START doctoc generated TOC please keep comment here to allow auto update -->

<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->

* [glamorous codemods](#glamorous-codemods)
  * [Running Codemods](#running-codemods)
  * [Available codemods](#available-codemods)
    * [`theme-move`](#theme-move)
    * [`glamorous-to-emotion`](#glamorous-to-emotion)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

# glamorous codemods

This is where we'll develop and release codemods for `glamorous`. We hopefully
wont have to do it all that much 😄

## Running Codemods

First, you'll need to clone the glamorous repo somewhere:

```bash
git clone https://github.com/paypal/glamorous.git
```

The codemods will then be available to you in `glamorous/other/codemods`

To run the codemods, you'll need to run `babel-codemod`. You can install that
package globally, or you can use `npx` (which comes pre-installed with npm@5.2.0
or greater). Here's how you use it with `npx`:

```bash
npx babel-codemod --plugin ./glamorous/other/codemods/{CODEMOD_NAME}.js "src/**/*.js"
```

Where `CODEMOD_NAME` is the filename of the codemod and `src/**/*.js` is a glob
that matches the files you want to run the codemods on.

> If you don't have `npx` installed, you can install `babel-codemod` globally
> and run the same script without the `npx` prefix.

## Available codemods

### `theme-move`

In glamorous v4 the dynamic props API changed from:

```javascript
function(props, theme, context) {}
```

To

```javascript
function(props, context) {}
```

Where `props` has a `theme` property.

This codemod updates your code to use the `theme` from props and remove the
`theme` argument.

### `glamorous-to-emotion`

[This codemod](https://github.com/TejasQ/babel-plugin-glamorous-to-emotion) helps migrate an existing codebase from glamorous to emotion.


text:
using System;

namespace CDLib.Domain
{
    public class Company
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string UserId { get; set; }
        public DateTime CreatedOn { get; set; }
        public DateTime? UpdatedOn { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string PostalCode { get; set; }
        public string PhoneNumber { get; set; }
    }
}


text:
{{-- Text Backpack CRUD filter --}}

name }}"
    filter-type="{{ $filter->type }}"
    filter-key="{{ $filter->key }}"
	class="nav-item dropdown {{ Request::get($filter->name) ? 'active' : '' }}">
	{{ $filter->label }}

		        <input class="form-control pull-right"
		        		id="text-filter-{{ $filter->key }}"
		        		type="text"
						@if ($filter->currentValue)
							value="{{ $filter->currentValue }}"
						@endif
		        		>

key }}-clear-button">

{{-- ########################################### --}}
{{-- Extra CSS and JS for this particular filter --}}

{{-- FILTERS EXTRA JS --}}
{{-- push things in the after_scripts section --}}

@push('crud_list_scripts')

@endpush
{{-- End of Extra CSS and JS --}}
{{-- ########################################## --}}


text:
/*
 * 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.
 */
package com.facebook.presto.block;

import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.BlockBuilderStatus;
import org.testng.annotations.Test;

import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

public class TestBlockBuilder
{
    @Test
    public void testMultipleValuesWithNull()
    {
        BlockBuilder blockBuilder = BIGINT.createBlockBuilder(new BlockBuilderStatus(), 10);
        blockBuilder.appendNull();
        BIGINT.writeLong(blockBuilder, 42);
        blockBuilder.appendNull();
        BIGINT.writeLong(blockBuilder, 42);
        Block block = blockBuilder.build();

        assertTrue(block.isNull(0));
        assertEquals(BIGINT.getLong(block, 1), 42L);
        assertTrue(block.isNull(2));
        assertEquals(BIGINT.getLong(block, 3), 42L);
    }
}