text:
import {
  User
} from '../models';

export const UserService = {
  getUsers(callback) {
    return User
      .find()
      .select('_id username')
      .exec(callback);
  },

  findById(userId, callback) {
    return User.findById(userId, callback);
  },

  findByUsername(username, callback) {
    return User.findOne({ username: username }, callback);
  },

  newUser(username, password, email, callback) {
    return new User({
      username: username,
      email: email || null,
      password: password,
      bookmarks: []
    }).save(callback);
  },

  removeByUsername(username, callback) {
    return User.remove({ username: username }, callback);
  },

  addBookmark(user, bookmark, callback) {
    user.bookmarks.push(bookmark);
    return user.save(callback);
  },

  editBookmark(user, bookmarkId, newBookmark, callback) {
    for (let bookmark of user.bookmarks) {
      if (bookmark._id === bookmarkId) {
        bookmark = newBookmark;
        break;
      }
    }
    return user.save(callback);
  },

  deleteBookmark(user, bookmarkId, callback) {
    user.bookmarks = user.bookmarks.filter(b => b._id !== bookmarkId);
    return user.save(callback);
  }
};


text:
.extLink {
	display:inline !important;
	padding-right:3px !important;
}

.small-font-awesome {
	font-size:10px;
	padding-right: 10px;
}

redpajama_set_name: RedPajamaGithub


text:
class <%= controller_class_name %>Controller < ApplicationController
  def index
    @<%= table_name %> = <%= class_name %>.all
  end

  def show
    @<%= file_name %> = <%= class_name %>.find(params[:id])
  end

  def new
    @<%= file_name %> = <%= class_name %>.new
  end

  def edit
    @<%= file_name %> = <%= class_name %>.find(params[:id])
  end

  def create
    @<%= file_name %> = <%= class_name %>.new(params[:<%= file_name %>])

    if @<%= file_name %>.save
      flash[:notice] = 'This <%= class_name.titleize.downcase %> was saved successfully.'
      redirect_to <%= table_name %>_url
    else
      render :action => "new"
    end
  end

  def update
    @<%= file_name %> = <%= class_name %>.find(params[:id])

    if @<%= file_name %>.update_attributes(params[:<%= file_name %>])
      flash[:notice] = 'This <%= class_name.titleize.downcase %> was updated successfully.'
      redirect_to <%= table_name %>_url
    else
      render :action => "edit"
    end
  end

  def destroy
    @<%= file_name %> = <%= class_name %>.find(params[:id])
    @<%= file_name %>.destroy

    redirect_to (<%= table_name %>_url)
  end
end


text:
<?php

namespace Sylius\Component\Core\Model;

use Sylius\Component\User\Model\User;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
class AdminUser extends User implements AdminUserInterface
{
    /**
     * @var string
     */
    protected $firstName;

    /**
     * @var string
     */
    protected $lastName;

    /**
     * @var string
     */
    protected $localeCode;

    /**
     * {@inheritdoc}
     */
    public function __construct()
    {
        parent::__construct();

        $this->roles = [AdminUserInterface::DEFAULT_ADMIN_ROLE];
    }

    /**
     * @return string
     */
    public function getFirstName()
    {
        return $this->firstName;
    }

    /**
     * @param string $firstName
     */
    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;
    }

    /**
     * @return string
     */
    public function getLastName()
    {
        return $this->lastName;
    }

    /**
     * @param string $lastName
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;
    }

    /**
     * {@inheritdoc}
     */
    public function getLocaleCode()
    {
        return $this->localeCode;
    }

    /**
     * {@inheritdoc}
     */
    public function setLocaleCode($code)
    {
        $this->localeCode = $code;
    }
}


text:
#import "PDF417BlackBox2TestCase.h"
#import "ZXMultiFormatReader.h"

/**
 * This test contains 480x240 images captured from an Android device at preview resolution.
 */
@implementation PDF417BlackBox2TestCase

- (id)initWithInvocation:(NSInvocation *)anInvocation {
  self = [super initWithInvocation:anInvocation
                testBasePathSuffix:@"Resources/blackbox/pdf417-2"
                     barcodeReader:[[[ZXMultiFormatReader alloc] init] autorelease]
                    expectedFormat:kBarcodeFormatPDF417];

  if (self) {
    [self addTest:19 tryHarderCount:19 maxMisreads:0 maxTryHarderMisreads:0 rotation:0.0f];
    [self addTest:17 tryHarderCount:17 maxMisreads:0 maxTryHarderMisreads:0 rotation:180.0f];
  }

  return self;
}

- (void)testBlackBox {
  [super runTests];
}

@end


text:
package al.jdi.dao.beans;

import java.util.List;

import al.jdi.dao.model.Campanha;

public interface CampanhaDao extends Dao<Campanha> {
  List<Campanha> listaAtivas();
}


text:
import sys

global api
selfuser = api.call('get_self')
visitor = api.call('get_visitor')

for xfer in api.call('get_xfers', username=selfuser):
  if xfer['sender'] == visitor:
    print 'You gave me', xfer['amount'], 'zoobars @', xfer['time']
    sys.exit(0)
  if xfer['recipient'] == visitor:
    print 'I gave you', xfer['amount'], 'zoobars @', xfer['time']
    sys.exit(0)

print 'We never exchanged zoobars!'


text:
package org.apache.camel.spring.processor.onexception;

/**
 * Exception thrown if the order cannot be processed
 */
public class OrderFailedException extends Exception {

    private static final long serialVersionUID = 1L;

    public OrderFailedException(String message) {
        super(message);
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Oscar's Defense - n montano</title>
    <meta name="description" content="Grease-stained plates covered the table, accompanied by staling pieces of      mediocre pizza while fluorescent lights rained down harshly on the dining esta...">

    <link href='https://fonts.googleapis.com/css?family=Roboto+Mono|Roboto:300,400,900,400italic' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="/css/main.css">
    <link rel="canonical" href="http://erikradio.github.io/2010/09/Oscar's-Defense">
    <link rel="alternate" type="application/rss+xml" title="n montano" href="http://erikradio.github.io/feed.xml">

        *

Oscar's Defense

<time datetime="2010-09-05T00:00:00-05:00" itemprop="datePublished">Sep 5, 2010</time>

Grease-stained plates covered the table, accompanied by staling pieces of
      mediocre pizza while fluorescent lights rained down harshly on the dining establishment. Dross
      entered in a fur coat.    "Looks like Oscar is going to be…  going away for a while  ." A big grin danced across
      his face. From the table Jambor looked up at him disinterestedly.    "Oh
      come on. Yes, he's a putz but it isn't all bad. He's still got some good stuff going for him.
      Give him another shot."    "Oh no. Not this time. Oscar has no more
      blunders to make. He's   outta here.  "    "What about those exugomic things?"    Dross hadn't
      considered this. "Hmm. He   could   sell
      those chairs…all he'd have to do is be real sassy to the queers and they'd buy it! They
      fucking love those chairs!"    In a light-filled tunnel between two
      dimensions, a figure struggled to put on a pair of underwear.    "Have you
      listened to 'Angel'?" asked Narin to the figure.    "Isn't that that dumb
      New Age crap?" he replied, annoyed.    Finally, he succeeded in his
      endeavor and looked up at Narin to find she was Merrem.

© erik radio 2016


text:
#pragma once

#include "DatabaseFwd.h"
#include "IDecompressor.h"

namespace CR
{
	namespace Sound
	{
		class Buffer
		{
		public:
			Buffer(const CR::Database::IRecord* const _record);
			~Buffer();
			unsigned int OpenALID() {return m_id;}
			short* Data() const {return m_data;}
			unsigned int NumSamples() {return m_dataSize/2;}
		private:
			short* m_data;
			unsigned int m_id;
			unsigned long m_dataSize;
		};
	}
}


text:
This is the first version of this package to depend on GAX v4.

There are some breaking changes, both in GAX v4 and in the generated
code. The changes that aren't specific to any given API are [described in the Google Cloud
documentation](https://cloud.google.com/dotnet/docs/reference/help/breaking-gax4).
We don't anticipate any changes to most customer code, but please [file a
GitHub issue](https://github.com/googleapis/google-cloud-dotnet/issues/new/choose)
if you run into problems.

The most important change in this release is the use of the Grpc.Net.Client package
for gRPC communication, instead of Grpc.Core. When using .NET Core 3.1 or .NET 5.0+
this should lead to a smaller installation footprint and greater compatibility (e.g.
with Apple M1 chips). Any significant change in a core component comes with the risk
of incompatibility, however - so again, please let us know if you encounter any
issues.

## Version 2.5.0, released 2022-04-04

### New features

- Add support for Maintenance Window ([commit fa2f5e9](https://github.com/googleapis/google-cloud-dotnet/commit/fa2f5e95b580a0aa03618408b09d798c9e6d82d8))
- Add support for AUTH functionality ([commit bed04f2](https://github.com/googleapis/google-cloud-dotnet/commit/bed04f2667156b728fe42c748f71fddf613c02e7))
- Add support for TLS functionality ([commit bed04f2](https://github.com/googleapis/google-cloud-dotnet/commit/bed04f2667156b728fe42c748f71fddf613c02e7))
- Add secondary_ip_range field ([commit bed04f2](https://github.com/googleapis/google-cloud-dotnet/commit/bed04f2667156b728fe42c748f71fddf613c02e7))

## Version 2.4.0, released 2021-11-10

- [Commit a7e87ee](https://github.com/googleapis/google-cloud-dotnet/commit/a7e87ee): feat: Support Multiple Read Replicas when creating Instance

## Version 2.3.0, released 2021-09-01

- [Commit ac367e2](https://github.com/googleapis/google-cloud-dotnet/commit/ac367e2): feat: Regenerate all APIs to support self-signed JWTs

## Version 2.2.0, released 2021-05-26

No API surface changes; just dependency updates.

## Version 2.1.0, released 2020-11-09

- [Commit 0790924](https://github.com/googleapis/google-cloud-dotnet/commit/0790924): fix: Add gRPC compatibility constructors
- [Commit 0ca05f5](https://github.com/googleapis/google-cloud-dotnet/commit/0ca05f5): chore: Regenerate all APIs using protoc 3.13 and Grpc.Tools 2.31
- [Commit 6bde7a3](https://github.com/googleapis/google-cloud-dotnet/commit/6bde7a3): docs: Regenerate all APIs with service comments in client documentation
- [Commit 0014243](https://github.com/googleapis/google-cloud-dotnet/commit/0014243): redis: v1 add UpgradeInstance request
- [Commit f83bdf1](https://github.com/googleapis/google-cloud-dotnet/commit/f83bdf1): fix: Apply timeouts to RPCs without retry
- [Commit a9ff54c](https://github.com/googleapis/google-cloud-dotnet/commit/a9ff54c): docs: change relative URLs to absolute URLs to fix broken links.
- [Commit 947a573](https://github.com/googleapis/google-cloud-dotnet/commit/947a573): docs: Regenerate all clients with more explicit documentation
- [Commit c9149b9](https://github.com/googleapis/google-cloud-dotnet/commit/c9149b9): docs: Comment-only changes

## Version 2.0.0, released 2020-03-18

No API surface changes compared with 2.0.0-beta01, just dependency
and implementation changes.

## Version 2.0.0-beta01, released 2020-02-18

This is the first prerelease targeting GAX v3. Please see the [breaking changes
guide](https://cloud.google.com/dotnet/docs/reference/help/breaking-gax2)
for details of changes to both GAX and code generation.

## Version 1.1.0, released 2019-12-09

- [Commit 95691ca](https://github.com/googleapis/google-cloud-dotnet/commit/95691ca): Retry settings are now obsolete, and will be removed from the next major version
- Async RPC methods now always have overloads accepting request objects
- Resource name classes now have format methods

## Version 1.0.0, released 2019-07-10

Initial GA release.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Protocols.TestSuites.FileSharing.SMB2.Adapter;

namespace Microsoft.Protocols.TestSuites.FileSharing.SMB2.TestSuite.OpLock
{
    [TestClass]
    public class OpLock : SMB2TestBase
    {
        #region Variables
        private Smb2FunctionalClient client1;
        private Smb2FunctionalClient client2;
        private string fileName;
        private string sharePath;
        private uint treeId;
        private FILEID fileId;
        private OPLOCK_BREAK_Notification_Packet OpLockBreakNotifyReceived;
        private ManualResetEvent OpLockNotificationReceived;
        #endregion

        #region Test Initialize and Cleanup
        [ClassInitialize()]
        public static void ClassInitialize(TestContext testContext)
        {
            TestClassBase.Initialize(testContext);
        }

        [ClassCleanup()]
        public static void ClassCleanup()
        {
            TestClassBase.Cleanup();
        }
        #endregion

        #region Test Case Initialize and Clean up
        protected override void TestInitialize()
        {
            base.TestInitialize();
            fileName = "OpLock" + Guid.NewGuid() + ".txt";
            sharePath = Smb2Utility.GetUncPath(testConfig.SutComputerName, testConfig.BasicFileShare);
            client1 = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite);
            client2 = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite);
            client1.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress);
            client2.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress);
            OpLockNotificationReceived = new ManualResetEvent(false);
        }

        protected override void TestCleanup()
        {
            if (client1 != null)
            {
                client1.Disconnect();
            }
            if (client2 != null)
            {
                client2.Disconnect();
            }
            sutProtocolController.DeleteFile(sharePath, fileName);
            base.TestCleanup();
        }
        #endregion

        #region Test Cases
        [TestMethod]
        [TestCategory(TestCategories.Bvt)]
        [TestCategory(TestCategories.Smb2002)]
        [TestCategory(TestCategories.OplockOnShareWithoutForceLevel2OrSOFS)]
        [Description("This test case is designed to test whether sever can handle OplockBreak correctly.")]
        public void BVT_OpLockBreak()
        {
            #region Add Event Handler
            client1.Smb2Client.OplockBreakNotificationReceived += new Action<Packet_Header, OPLOCK_BREAK_Notification_Packet>(OnOpLockBreakNotificationReceived);
            #endregion

            #region Client1 Open a File with BatchOpLock
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Start the first client by sending the following requests: NEGOTIATE; SESSION_SETUP; TREE_CONNECT.");
            client1.Negotiate(TestConfig.RequestDialects, TestConfig.IsSMB1NegotiateEnabled);
            client1.SessionSetup(TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, TestConfig.AccountCredential, false);
            client1.TreeConnect(sharePath, out treeId);

            Smb2CreateContextResponse[] createContextResponse;
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "The first client sends CREATE request with BatchOplock.");
            client1.Create(treeId, fileName, CreateOptions_Values.FILE_NON_DIRECTORY_FILE, out fileId, out createContextResponse, RequestedOplockLevel_Values.OPLOCK_LEVEL_BATCH,
                checker: (header, response) =>
                {
                    BaseTestSite.Assert.AreEqual(
                        Smb2Status.STATUS_SUCCESS,
                        header.Status,
                       "{0} should be successful, actually server returns {1}.", header.Command, Smb2Status.GetStatusCode(header.Status));

                    if (response.OplockLevel == OplockLevel_Values.OPLOCK_LEVEL_NONE)
                    {
                        BaseTestSite.Assert.Inconclusive("OpLock request not succeeded.");
                    }
                });
            #endregion

            #region Oplock Break
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Start the second client by sending the following requests: NEGOTIATE; SESSION_SETUP; TREE_CONNECT.");
            client2.Negotiate(TestConfig.RequestDialects, TestConfig.IsSMB1NegotiateEnabled);
            client2.SessionSetup(TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, TestConfig.AccountCredential, false);
            uint client2TreeId;
            client2.TreeConnect(sharePath, out client2TreeId);

            FILEID client2FileId;
            ulong createRequestId;
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "The second client sends CREATE request on the same file with the first client.");
            client2.CreateRequest(client2TreeId, fileName, CreateOptions_Values.FILE_NON_DIRECTORY_FILE, out createRequestId);

            BaseTestSite.Assert.IsTrue(OpLockNotificationReceived.WaitOne(SMB2TestConfig.WAIT_TIMEOUT_IN_MILLISECONDS),
                "The expected OPLOCK_BREAK_NOTIFY should be received within {0} milliseconds", SMB2TestConfig.WAIT_TIMEOUT_IN_MILLISECONDS);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "The first client sends OPLOCK_ACKNOWLEDGEMENT request after received OPLOCK_BREAK_NOTIFICATION response from server.");
            OplockBreakAcknowledgment(client1);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "The second client sends CREATE response");
            client2.CreateResponse(createRequestId, out client2FileId, out createContextResponse);
            #endregion

            #region Tear Down Clients
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the first client by sending CLOSE, TREE_DISCONNECT, and LOG_OFF.");
            client1.Close(treeId, fileId);
            client1.TreeDisconnect(treeId);
            client1.LogOff();

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the second client by sending CLOSE, TREE_DISCONNECT, and LOG_OFF.");
            client2.Close(client2TreeId, client2FileId);
            client2.TreeDisconnect(client2TreeId);
            client2.LogOff();
            #endregion
        }
        #endregion

        #region Private Methods
        private void OnOpLockBreakNotificationReceived(Packet_Header respHeader, OPLOCK_BREAK_Notification_Packet OpLockBreakNotify)
        {
            BaseTestSite.Log.Add(
                LogEntryKind.Comment,
                "OpLockBreakNotification was received from server");
            OpLockBreakNotifyReceived = OpLockBreakNotify;

            ///The FileId field of the response structure MUST be set to the values from the Open structure,
            ///with the volatile part set to Open.FileId and the persistent part set to Open.DurableFileId.
            BaseTestSite.Assert.AreEqual(fileId, OpLockBreakNotify.FileId, "FileId should be identical");

            BaseTestSite.Assert.IsTrue(
                OpLockBreakNotify.OplockLevel == OPLOCK_BREAK_Notification_Packet_OplockLevel_Values.OPLOCK_LEVEL_II ||
                OpLockBreakNotify.OplockLevel == OPLOCK_BREAK_Notification_Packet_OplockLevel_Values.OPLOCK_LEVEL_NONE,
                "The new oplock level MUST be either SMB2_OPLOCK_LEVEL_NONE or SMB2_OPLOCK_LEVEL_II.");
            OpLockNotificationReceived.Set();
        }

        private void OplockBreakAcknowledgment(Smb2FunctionalClient client)
        {
            OPLOCK_BREAK_Acknowledgment_OplockLevel_Values acknowledgementOplockLevel = default(OPLOCK_BREAK_Acknowledgment_OplockLevel_Values);

            //OpLockBreakNotifyReceived.OplockLevel can only be one of the next two values, otherwise AssertionError will be got in OnOpLockBreakNotificationReceived
            if (OpLockBreakNotifyReceived.OplockLevel == OPLOCK_BREAK_Notification_Packet_OplockLevel_Values.OPLOCK_LEVEL_II)
            {
                acknowledgementOplockLevel = OPLOCK_BREAK_Acknowledgment_OplockLevel_Values.OPLOCK_LEVEL_II;
            }
            else if (OpLockBreakNotifyReceived.OplockLevel == OPLOCK_BREAK_Notification_Packet_OplockLevel_Values.OPLOCK_LEVEL_NONE)
            {
                acknowledgementOplockLevel = OPLOCK_BREAK_Acknowledgment_OplockLevel_Values.OPLOCK_LEVEL_NONE;
            }

            client.OplockAcknowledgement(treeId, fileId, acknowledgementOplockLevel);
        }
        #endregion
    }
}


text:
using System;
using System.Diagnostics;

namespace MessTalk.Models
{
    [DebuggerDisplay("{Name}:{DataType}")]
    public class Property
    {
        public Property()
        {
            _name = "<not_specified>";
            _dataType = "<not_specified>";
        }

        private string _name;
        private string _dataType;

        public string Name
        {
            get { return _name; }
            set
            {
                if (string.IsNullOrEmpty(value))
                    throw new ArgumentNullException("value");
                _name = value;
            }
        }

        public string DataType
        {
            get { return _dataType; }
            set
            {
                if (string.IsNullOrEmpty(value))
                    throw new ArgumentNullException("value");
                _dataType = value;
            }
        }
    }
}


text:
var assert = require('assert');

// http://www.2ality.com/2014/05/is-integer.html
//
// не то, чтобы надо прям упираться рогом и зубрить Стефанова и Крокфорда. Это как
// у хорошего столяра в чемоданчике много всяких интересных штук, хотя он вполне может
// обойтись стамеской, пилой и молотком. Наличие их не необходимо, не обязательно, что он
// будет их использовать в каждом проекте, но знание - чего бывает и умение это заюзать
// - бесценно. Оно, собственно, и отличает столяра от мастера. Как-то так.

describe('Integer validators', function () {
	it('(x | 0) === x', function () {
		var bulk =    [1,0,-5,'a', '42', 8.35, 'a42', '42a'];
		var results = [true, true, true, false, false, false, false, false, false];

		var isInteger = function (x) {
			return (x | 0) === x;
		};

		assert(isInteger(42));
		assert( ! isInteger('a'));
	});

	it('x % 1 === 0', function () {
		var isInteger = function (x) {
			return x % 1 === 0;
		};

		// as expected
		assert(isInteger(42));
		assert( ! isInteger('a'));

		// glitches
		assert(isInteger(false));
		assert(isInteger(true));

		// overflow - depends of how `wide` bitwise operands could be
		// on my system (node 0.10.29, MacOS 10.9.4) it is 1024 bit; on some - 32.
		assert(isInteger(Math.pow(2, 1023)));

		// this one overflows:
		assert( ! isInteger(Math.pow(2, 1024)));
	});

	it('parseInt(x, 10)', function () {
		var isInteger = function (x) {
			return parseInt(x, 10) === x;
		};

		// as expected
		assert(isInteger(42));
		assert( ! isInteger('a'));
		assert( ! isInteger(false));
		assert( ! isInteger(true));

		// border cases
		assert( ! isInteger('42'));
		assert(isInteger(+'42'));

		assert(   isInteger(100000000000000000000));
		assert( ! isInteger(1000000000000000000000));
		// why? Here's why:
		assert.equal(String(1000000000000000000000), '1e+21');

		// glitches
	});

	it('Math.round(x) === x', function () {
		var isInteger = function (x) {
			return Math.round(x) === x;
		};

		// as expected
		assert(isInteger(42));
		assert( ! isInteger('a'));
		assert( ! isInteger(false));
		assert( ! isInteger(true));

		// border cases
		assert( ! isInteger('42'));
		assert(isInteger(+'42'));

		// these works just fine since no `to String` conversion happens
		assert(   isInteger(100000000000000000000));
		assert(   isInteger(1000000000000000000000));

		// glitches
	});

	it ('ECMAScript v.6 extensions', function (done) {
		// this wreck is needed to print `not supported` messages _after_ the test name
		setTimeout(function () {
			done();
			if ( typeof Math.trunc !== 'function') {
				console.log('Math.trunc is not supported');
			}
			if ( typeof Math.isInteger !== 'function') {
				console.log('Math.isInteger is not supported');
			}
		}, 0);
	});

	it ('!isNaN(+x)', function () {
		// it is more, like, isNumber since fractions are supported also.
		var isInteger = function (x) {
			return !isNaN(+x);
		};

		// as expected
		assert(   isInteger(42));
		assert( ! isInteger('a'));
		assert(   isInteger(false));
		assert(   isInteger(true));

		// border cases
		assert(   isInteger(4.26e307));
		assert(   isInteger('4.26e307'));
		assert(   isInteger(42.6));
		assert(   isInteger('42.6'));
		assert(   isInteger('42'));
		assert(   isInteger(+'42'));
		assert( ! isInteger('42a'));

		// these works just fine since no `to String` conversion happens
		assert(   isInteger(100000000000000000000));
		assert(   isInteger(1000000000000000000000));

		// that works, too:
		assert(   isInteger(Math.pow(2, 1025)));

	});

	it ('using powers', function () {
		var isInteger = function (x) {
			return x^0 === x;
			// return Math.round(x) === x;
			// return (typeof x === 'number') && (x % 1 === 0);
		};

		assert(   isInteger(42));
		assert( ! isInteger('a'));

	});

});


text:
require "Window"
require "CommodityOrder"
require "GameLib"
require "MarketplaceLib"
require "Money"

local Outbid = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("Outbid", true,
	{
		"MarketplaceListings",
		"Gemini:Logging-1.2"
	},
	"Gemini:Hook-1.0"
)

function Outbid:OnInitialize()
    -- load our form file
	self.xmlDoc = XmlDoc.CreateFromFile("Outbid.xml")
	self.xmlDoc:RegisterCallback("OnDocLoaded", self)
	GeminiLogging = Apollo.GetPackage("Gemini:Logging-1.2").tPackage
    logger = GeminiLogging:GetLogger({
        --level = GeminiLogging.INFO,
        appender = "GeminiConsole"
    })

	self.orders = nil
	self.orderListWindow = nil

	Apollo.RegisterEventHandler("CommodityInfoResults", "OnCommodityInfoResults", self)
end

-----------------------------------------------------------------------------------------------
-- Outbid OnDocLoaded
-----------------------------------------------------------------------------------------------
function Outbid:OnDocLoaded()
	if self.xmlDoc ~= nil and self.xmlDoc:IsLoaded() then
		self:Hook(Apollo.GetAddon("MarketplaceListings"), "OnOwnedCommodityOrders")
		self:PostHook(Apollo.GetAddon("MarketplaceListings"), "BuildCommodityOrder")
		self:PostHook(Apollo.GetAddon("MarketplaceListings"), "OnToggleFromAuctionHouse")
	end
end

function Outbid:OnToggleFromAuctionHouse(luaCaller)
	local marketplaceListings = Apollo.GetAddon("MarketplaceListings")
	marketplaceListings.wndBtnAuctionListing:SetCheck(false)
	marketplaceListings.wndBtnCommodityListing:SetCheck(true)
end

function Outbid:BuildCommodityOrder(luaCaller, nIdx, aucCurrent, wndParent)
	self.orderListWindow = wndParent:GetParent():GetParent()
	local item = aucCurrent:GetItem()
	MarketplaceLib.RequestCommodityInfo(item:GetItemId())
end

function Outbid:OnCommodityInfoResults(nItemId, tStats, tOrders)
	if not self.orders or not self.orderListWindow or not self.orderListWindow:IsValid() then
		return
	end

	if self.oldSellOrder and self.readyToResell then
		if self.oldSellOrder:GetItem():GetItemId() == nItemId then
			local topPrice = tStats.arSellOrderPrices[1].monPrice
			self.sellDialog = Apollo.LoadForm(self.xmlDoc, "ResellConfirm", nil, self)
			local sellButton = self.sellDialog:FindChild("SellButton")

			local newPrice = Money.new()
			if self:HaveMatchingOrderPrice(nItemId, topPrice) then
				newPrice:SetAmount(topPrice:GetAmount())
			else
				newPrice:SetAmount(topPrice:GetAmount() - 1)
			end

			self:CreateOrderCommand("sell", sellButton, nItemId, newPrice, self.oldSellOrder:GetCount())

			self.sellDialog:FindChild("SellText"):SetText(self.oldSellOrder:GetItem():GetName())
			self.sellDialog:FindChild("UnitPrice"):SetAmount(newPrice:GetAmount(), true)
			self.sellDialog:Invoke()

			self.oldSellOrder = nil
			self.readyToResell = false
		end
	end

	for idx, order in pairs(self.orders) do
		if order:GetItem():GetItemId() == nItemId then
			local orderPrice = order:GetPricePerUnit()
			if order:IsBuy() then
				local topPrice = tStats.arBuyOrderPrices[1].monPrice --Top 1 is first index
				if orderPrice:GetAmount() < topPrice:GetAmount() then
					local listItemPanel = self.orderListWindow:FindChildByUserData(order)
					local oldButton = listItemPanel:FindChild("RelistBuyButton")
					if oldButton then
						oldButton:Destroy()
					end

					local newButton = Apollo.LoadForm(self.xmlDoc, "RelistBuyButton", listItemPanel, self)
					newButton:SetData(order)

					local newPrice = Money.new()
					if self:HaveMatchingOrderPrice(nItemId, topPrice) then
						newPrice:SetAmount(topPrice:GetAmount())
					else
						newPrice:SetAmount(topPrice:GetAmount() + 1)
					end
					self:CreateOrderCommand("buy", newButton, nItemId, newPrice, order:GetCount())
				end
			else
				local topPrice = tStats.arSellOrderPrices[1].monPrice --Top 1 is first index
				if orderPrice:GetAmount() > topPrice:GetAmount() then
					local listItemPanel = self.orderListWindow:FindChildByUserData(order)
					local oldButton = listItemPanel:FindChild("RelistSellButton")
					if oldButton then
						oldButton:Destroy()
					end

					local newButton = Apollo.LoadForm(self.xmlDoc, "RelistSellButton", listItemPanel, self)
					newButton:SetData(order)
				end
			end
		end
	end
end

function Outbid:OnOwnedCommodityOrders(luaCaller, tOrders)
	self.orders = tOrders
end

function Outbid:CreateOrderCommand(orderType, button, itemId, price, amount)
	local orderNew = orderType == "buy" and CommodityOrder.newBuyOrder(itemId) or CommodityOrder.newSellOrder(itemId)
	if price and amount then
		orderNew:SetCount(amount)
		orderNew:SetPrices(price)
	end

	if not orderNew:CanPost() then
		button:Enable(false)
	else
		button:SetActionData(GameLib.CodeEnumConfirmButtonType.MarketplaceCommoditiesSubmit, orderNew)
	end
end

function Outbid:HaveMatchingOrderPrice(itemId, price)
	for idx, order in pairs(self.orders) do
		if order:GetItem():GetItemId() == itemId then
			local orderPrice = order:GetPricePerUnit()
			if orderPrice:GetAmount() == price:GetAmount() then
				return true
			end
		end
	end
	return false
end

function Outbid:SubmittedBuyOrder( wndHandler, wndControl, bSuccess )
	if not bSuccess then
		return
	end
	local order = wndHandler:GetData()
	if not order then
		return
	end
	order:Cancel()

	self.oldBuyOrder = order
	self:BuildTimer("BuyMailTimer")
end

function Outbid:RelistSellClick( wndHandler, wndControl, eMouseButton )
	local order = wndHandler:GetData()
	if not order then
		return
	end
	order:Cancel()

	self.oldSellOrder = order
	self.readyToResell = false
	self:BuildTimer("SellMailTimer")
end

function Outbid:BuildTimer(timerFunc)
	if self.timer then
		self.timer:Stop()
		self.timer = nil
	end
	self.timer = ApolloTimer.Create(0.2, true, timerFunc, self)
end

function Outbid:BuyMailTimer()
	if not self.oldBuyOrder then
		self.timer:Stop()
	end

	--Fetch the money from the cancel mail
	local mails = MailSystemLib.GetInbox()
	local oldItemName = self.oldBuyOrder:GetItem():GetName()

	for idx, mail in pairs(mails) do
		local mailInfo = mail:GetMessageInfo()
		local searchPattern = self:GetItemSearchPattern(oldItemName)
		if string.find(mailInfo.strSubject, "Buy") and string.find(mailInfo.strBody, searchPattern) then
			mail:TakeMoney()
			mail:DeleteMessage()
			self.timer:Stop()
			self.oldBuyOrder = nil
			break
		end
	end
end

function Outbid:GetItemSearchPattern(itemName)
	itemName = string.gsub(itemName, "%-", ".") --Dash is special character, replace with dot
	itemName = string.gsub(itemName, "Sign ", "Signs? ") --Possible pluralized word
	return itemName
end

function Outbid:SellMailTimer()
	local mails = MailSystemLib.GetInbox()

	if not self.oldSellOrder then
		self.timer:Stop()
	end

	local oldItemId = self.oldSellOrder:GetItem():GetItemId()

	for idx, mail in pairs(mails) do
		if self:IsItemAttached(mail, oldItemId) then
			mail:TakeAllAttachments()
			mail:DeleteMessage()
			self.timer:Stop()
			self.readyToResell = true
			MarketplaceLib.RequestCommodityInfo(oldItemId) --Re-trigger a market check to relist
			break
		end
	end
end

function Outbid:IsItemAttached(mail, itemId)
	attachements = mail:GetMessageInfo().arAttachments
	for idx, attachment in pairs(attachements) do
		if attachment.itemAttached:GetItemId() == itemId then
			return true
		end
	end
	return false
end

function Outbid:SellCancelClick( wndHandler, wndControl, eMouseButton )
	if self.sellDialog then
        self.sellDialog:Destroy()
        self.sellDialog = nil
    end
end

function Outbid:SellOrderSubmitted( wndHandler, wndControl, bSuccess )
    if self.sellDialog then
        self.sellDialog:Destroy()
        self.sellDialog = nil
    end
end


text:
package de.bluebiz.bluelytics.api.query;

import de.bluebiz.bluelytics.api.Engine;
import de.bluebiz.bluelytics.api.connection.observer.ConnectionHandler;
import de.bluebiz.bluelytics.api.connection.observer.ConnectionProperties;
import de.bluebiz.bluelytics.api.connection.observer.StreamListener;
import de.bluebiz.bluelytics.api.exceptions.BluelyticsException;

/**
 * The type Deployed query.
 *
 * @param <T> the type parameter
 */
public class DeployedQuery<T> {

    private final Engine engine;
    private final String space;
    private final String name;
    private final Class<T> type;

    /**
     * Instantiates a new Deployed query.
     *
     * @param engine the engine
     * @param space  the space
     * @param name   the name
     * @param type   the type
     */
    public DeployedQuery(Engine engine, String space, String name, Class<T> type) {
        this.engine = engine;
        this.space = space;
        this.name = name;
        this.type = type;
    }

    /**
     * Connect.
     *
     * @param listener               the listener
     * @param blocking               the blocking
     * @param ignoreMissingAttribute the ignore missing attribute
     * @throws BluelyticsException the bluelytics exception
     */
    public void connect(StreamListener<T> listener, boolean blocking, boolean ignoreMissingAttribute) throws BluelyticsException {
        ConnectionProperties props = this.engine.services().getQueryService().connect(this.space, this.name);
        props.setHost(this.engine.getConnectionData().getHost());
        ConnectionHandler<T> handler = new ConnectionHandler<T>(props, listener, type, blocking, ignoreMissingAttribute);
        handler.open();

    }

    /**
     * Connect.
     *
     * @param listener the listener
     * @param blocking the blocking
     * @throws BluelyticsException the bluelytics exception
     */
    public void connect(StreamListener<T> listener, boolean blocking) throws BluelyticsException {
        connect(listener, blocking, true);
    }

    /**
     * Connect.
     *
     * @param listener the listener
     * @throws BluelyticsException the bluelytics exception
     */
    public void connect(StreamListener<T> listener) throws BluelyticsException {
        connect(listener, false, true);
    }

    /**
     * Start.
     *
     * @throws BluelyticsException the bluelytics exception
     */
    public void start() throws BluelyticsException {
        this.engine.services().getQueryService().start(this.space, this.name);
    }

    /**
     * Stop.
     *
     * @throws BluelyticsException the bluelytics exception
     */
    public void stop() throws BluelyticsException {
        this.engine.services().getQueryService().stop(this.space, this.name);
    }

    /**
     * Resume.
     *
     * @throws BluelyticsException the bluelytics exception
     */
    public void resume() throws BluelyticsException {
        this.engine.services().getQueryService().resume(this.space, this.name);
    }

    /**
     * Suspend.
     *
     * @throws BluelyticsException the bluelytics exception
     */
    public void suspend() throws BluelyticsException {
        this.engine.services().getQueryService().suspend(this.space, this.name);
    }
}


text:
/**
 * @file some preserved attributes handler
 *
 * @author Leo Wang(leowang721@gmail.com)
 */

define(function (require) {
    var $ = require('./lib/zepto');

    var preservedAttributes = {
        'hidden': function (newVal, oldVal) {
            if (newVal == null) {  // 要显示
                $(this.el).css({
                    height: 'auto',
                    visibility: 'visible'
                });
            }
            else {
                $(this.el).css({
                    height: 0,
                    visibility: 'hidden'
                });
            }
        }
    };

    return preservedAttributes;
});


text:
layout: post
tags: [algorithms, matlab]
title: Gaussian Discriminant Analysis
---
GDA is an example of generative learining. It works very simple:

1. We make assumption about the type of distributions of our data - in given example: Normal Distribution
2. For each class we learn (on training data) the parametrs of distribution: mu, sd
3. We model each class' distribution via Likelihood
4. For new data example we calculate the likelihood of belonging to each of the classes
5. Finally, we choose the maximimum likelihood to predict the class.

Here is the simplyfied code for Matlab:

{% highlight matlab linenos %}
function gda()
    train_data = load('vowel.train');

    % extract the target and the predictor variables for all the data
    x = train_data(:,2:11);
    y = train_data(:,1);

    [m,n] = size(x);

    % find out the number of classes
    unique_classes = unique(y);
    k = length(unique_classes);

    % estimate the prior probability of each class
    phi = zeros(num_classes, 1);
    for i = 1:k
        class = unique_classes(i);
        phi(i) = length(y(y==class)) / m;
    end

    % estimate the mean for each class
    mu = zeros(k, n);
    for i = 1:k
        class = unique_classes(i);
        x_in_class = x(y == class,:);
        mu(i, :) = mean(x_in_class);
    end

    % estimate the common covariance matrix for the data centered on its
    % respective means
    sigma = eye(n, n);
    for i = 1:k
        class = unique_classes(i);
        x_in_class = x(y == class,:);
        diff = x_in_class - repmat(mu(i, :), length(x_in_class(:,1)), 1);
        sigma = sigma + diff'*diff;
    end
    % Normalize sigma
    sigma = sigma / m;

    % precompute the inverse of sigma for later use
    sigma_inv = inv(sigma);

    % make predictions on the train data
    % intialize conf -- the k*k confusion matrix, where entry conf(i,j) is the
    % number of times the true class i was predicted as class j
    conf = zeros(k, k);

    coef = 1/((2*pi)^(n/2) * sqrt(det(sigma)));
    for i = 1:m
        p = zeros(k, 1);
        for class = 1:k
            diff = x(i, :) - mu(class, :);
            pxy = coef * exp( -1/2 * diff * sigma_inv * diff');
            py = phi(class);
            p(class) = pxy * py;
        end
        p = p / sum(p);

        % find the most probable class
        [max_prob, predicted_class] = max(p);

        % update the confusion matrix for this example's prediction
        conf(y(i), predicted_class) = conf(y(i), predicted_class) + 1;
    end

    % compute the accuracy of all predictions
    accuracy = sum(diag(conf)) / sum(sum(conf))

    % compute the precision per class
    per_class_precision = diag(conf) ./ sum(conf, 2)

    % compute the base rate accuracy
    base_rate = max(sum(conf, 2)) ./ sum(sum(conf))
{% endhighlight %}


text:
//
//  DCSettingCell.m
//  CDDMall
//
//  Created by apple on 2017/6/4.
//  Copyright © 2017年 RocketsChen. All rights reserved.
//

#import "DCSettingCell.h"

// Controllers

// Models

// Views

// Vendors

// Categories

// Others

@interface DCSettingCell ()
/* 日期上方工具条 */
@property(nonatomic,strong)UIToolbar* textFieldToolbar;
/* 日期DatePicker */
@property(nonatomic,strong)UIDatePicker* dataPicker;

@end

@implementation DCSettingCell

#pragma mark - loadLazy

- (UIDatePicker *)dataPicker{
    if (!_dataPicker) {

        _dataPicker = [[UIDatePicker alloc]init];
        _dataPicker.backgroundColor = [UIColor whiteColor];
        //设置显示模式,只显示日期
        _dataPicker.datePickerMode = UIDatePickerModeDate;
        //本地化
        _dataPicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
    }
    return _dataPicker;
}

-(UIView *)textFieldToolbar{

    if (!_textFieldToolbar) {

        _textFieldToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 44)];
        _textFieldToolbar.backgroundColor = [UIColor whiteColor];
        //设置按钮
        UIBarButtonItem *fixSpaceBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] ;
        UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(finishBirthChange)];
        [doneBtn setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} forState:UIControlStateNormal];
        _textFieldToolbar.items = @[fixSpaceBtn,doneBtn];
    }
    return _textFieldToolbar;
}

#pragma mark - Intial
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {

        [self setUpUI];
    }
    return self;
}

#pragma mark - UI
- (void)setUpUI
{
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.font = PFR15Font;

    _setSwitch = [[UISwitch alloc]init];
    [_setSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    _setSwitch.onTintColor = [UIColor redColor]; // 在oneSwitch开启的状态显示的颜色 默认是blueColor
//    _setSwitch.tintColor = [UIColor lightGrayColor]; // 设置关闭状态的颜色
//    _setSwitch.thumbTintColor = [UIColor whiteColor]; // 设置开关上左右滑动的小圆点的颜色

    _indicateButton = [UIButton buttonWithType:UIButtonTypeCustom];

    _contentLabel = [[UILabel alloc] init];
    _contentLabel.textColor = [UIColor darkGrayColor];
    _contentLabel.font = PFR13Font;

    _birthField = [[UITextField alloc]init];
    _birthField.borderStyle = UITextBorderStyleNone;
    //设置文本输入框的输入辅助视图为自定义的视图
    _birthField.inputAccessoryView = self.textFieldToolbar;
    //设置文本输入框的输入视图为自定义的dataPicker;
    _birthField.inputView = self.dataPicker;
    _birthField.textColor = [UIColor darkGrayColor];
    _birthField.font = PFR13Font;

}

#pragma mark - Setter Getter Methods
- (void)layoutSubviews
{
    [super layoutSubviews];

    [self addSubview:_titleLabel];

    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        [make.left.mas_equalTo(self)setOffset:DCMargin];
        make.centerY.mas_equalTo(self);
    }];
    if (_type == cellTypeOne) {
        [self addSubview:_indicateButton];
        [self addSubview:_contentLabel];

        [_indicateButton mas_makeConstraints:^(MASConstraintMaker *make) {
            [make.right.mas_equalTo(self)setOffset:-DCMargin];
            make.size.mas_equalTo(CGSizeMake(30, 30));
            make.centerY.mas_equalTo(self);
        }];

        [_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(_indicateButton.mas_left);
            make.centerY.mas_equalTo(self);
        }];

    }else if (_type == cellTypeTwo){

        [self addSubview:_setSwitch];
        [_setSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
            [make.right.mas_equalTo(self)setOffset:-DCMargin];
            make.size.mas_equalTo(CGSizeMake(60, 35));
            make.centerY.mas_equalTo(self);
        }];
    }else if (_type == cellTypeThree){

        [self addSubview:_birthField];
        [self addSubview:_indicateButton];
        [_indicateButton mas_makeConstraints:^(MASConstraintMaker *make) {
            [make.right.mas_equalTo(self)setOffset:-DCMargin];
            make.size.mas_equalTo(CGSizeMake(30, 30));
            make.centerY.mas_equalTo(self);
        }];

        [_birthField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(_indicateButton.mas_left);
            make.centerY.mas_equalTo(self);
        }];
    }

}
#pragma mark - 点击事件
- (void)switchAction:(UISwitch *)sender
{
    NSLog(@"%@", sender.isOn ? @"ON" : @"OFF");
}

#pragma mark - 跟换生气结束
- (void)finishBirthChange
{
    DCUserInfo *userInfo = UserInfoData;
    NSDate* choosedDate = self.dataPicker.date;
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init]; //设置日期格式
    formatter.dateFormat = @"yyyy-MM-dd";

    NSString *birthDayStr = [formatter stringFromDate:choosedDate];

    if (![birthDayStr isEqualToString:_birthField.text]) { //跟换日期
//        userInfo.birthDay = birthDayStr;
        [userInfo save];
        _birthField.text = birthDayStr;
    }
    [_birthField resignFirstResponder];
}

@end


text:
{# myapp/templates/macros.html #}

{% macro nav_link(endpoint, text) %}
    {% if request.endpoint is not none %}
        {% if request.endpoint.endswith(endpoint) %}
            {{ text }}
        {% else %}
            {{ text }}
        {% endif %}
    {% else %}
        {{ text }}
    {% endif %}
{% endmacro %}

{% macro render_field(field) %}

        {{ field(name_=field.name, id=field.name, placeholder=field.description, class_="field") }}

    {% if field.errors %}

            {% for error in field.errors %}

{{ error }}

            {% endfor %}

    {% endif %}
{% endmacro %}


text:
using System.Collections.Generic;

namespace CSharpinator
{
    public interface IClass
    {
        bool IsPlural { get; }
        string GeneratePropertyCode(string propertyName, Case classCase, IEnumerable<AttributeProxy> attributes, DocumentType documentType);
    }
}


text:
module Metadata
  class CreateConfigurationField
    attr_reader :collection

    def self.call(collection, new_data)
      new(collection).create_field(new_data)
    end

    def initialize(collection)
      @collection = collection
    end

    def create_field(new_data)
      populate_defaults(values: new_data)
      new_data = ConfigurationInputCleaner.call(new_data)

      if duplicate_label?(new_data)
        return nil
      else
        unique_key = Metadata::GenerateUniqueKey.call
        new_data[:name] = unique_key
        configuration.save_field(unique_key, new_data)
      end
    end

    private

    # Populates default values for some fields when there are no values given,
    # since we can't do it at the database layer
    def populate_defaults(values:)
      if values[:order].nil? || values[:order] == ""
        max = CollectionConfigurationQuery.new(collection).max_metadata_order
        values[:order] = max + 1
      end

      if values[:active].nil? || values[:active] == ""
        values[:active] = true
      end
    end

    def duplicate_label?(new_data)
      duplicates = @collection.collection_configuration.metadata.select do |m|
        h = m.with_indifferent_access
        h[:label].casecmp(new_data[:label]) == 0
      end
      duplicates.count >= 1 ? true : false
    end

    def configuration
      @configuration ||= CollectionConfigurationQuery.new(collection).find
    end
  end
end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>AdminLTE 2 | Dashboard</title>

  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

  <link rel="stylesheet" href="<?php echo base_url('assets/css/bootstrap.min.css') ?>">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css') ?>">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('dist/css/AdminLTE.min.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('dist/css/skins/_all-skins.min.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('plugins/iCheck/flat/blue.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('plugins/morris/morris.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('plugins/jvectormap/jquery-jvectormap-1.2.2.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('plugins/datepicker/datepicker3.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('plugins/daterangepicker/daterangepicker.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css') ?>') ?>">
   <link href="<?php echo base_url('assets/css/bootstrap.min.css') ?>" rel="stylesheet">
    <link href="<?php echo base_url('assets/css/font-awesome.min.css') ?>" rel="stylesheet">

      D

      Dashboards

        Toggle navigation

<?php echo $this->session->userdata('username')?>

           Online

MAIN NAVIGATION

          <a href="<?php echo base_url();?>index.php/home_cont/homeview">

            Dashboards

              4

          <a href="<?php echo base_url();?>index.php/home_cont/connectdatabase">
             Create Dashboards

          <a href="<?php echo base_url();?>index.php/home_cont/connectdatabase">
             Connect Database

            Your Databases

             <?php
        $dbs = $this->session->flashdata('dbs');
        foreach ($dbs as $row)
         {
            echo "
id.">".$row->host.'/'.$row->data_base."
";
          }
          ?>

          <a href="<?php echo base_url();?>index.php/home_cont/logout">
             Logout

Table List

                <?php
                $table_data = $this->session->flashdata('table_data');
                 $id=$this->session->userdata('id');
                  //echo "id".$id;
                foreach ($table_data as $table => $fields)
                {

                    ?>

                  <?php echo $table?>

              <a href="<?php echo base_url() .'index.php/home_cont/table_delete/'.$table.'/'.$id ?>" class="pull-right" style="color: black;">
                   <button type="button" class="pull-right">
                    Drop
                                       </button>

              <a href="<?php echo base_url() .'index.php/home_cont/insertfield/'.$table ?>" class="pull-right" style="color: black;">
                    <button type="button " class="pull-right" >
                    Insert
                                      </button>

                <?php
                    foreach ($fields as $field)
                    {
                       ?>

                   <?php echo $field   ?>
                    <a href="<?php echo base_url().'index.php/home_cont/field_delete/'.$id.'/'.$table.'/'.$field?>"  style="color: black;">
                   <button type="button" >
                    Delete
                    </button>

                <?php
                }
                }
                ?>

Recent Activity

Langdon's Birthday

Will be 23 on April 24th

Frodo Updated His Profile

New phone +1(800)555-1234

Nora Joined Mailing List

nora@example.com

Cron Job 254 Executed

Execution time 5 seconds

Tasks Progress

                Custom Template Design
                70%

                Update Resume
                95%

                Laravel Integration
                50%

                Back End Framework
                68%

Stats Tab Content

        <form method="post">

General Settings

              Report panel usage
              <input type="checkbox" class="pull-right" checked>

              Some information about this general settings option

              Allow mail redirect
              <input type="checkbox" class="pull-right" checked>

              Other sets of options are available

              Expose author name in posts
              <input type="checkbox" class="pull-right" checked>

              Allow the user to show his name in blog posts

Chat Settings

              Show me as online
              <input type="checkbox" class="pull-right" checked>

              Turn off notifications
              <input type="checkbox" class="pull-right">

              Delete chat history

        </form>


text:
:mod:`maec.bundle.candidate_indicator` Module
=============================================

.. module:: maec.bundle.candidate_indicator

Classes
-------

.. autoclass:: CandidateIndicator
	:show-inheritance:
	:members:

.. autoclass:: CandidateIndicatorList
	:show-inheritance:
	:members:

.. autoclass:: CandidateIndicatorComposition
	:show-inheritance:
	:members:

.. autoclass:: MalwareEntity
	:show-inheritance:
	:members:


text:
package cc.mallet.util.search;

import java.util.Iterator;

/**
 * Created by IntelliJ IDEA.
 * User: pereira
 * Date: Jun 20, 2005
 * Time: 4:54:46 PM
 * A state (vertex) in a graph being searched.
 */
public interface SearchState {
  /**
   * Iterator over the states with transitions from a given state.
   */
  public static abstract class NextStateIterator implements Iterator<SearchState> {
    public abstract boolean hasNext();
    public SearchState next() {return nextState(); };
    /**
     * Get the next reachable state.
     * @return the state
     */
    public abstract SearchState nextState();
    /**
     * The cost of the transition to the current state.
     * @return transition cost
     */
    public abstract double cost();
    public void remove() {
      throw new UnsupportedOperationException();
    }
  }
  /**
   * Get an iterator over the states with transitions from
   * this state.
   * @return the iterator
   */
  public abstract NextStateIterator getNextStates();
  /**
   * Is this state final?
   * @return whether this state is final
   */
  public abstract boolean isFinal();
}


text:
namespace KeyQuest.Modules {
    public class TreasureItem {
        public string Name { get; set; }
        public string Description { get; set; }
    }
}


text:
require "coveralls"
Coveralls.wear!

$LOAD_PATH.unshift File.dirname(__FILE__)
require "rspec"
require "money"

I18n.enforce_available_locales = false

RSpec.configure do |c|
  c.order = :random
end

def reset_i18n
  I18n.backend = I18n::Backend::Simple.new
end

RSpec.shared_context "with infinite precision", :infinite_precision do
  before do
    Money.infinite_precision = true
  end

  after do
    Money.infinite_precision = false
  end
end


text:
// See http://www.boost.org/libs/iostreams for documentation.

#include <fstream>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
#include "detail/filters.hpp"
#include "detail/sequence.hpp"
#include "detail/temp_file.hpp"
#include "detail/verification.hpp"

using boost::unit_test::test_suite;

void pipeline_test()
{
    using namespace std;
    using namespace boost;
    using namespace boost::iostreams;
    using namespace boost::iostreams::test;

    {
        test_file src;
        filtering_istream
            in1( toupper_filter() |
                 file_source(src.name()) );
        filtering_istream
            in2( toupper_filter() |
                 toupper_filter() |
                 file_source(src.name()) );
        filtering_istream
            in3( toupper_filter() |
                 toupper_filter() |
                 toupper_filter() |
                 file_source(src.name()) );
        filtering_istream
            in4( toupper_filter() |
                 toupper_filter() |
                 toupper_filter() |
                 toupper_filter() |
                 file_source(src.name()) );
        BOOST_CHECK(in1.size() == 2);
        BOOST_CHECK(in2.size() == 3);
        BOOST_CHECK(in3.size() == 4);
        BOOST_CHECK(in4.size() == 5);
    }

    {
        test_file       src;
        uppercase_file  upper;
        filtering_istream
            first( toupper_filter() |
                   toupper_multichar_filter() |
                   file_source(src.name(), in_mode) );
        ifstream second(upper.name().c_str(), in_mode);
        BOOST_CHECK_MESSAGE(
            compare_streams_in_chunks(first, second),
            "failed reading from a filtering_istream in chunks with a "
            "multichar input filter"
        );
    }

    {
        temp_file       dest;
        lowercase_file  lower;
        filtering_ostream
            out( tolower_filter() |
                 tolower_multichar_filter() |
                 file_sink(dest.name(), out_mode) );
        write_data_in_chunks(out);
        out.reset();
        BOOST_CHECK_MESSAGE(
            compare_files(dest.name(), lower.name()),
            "failed writing to a filtering_ostream in chunks with a "
            "multichar output filter with no buffer"
        );
    }
}

test_suite* init_unit_test_suite(int, char* [])
{
    test_suite* test = BOOST_TEST_SUITE("pipeline test");
    test->add(BOOST_TEST_CASE(&pipeline_test));
    return test;
}


text:
//
//  RDHExpandingDatePickerView.h
//  RDHExpandingPickerViews
//
//  Created by Richard Hodgkins on 15/02/2014.
//  Copyright (c) 2014 Rich H. All rights reserved.
//

#import "_RDHBaseExpandingPickerContainerView.h"

NS_ASSUME_NONNULL_BEGIN

/// Expanding picker view backed by a `UIDatePicker`.
@interface RDHExpandingDatePickerView : _RDHBaseExpandingPickerContainerView

/// The backing data picker.
@property (nonatomic, assign, readonly) UIDatePicker *pickerView;

#pragma mark - Date selection
/// @name Date selection

/// The selected `NSDate`.
@property (nonatomic, copy, nullable) NSDate *selectedDate;

/// @see selectedDate
-(void)setSelectedDate:(nullable NSDate *)selectedDate animated:(BOOL)animated;

#pragma mark - Countdown time selection
/// @name Countdown time selection

/// The selected `NSTimeInterval`.
@property (nonatomic, assign) NSTimeInterval selectedTimeInterval;

/// @see selectedTimeInterval
-(void)setSelectedTimeInterval:(NSTimeInterval)selectedTimeInterval animated:(BOOL)animated;

#pragma mark - Date display
/// @name Date display

/**
 * This will be used to display the `selectedObject` date when the `pickerView` is **not** in `UIDatePickerModeCountDownTimer` mode. This is ignored if `setDateDisplayValueBlock:` if non-nil or `setDateDisplayValueBlock:` is non-nil.
 *
 * If this property or the other two block properties are not set the `[NSDateFormatter localizedStringFromDate:dateStyle:timeStyle:]` with the date and time style depending on the picker mode.
 */
@property (nonatomic, copy, nullable) NSDateFormatter *dateFormatter;

/// This will be ignored if the value passed into `setDateDisplayValueBlock:` is non-nil.
-(void)setDateDisplayValueBlock:(NSString* _Nullable (^_Nullable)(RDHExpandingDatePickerView * _Nonnull, NSDate * _Nonnull))block;

/// This will be used first, followed by the non-nil value passed into `setDateDisplayValueBlock:` and then the `dateFormatter`.
-(void)setAttributedDateDisplayValueBlock:(NSAttributedString * _Nullable (^_Nullable)(RDHExpandingDatePickerView * _Nonnull, NSDate * _Nonnull))block;

#pragma mark - Time interval display
/// @name Time interval display

/**
 * This will be used to display the `selectedObject` date when the `pickerView` **is** in `UIDatePickerModeCountDownTimer` mode. This is ignored if `setTimeIntervalDisplayValueBlock` is non-nil or `setAttributedTimeIntervalDisplayValueBlock:` is non-nil.
 *
 * If this property or the other two block properties are not set the format `H:m` of the current locale is used.
 *
 * The object passed into this formatter will be a `NSNumber` wrapping up the selected time interval.
 */
@property (nonatomic, copy, nullable) NSFormatter *timeIntervalFormatter;

/// This will be ignored if the value passed into `setAttributedTimeIntervalDisplayValueBlock:` is non-nil.
- (void)setTimeIntervalDisplayValueBlock:(NSString* _Nullable (^_Nullable)(RDHExpandingDatePickerView *expandingPickerView, NSTimeInterval selectedObject))block;

/// This will be used first, followed by the non-nil value passed into `setTimeIntervalDisplayValueBlock:` and then the `timeIntervalFormatter`.
-(void)setAttributedTimeIntervalDisplayValueBlock:(NSAttributedString * _Nullable (^_Nullable)(RDHExpandingDatePickerView * _Nonnull, NSTimeInterval))block;

@end

NS_ASSUME_NONNULL_END


text:
<?php

namespace Drupal\Core\Plugin\Context;

use Drupal\Component\Plugin\PluginManagerInterface;

/**
 * Provides an interface for plugin managers that support context-aware plugins.
 */
interface ContextAwarePluginManagerInterface extends PluginManagerInterface {

  /**
   * Determines plugins whose constraints are satisfied by a set of contexts.
   *
   * @todo Use context definition objects after
   *   https://www.drupal.org/node/2281635.
   *
   * @param \Drupal\Component\Plugin\Context\ContextInterface[] $contexts
   *   An array of contexts.
   *
   * @return array
   *   An array of plugin definitions.
   *
   * @see \Drupal\Core\Plugin\FilteredPluginManagerInterface::getFilteredDefinitions()
   */
  public function getDefinitionsForContexts(array $contexts = []);

}


text:
package com.ocdsoft.bacta.swg.precu.controller.game.object.command;

import com.google.inject.Inject;
import com.ocdsoft.bacta.soe.controller.Command;
import com.ocdsoft.bacta.soe.connection.SoeUdpConnection;
import com.ocdsoft.bacta.swg.precu.event.ObservableGameEvent;
import com.ocdsoft.bacta.swg.precu.message.player.LogoutMessage;
import com.ocdsoft.bacta.swg.precu.object.tangible.TangibleObject;
import com.ocdsoft.bacta.swg.precu.object.tangible.creature.CreaturePosture;
import com.ocdsoft.bacta.swg.precu.task.GameTask;
import com.ocdsoft.network.service.scheduler.SchedulerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

@Command(id=0x3b65950)
public class LogoutCommandController implements CommandController {

	private Logger logger = LoggerFactory.getLogger(getClass().getSimpleName());

    private final SchedulerService schedulerService;

    @Inject
    public LogoutCommandController(SchedulerService schedulerService) {
        this.schedulerService = schedulerService;
    }

	@Override
	public void handleCommand(SoeUdpConnection connection, TangibleObject invoker, TangibleObject target, String params) {

        schedulerService.schedule(new LogoutTask(client), 30, TimeUnit.SECONDS);
	}

    private class LogoutTask extends GameTask {

        private final SoeUdpConnection connection;

        public LogoutTask(SoeUdpConnection connection) {
            this.client = client;
            client.getCharacter().setPosture(CreaturePosture.SITTING);
            client.getCharacter().register(this, ObservableGameEvent.POSTURE_CHANGE);
        }

        @Override
        public void run() {
            if(client != null) {
                client.getCharacter().unregister(this, ObservableGameEvent.POSTURE_CHANGE);

                LogoutMessage logout = new LogoutMessage();
                client.sendMessage(logout);

                client.disconnect();
                client.close();
            }
        }

        @Override
        public void update(ObservableGameEvent observableGameEvent) {
            if(observableGameEvent == ObservableGameEvent.POSTURE_CHANGE) {
                client.getCharacter().unregister(this, ObservableGameEvent.POSTURE_CHANGE);
                cancel(false);
            }
        }
    }
}


text:
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"><title>RenameFTPFile</title>

RenameFTPFile()

语法

Result = RenameFTPFile(#Ftp, Filename$, NewFilename$)

概要

Renames a file on the FTP server.

参数

#Ftp

The connection to use.

Filename$

The name of the file on the server to be renamed.
The renamed file has to be in the current directory (see GetFTPDirectory()
and SetFTPDirectory()). It is not possible to specify a subpath in the Filename$.

NewFilename$

The new name for the file on the server.
The renamed file has to be in the current directory (see GetFTPDirectory()
and SetFTPDirectory()). It is not possible to specify a subpath in the NewFilename$.

返回值

Returns nonzero if the file was renamed successfully and zero otherwise.

参阅

SendFTPFile(), SetFTPDirectory(), GetFTPDirectory(),

已支持操作系统
所有

<- ReceiveFTPFile() - Ftp Index - SendFTPFile() ->


text:
<?php

class ProjectsController extends Zend_Controller_Action {
	private $oCache;
	private $oSettings;
	private $oAccount;
	public function init() {
		/* Initialize action controller here */
		$this -> oSettings = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', 'production');
	}

	public function indexAction() {

		$this -> oCache = new Application_Model_Cache(md5('projects/index'));
		if ($this -> oCache -> isOlderAs($this -> oSettings -> website -> cachetime)) {
			$aBoxes = array();
			$aNavigations = array();
			$oPage = new Application_Model_Page();
			$oApstack = new Application_Model_Appstackapi;

			$oApstack -> setCompReq('index_news', 'appstack', 'index_news');
			$oApstack -> setCompReq('files', 'appstack', false, 281);
			$oApstack -> setCompReq('social', 'appstack', false, 277);
			$oApstack -> setCompReq('wide', 'appstack', false, 269);
			$aWideImages = $oApstack -> ask($oApstack -> getReq('wide', 'comp'));
			$aContent = $oApstack -> ask($oApstack -> getReq('index_news', 'comp'), true);
			$aIndexFiles = $oApstack -> ask($oApstack -> getReq('files', 'comp'));
			$aSocialFiles = $oApstack -> ask($oApstack -> getReq('social', 'comp'));
			$sWideImages = '';
			$sIndexFilesHTML = '';
			$sSocialNetworks = '';

			foreach ($aIndexFiles as $iNumComp => $aComposite) {
				$sIndexFilesHTML .= $oPage -> teaserFile($aComposite);
			}

			foreach ($aSocialFiles as $iNumComp => $aComposite) {
				$sSocialNetworks .= $oPage -> teaserSocial($aComposite);
			}

			foreach ($aWideImages as $iWideImg => $aComposite) {
				$sWideImages .= $oPage -> linkImage($aComposite);
			}

			// Dont edit the following three lines
			$aNavigations['HEADNAV'] = $oPage -> getNavi('navi_top', 'top_nav', 'apst_small');
			$aNavigations['MAINNAV'] = $oPage -> getNavi('navi_main', 'main_nav', '');
			$aNavigations['FOOTERNAV'] = $oPage -> getNavi('navi_bottom', 'footer', 'clearfix apst_small', ' | ');

			// Fill boxes with content
			array_push($aBoxes, $oPage -> getBox('

' . $sWideImages . '

', '', 'big_box'));
			array_push($aBoxes, $oPage -> getBox($aContent[0]['source_content'], false, 'small_box'));
			array_push($aBoxes, $oPage -> getTabbox('tabboxes'));
			array_push($aBoxes, $oPage -> getBox($sIndexFilesHTML, 'documents', 'small_left'));
			array_push($aBoxes, $oPage -> getBox('DATEN', 'signup', 'small_left'));
			array_push($aBoxes, $oPage -> getBox($sSocialNetworks, 'social', 'small_box'));

			$this -> oCache -> writeCache($oPage -> getPage('door', $aNavigations, $aBoxes, 'landing.js'));
			$this -> view -> sPage = $this -> oCache -> readCache();
		} else {
			$this -> view -> sPage = $this -> oCache -> readCache();
		}
	}

	public function contentpageAction() {

		$this -> oCache = new Application_Model_Cache(md5('projects/contentpage'));

		if ($this -> oCache -> isOlderAs($this -> oSettings -> website -> cachetime)) {
			$aBoxes = array('LEFT' => array(), 'CONTENT' => array(), 'RIGHT' => array());
			$aNavigations = array();
			$oPage = new Application_Model_Page();
			$oApstack = new Application_Model_Appstackapi;

			$aNavigations['HEADNAV'] = $oPage -> getNavi('navi_top', 'top_nav', 'apst_small');
			$aNavigations['MAINNAV'] = $oPage -> getNavi('navi_main', 'main_nav', '');
			$aNavigations['FOOTERNAV'] = $oPage -> getNavi('navi_bottom', 'footer', 'clearfix apst_small', ' | ');

			array_push($aBoxes['LEFT'], $oPage -> getBox('X', 'l1', 'teaser_box'));
			array_push($aBoxes['CONTENT'], $oPage -> getBox('y', 'c1', 'content_box'));
			array_push($aBoxes['RIGHT'], $oPage -> getBox('z', 'r1', 'teaser_box'));

			$this -> oCache -> writeCache($oPage -> getPage('content', $aNavigations, $aBoxes, 'landing.js'));
			$this -> view -> sPage = $this -> oCache -> readCache();
		} else {
			$this -> view -> sPage = $this -> oCache -> readCache();
		}
	}

}
?>


text:
! { dg-do run }
! { dg-require-effective-target static_libgfortran }
! { dg-additional-sources static_linking_1.c }
! { dg-options "-static" }
!
! This testcase checks that statically linking libgfortran with C main()
! really calls the constructor function
! PR libfortran/22298
      subroutine f
        print *, "subroutine output"
      end


text:
[jvm]
Content
open override fun [localization](localization.md)(value: [Type](https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Type.html)): [FieldAccess.Builder](index.md)
More info

See [Accessor.localization](../../-accessor/localization.md)

[jvm]
Content
lateinit var [localization](localization.md): [Type](https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Type.html)


text:
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var pkg = require('./package.json');
var name = pkg.name;
var banner = [
  '',
  '',
  ''].join('\n');

gulp.task('coffee', function() {
  gulp.src('src/coffee/' + name + '.coffee')
    .pipe(plugins.coffeelint({
      indentation: 2,
      no_trailing_semicolons: true,
      no_trailing_whitespace: true
    }))
    .pipe(plugins.coffee()).on('error', plugins.util.log)
    .pipe(plugins.header(banner, { pkg: pkg }))
    .pipe(gulp.dest('build/js'))
    .pipe(plugins.uglify())
    .pipe(plugins.header(banner, { pkg: pkg }))
    .pipe(plugins.rename({ suffix: '.min' }))
    .pipe(gulp.dest('build/js'));
});

gulp.task('less-bootstrap2', function() {
  gulp.src('src/less/bootstrap2/build.less')
    .pipe(plugins.less())
    .pipe(plugins.header(banner, { pkg: pkg }))
    .pipe(plugins.rename({ basename: name }))
    .pipe(gulp.dest('build/css/bootstrap2'))
    .pipe(plugins.less({
      compress: true,
      cleancss: true
    }))
    .pipe(plugins.header(banner, { pkg: pkg }))
    .pipe(plugins.rename({ suffix: '.min' }))
    .pipe(gulp.dest('build/css/bootstrap2'));
});

gulp.task('less-bootstrap3', function() {
  gulp.src('src/less/bootstrap3/build.less')
    .pipe(plugins.less())
    .pipe(plugins.header(banner, { pkg: pkg }))
    .pipe(plugins.rename({ basename: name }))
    .pipe(gulp.dest('build/css/bootstrap3'))
    .pipe(plugins.less({
      compress: true,
      cleancss: true
    }))
    .pipe(plugins.header(banner, { pkg: pkg }))
    .pipe(plugins.rename({ suffix: '.min' }))
    .pipe(gulp.dest('build/css/bootstrap3'));
});

gulp.task('docs', function() {
  gulp.src('docs/index.jade')
    .pipe(plugins.jade())
    .pipe(gulp.dest('./'));
});

gulp.task('connect', ['docs'], plugins.connect.server({
  root: [__dirname],
  open: true
}));

gulp.task('watch', ['connect'], function() {
  gulp.watch('src/coffee/' + name + '.coffee', ['coffee']).on('change', function(data) {
    gulp.src(data.path).pipe(plugins.connect.reload());
  });

  gulp.watch('src/less/bootstrap2/*.less', ['less-bootstrap2']).on('change', function(data) {
    gulp.src(data.path).pipe(plugins.connect.reload());
  });

  gulp.watch('src/less/bootstrap3/*.less', ['less-bootstrap3']).on('change', function(data) {
    gulp.src(data.path).pipe(plugins.connect.reload());
  });

  gulp.watch('docs/index.jade', ['docs']).on('change', function(data) {
    gulp.src(data.path).pipe(plugins.connect.reload());
  });

});

gulp.task('less', ['less-bootstrap2', 'less-bootstrap3']);
gulp.task('build', ['coffee', 'less']);
gulp.task('default', ['connect', 'build', 'docs', 'watch']);


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('orm', '0009_auto_20170914_2351'),
    ]

    operations = [
        migrations.AlterField(
            model_name='raid',
            name='private_channel',
            field=models.BigIntegerField(null=True),
        ),
        migrations.AlterField(
            model_name='raidmessage',
            name='channel',
            field=models.BigIntegerField(),
        ),
        migrations.AlterField(
            model_name='raidmessage',
            name='message',
            field=models.BigIntegerField(),
        ),
        migrations.AlterField(
            model_name='raidparticipant',
            name='user_id',
            field=models.BigIntegerField(),
        ),
        migrations.AlterField(
            model_name='raidzone',
            name='destination',
            field=models.BigIntegerField(),
        ),
    ]


text:
GPSLogger::GPSLogger() {
  //this->gps = &gGPS;
}

GPSLogger::GPSLogger(GPS* gps, Adafruit_FRAM_I2C* staticMemory) {
  this->gps = gps;
  this->staticMemory = staticMemory;
}

GPSLogger::~GPSLogger() {
}

void GPSLogger::begin() {
  readLoggerData();
  this->loggerData.lastLat = 0;
  this->loggerData.lastLng = 0;
  this->loggerData.logCounter = 0;
  this->lastLocationAvailable = false;
  Serial.println(F("GPS logger ready"));
}

uint32_t GPSLogger::getDistanceTravelled() {
  return this->loggerData.distanceTravelled;
}

void GPSLogger::locateHome(float lat, float lng) {
  if (kHomeLat>lat) {
    this->loggerData.homeLatDir = 'N';
  }
  else {
    this->loggerData.homeLatDir = 'S';
  }
  if (kHomeLng>lng) {
    this->loggerData.homeLngDir = 'E';
  }
  else {
    this->loggerData.homeLngDir = 'W';
  }
}

void GPSLogger::log() {
  float lat, lng;
  this->gps->latlng(&lat, &lng);
  if (this->lastLocationAvailable) {
    uint32_t distIncrement = this->dist(this->lastLat, this->lastLng, lat, lng);
    if (this->gps->speed()>=kMinLogSpeed || distIncrement>=kMinLogDistance) {
      this->loggerData.lastDistance = distIncrement;
      this->loggerData.distanceTravelled+=distIncrement;
      this->loggerData.tripDistance+=distIncrement;
      this->loggerData.distanceTravelledScaled = this->loggerData.distanceTravelled / 100;
      this->loggerData.tripDistanceScaled = this->loggerData.tripDistance / 100;
      this->lastLat = lat;
      this->lastLng = lng;
      this->loggerData.lastLat = lat;
      this->loggerData.lastLng = lng;
      this->loggerData.logged = true;
      this->writeLoggerData();
    }
  }
  else {
    this->lastLocationAvailable = true;
    this->lastLat = lat;
    this->lastLng = lng;
  }
  float currentSpeed = this->gps->speed();
  float currentAltitude = this->gps->altitude();
  if (currentSpeed > this->loggerData.maxSpeed) {
    this->loggerData.maxSpeed = currentSpeed;
  }
  if (currentAltitude > this->loggerData.maxAltitude) {
    this->loggerData.maxAltitude = currentAltitude;
  }
  if (currentAltitude < this->loggerData.minAltitude) {
    this->loggerData.minAltitude = currentAltitude;
  }
  this->loggerData.distanceFromHome = this->dist(kHomeLat, kHomeLng, lat, lng);
  this->locateHome(lat, lng);
  this->loggerData.logCounter++;
}

void GPSLogger::resetLastLocation() {
  this->lastLat = 0;
  this->lastLng = 0;
  this->lastLocationAvailable = false;
  this->loggerData.logged = false;
}

void GPSLogger::writeLoggerData() {
  int address = kLoggerDataStatusAddress;
  staticMemoryWrite(this->staticMemory, address, &kLoggerDataAvailable, sizeof(uint8_t));
  address = kLoggerDataAddress;
  staticMemoryWrite(this->staticMemory, address, &this->loggerData.distanceTravelled, sizeof(this->loggerData.distanceTravelled));
  staticMemoryWrite(this->staticMemory, address, &this->loggerData.timeInMotion, sizeof(this->loggerData.timeInMotion));
  staticMemoryWrite(this->staticMemory, address, &this->loggerData.maxSpeed, sizeof(this->loggerData.maxSpeed));
  staticMemoryWrite(this->staticMemory, address, &this->loggerData.minAltitude, sizeof(this->loggerData.minAltitude));
  staticMemoryWrite(this->staticMemory, address, &this->loggerData.maxAltitude, sizeof(this->loggerData.maxAltitude));
}

void GPSLogger::readLoggerData() {
  uint8_t dataStatus = 0;
  int address = kLoggerDataStatusAddress;
  staticMemoryRead(this->staticMemory, address, &dataStatus, sizeof(uint8_t));
  if (dataStatus!=kLoggerDataAvailable) {
    return;
  }
  address = kLoggerDataAddress;
  staticMemoryRead(this->staticMemory, address, &this->loggerData.distanceTravelled, sizeof(this->loggerData.distanceTravelled));
  staticMemoryRead(this->staticMemory, address, &this->loggerData.timeInMotion, sizeof(this->loggerData.timeInMotion));
  staticMemoryRead(this->staticMemory, address, &this->loggerData.maxSpeed, sizeof(this->loggerData.maxSpeed));
  staticMemoryRead(this->staticMemory, address, &this->loggerData.minAltitude, sizeof(this->loggerData.minAltitude));
  staticMemoryRead(this->staticMemory, address, &this->loggerData.maxAltitude, sizeof(this->loggerData.maxAltitude));
  this->loggerData.distanceTravelledScaled = this->loggerData.distanceTravelled / 100;
  this->loggerData.tripDistanceScaled = this->loggerData.tripDistance / 100;

}

uint32_t GPSLogger::dist(float lat1, float lng1, float lat2, float lng2) {
  float dist_calc=0;
  float dist_calc2=0;
  float diflat=0;
  float diflon=0;

  diflat=radians(lat2-lat1);
  lat1=radians(lat1);
  lat2=radians(lat2);
  diflon=radians((lng2)-(lng1));

  dist_calc = (sin(diflat/2.0)*sin(diflat/2.0));
  dist_calc2= cos(lat1);
  dist_calc2*=cos(lat2);
  dist_calc2*=sin(diflon/2.0);
  dist_calc2*=sin(diflon/2.0);
  dist_calc +=dist_calc2;

  dist_calc=(2*atan2(sqrt(dist_calc),sqrt(1.0-dist_calc)));

  dist_calc*=6371000.0; //Converting to meters
  return dist_calc;
}

const LoggerData& GPSLogger::getLoggerData() {
  return this->loggerData;
}

void GPSLogger::setDistanceTravelled(long dist) {
  this->loggerData.distanceTravelled = dist;
  this->loggerData.distanceTravelledScaled = dist / 100;
  this->writeLoggerData();
}


text:
#include "internal.h"

int
vlan_lookup_table_write(xmlTextWriterPtr writer,
                        struct sja1105_static_config *config)
{
	int rc = 0;
	int i;

	logv("writing %d VLAN Lookup entries", config->vlan_lookup_count);
	for (i = 0; i < config->vlan_lookup_count; i++) {
		rc |= xmlTextWriterStartElement(writer, BAD_CAST "entry");
		rc |= xml_write_field(writer, "index",      i);
		rc |= xml_write_field(writer, "ving_mirr",  config->vlan_lookup[i].ving_mirr);
		rc |= xml_write_field(writer, "vegr_mirr",  config->vlan_lookup[i].vegr_mirr);
		rc |= xml_write_field(writer, "vmemb_port", config->vlan_lookup[i].vmemb_port);
		rc |= xml_write_field(writer, "vlan_bc",    config->vlan_lookup[i].vlan_bc);
		rc |= xml_write_field(writer, "tag_port",   config->vlan_lookup[i].tag_port);
		rc |= xml_write_field(writer, "vlanid",     config->vlan_lookup[i].vlanid);
		rc |= xmlTextWriterEndElement(writer);
		if (rc < 0) {
			loge("error while writing vlan_lookup Table element %d", i);
			return -EINVAL;
		}
	}
	return 0;
}


text:
## Angular2 Express Starter

- Angular 2 ( 2.1 release )
- ExpressJS ( 4.x - with compression )
- Webpack ( angular-cli )
- Redux ( NgRx/Store - with server calls)

[![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy)

## Install / Development

```bash
git clone https://github.com/vladotesanovic/angular2-express-starter
cd angular2-express-starter

# Install dependencies
npm install

# start server
npm run start

# Client url: http://localhost:4200
# Application ( epxress ) API: http://localhost:4300
```

## Build / Production

```bash

npm run build

## Deploy dist folder to app server

Structure of dist folder:

/dist/server <-- expressjs
/dist/client <-- angular2

```


text:
layout: publication
category: publication
title: Predicate Monads
authors: Edwin Westbrook and Gregory Malecha
where: CoqPL'17
tags:
- coq
- monads
- verification
- logic
links:
 - paper: /publications/files/westbrook-coqpl17.pdf
 - conference link: http://popl17.sigplan.org/track/main#modal-phid_0636d96dda07318a382417ed35867ef8
---
@inproceedings{westbrook-predicate-monads,
  title={Predicate {M}onads: A {F}ramework for {P}roving {G}eneric {P}roperties of {M}onadic {P}rograms via {R}ewriting},
  authors={Edwin Westbrook and Gregory Malecha},
  year={2017},
  month=Jan,
  conference={CoqPL'17},
  location={Paris, France}
}


text:
//
//  UIImage+ASConvenience.h
//  AsyncDisplayKit
//
//  Created by Hannah Troisi on 6/24/16.
//
//  Copyright (c) 2014-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//

#import <UIKit/UIImage.h>
#import <UIKit/UIBezierPath.h>

// High-performance flat-colored, rounded-corner resizable images
//
// For "Baked-in Opaque" corners, set cornerColor equal to the color behind the rounded image object, e.g. the background color.
// For "Baked-in Alpha" corners, set cornerColor = [UIColor clearColor]
//
// See http://asyncdisplaykit.org/docs/corner-rounding.html for an explanation.

@interface UIImage (ASDKAdditions)

/**
 * This generates a flat-color, rounded-corner resizeable image
 *
 * @param cornerRadius The radius of the rounded-corner
 * @param cornerColor  The fill color of the corners (For Alpha corners use clearColor)
 * @param fillColor    The fill color of the rounded-corner image
 */
+ (UIImage *)as_resizableRoundedImageWithCornerRadius:(CGFloat)cornerRadius
                                          cornerColor:(UIColor *)cornerColor
                                            fillColor:(UIColor *)fillColor;

/**
 * This generates a flat-color, rounded-corner resizeable image with a border
 *
 * @param cornerRadius The radius of the rounded-corner
 * @param cornerColor  The fill color of the corners (For Alpha corners use clearColor)
 * @param fillColor    The fill color of the rounded-corner image
 * @param borderColor  The border color. Set to nil for no border.
 * @param borderWidth  The border width. Dummy value if borderColor = nil.
 */
+ (UIImage *)as_resizableRoundedImageWithCornerRadius:(CGFloat)cornerRadius
                                          cornerColor:(UIColor *)cornerColor
                                            fillColor:(UIColor *)fillColor
                                          borderColor:(UIColor *)borderColor
                                          borderWidth:(CGFloat)borderWidth;

/**
 * This generates a flat-color, rounded-corner resizeable image with a border
 *
 * @param cornerRadius    The radius of the rounded-corner
 * @param cornerColor     The fill color of the corners (For Alpha corners use clearColor)
 * @param fillColor       The fill color of the rounded-corner image
 * @param borderColor     The border color. Set to nil for no border.
 * @param borderWidth     The border width. Dummy value if borderColor = nil.
 * @param roundedCorners  Select individual or multiple corners to round. Set to UIRectCornerAllCorners to round all 4 corners.
 * @param scale           The number of pixels per point. Provide 0.0 to use the screen scale.
 */
+ (UIImage *)as_resizableRoundedImageWithCornerRadius:(CGFloat)cornerRadius
                                          cornerColor:(UIColor *)cornerColor
                                            fillColor:(UIColor *)fillColor
                                          borderColor:(UIColor *)borderColor
                                          borderWidth:(CGFloat)borderWidth
                                       roundedCorners:(UIRectCorner)roundedCorners
                                                scale:(CGFloat)scale;

@end


text:
package com.elfec.cobranza.business_logic;

import com.elfec.cobranza.business_logic.data_exchange.DataExporter;
import com.elfec.cobranza.business_logic.data_exchange.DataExporter.ExportSpecs;
import com.elfec.cobranza.model.CoopReceipt;
import com.elfec.cobranza.model.PeriodBankAccount;
import com.elfec.cobranza.model.WSCollection;
import com.elfec.cobranza.model.enums.ExportStatus;
import com.elfec.cobranza.model.enums.TransactionAction;
import com.elfec.cobranza.model.events.DataExportListener;
import com.elfec.cobranza.model.exceptions.NoPeriodBankAccountException;
import com.elfec.cobranza.model.results.DataAccessResult;
import com.elfec.cobranza.remote_data_access.WSCollectionRDA;

import org.joda.time.DateTime;

import java.net.ConnectException;
import java.sql.SQLException;
import java.util.List;

/**
 * Maneja las operaciones de negocio de COB_WS
 * @author drodriguez
 *
 */
public class WSCollectionManager {

	/**
	 * Genera el COB_WS para el cobro realizado
	 * @param receipt
	 * @param type COBRANZA o ANULACION_COBRANZA
	 * @return WSCollection
	 * @throws NoPeriodBankAccountException
	 */
	public static WSCollection generateWSCollection(CoopReceipt receipt, TransactionAction type) throws NoPeriodBankAccountException {
		PeriodBankAccount period = PeriodBankAccount.findByCashdeskNumberAndDate(SessionManager.getLoggedCashdeskNumber());
		if(period==null)
			throw new NoPeriodBankAccountException(SessionManager.getLoggedCashdeskNumber());
		return new WSCollection(type, receipt.getReceiptId(), "P",
					1, SessionManager.getLoggedCashdeskNumber(),
					period.getPeriodNumber(),
					DateTime.now(), ExportStatus.NOT_EXPORTED);
	}

	/**
	 * Exporta todos los COB_WS
	 * @return resultado del acceso remoto a datos
	 */
	public static DataAccessResult<Boolean> exportAllWSCollections(final String username, final String password,
			DataExportListener exportListener)
	{
		return DataExporter.exportData(new ExportSpecs<WSCollection>() {

			@Override
			public List<WSCollection> requestExportData() {
				return WSCollection.getExportPendingWSCollections();
			}

			@Override
			public int exportData(WSCollection wSCollection) throws ConnectException,
					SQLException {
				return WSCollectionRDA.insertWSCollection(username, password,
						getWSCollectionWithRemoteTransactionNumber(username, password, wSCollection));
			}
		}, exportListener);
	}

	/**
	 * Solicita y asigna un numero de transacción remoto para el WSCollection
	 * @param username
	 * @param password
	 * @param wSCollection
	 * @return la misma instancia del wSCollection con el numero de transacción remoto asignado
	 * @throws ConnectException
	 * @throws SQLException
	 */
	public static WSCollection getWSCollectionWithRemoteTransactionNumber(String username, String password, WSCollection wSCollection) throws ConnectException, SQLException
	{
		if(wSCollection.getRemoteTransactionNumber()==null)
		{
			wSCollection.setRemoteTransactionNumber(
					WSCollectionRDA.requestRemoteTransactionNumber(username, password));
			wSCollection.save();
		}
		return wSCollection;
	}

}


text:
package App::Netdisco::Web::Plugin::Report::PortBlocking;

use Dancer ':syntax';
use Dancer::Plugin::DBIC;
use Dancer::Plugin::Auth::Extensible;

use App::Netdisco::Web::Plugin;

register_report(
    {   category     => 'Port',
        tag          => 'portblocking',
        label        => 'Ports that are blocking',
        provides_csv => 1,
        api_endpoint => 1,
    }
);

get '/ajax/content/report/portblocking' => require_login sub {
    my @results = schema(vars->{'tenant'})->resultset('Device')->search(
        { 'stp' => [ 'blocking', 'broken' ], 'up' => { '!=', 'down' } },
        {   select       => [ 'ip', 'dns', 'name' ],
            join         => ['ports'],
            '+columns'   => [
                { 'port'        => 'ports.port' },
                { 'description' => 'ports.name' },
                { 'stp'         => 'ports.stp' },
            ]
        }
    )->hri->all;

    return unless scalar @results;

    if ( request->is_ajax ) {
        my $json = to_json (\@results);
        template 'ajax/report/portblocking.tt', { results => $json }, { layout => 'noop' };
    }
    else {
        header( 'Content-Type' => 'text/comma-separated-values' );
        template 'ajax/report/portblocking_csv.tt',
            { results => \@results, }, { layout => 'noop' };
    }
};

1;


text:
function BreadCrumbsDirective($route,$location) {
  function link(scope) {
    scope.roots = [];
    for(var path in $route.routes) {
      if (path != 'null' && path.lastIndexOf('/') !== path.length-1) {
        if ($route.routes[path].rootView == true) {
          scope.roots.push($route.routes[path]);
        }
      }
    }

    scope.goToRoot = function() {
      $location.url(scope.root);
    }
  }

  return {
    templateUrl: 'components/breadCrumbs/breadCrumbs.html',
    link: link,
    scope: {
      title: '@',
      root: '@',
      intermediate: '='
    }
  }
}

BreadCrumbsDirective.$inject = ['$route','$location'];

angular.module('gallery.breadcrumbs.directive',[])
.directive('cbBreadcrumbs',BreadCrumbsDirective);


text:
cask 'permute' do
  version '3.3.8,2211'
  sha256 '26b53cb5fe5295dae3c57214ae19ead0342a8b4ff814bedd47f7465df052d05b'

  url "https://trial.charliemonroe.net/permute/v#{version.major}/Permute_#{version.major}_#{version.after_comma}.dmg"
  appcast "https://trial.charliemonroe.net/permute/updates_#{version.major}.xml"
  name 'Permute'
  homepage 'https://software.charliemonroe.net/permute.php'

  auto_updates true
  depends_on macos: '>= :el_capitan'

  app "Permute #{version.major}.app"
end


text:
Google analytics tool for visualising which devices and browsers are used to visit your websites.

work-in-progress.


text:
package org.kie.api.fluent;

public interface SubProcessNodeBuilder<T extends NodeContainerBuilder<T, ?>> extends NodeBuilder<SubProcessNodeBuilder<T>, T>, HumanNodeOperations<SubProcessNodeBuilder<T>, T> {

    SubProcessNodeBuilder<T> processId(final String processId);

    SubProcessNodeBuilder<T> waitForCompletion(boolean waitForCompletion);

    SubProcessNodeBuilder<T> inMapping(String parameterName, String variableName);

    SubProcessNodeBuilder<T> outMapping(String parameterName, String variableName);

    SubProcessNodeBuilder<T> independent(boolean independent);

}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.MSBuild
{
    /// <summary>
    /// Represents a project file loaded from disk.
    /// </summary>
    internal sealed class ProjectFileInfo
    {
        /// <summary>
        /// The path to the output file this project generates.
        /// </summary>
        public string OutputFilePath { get; }

        /// <summary>
        /// The assembly name of the output.
        /// </summary>
        public string AssemblyName { get; }

        /// <summary>
        /// The command line args used to compile the project.
        /// </summary>
        public IReadOnlyList<string> CommandLineArgs { get; }

        /// <summary>
        /// The source documents.
        /// </summary>
        public IReadOnlyList<DocumentFileInfo> Documents { get; }

        /// <summary>
        /// The additional documents.
        /// </summary>
        public IReadOnlyList<DocumentFileInfo> AdditionalDocuments { get; }

        /// <summary>
        /// References to other projects.
        /// </summary>
        public IReadOnlyList<ProjectFileReference> ProjectReferences { get; }

        /// <summary>
        /// The error message produced when a failure occurred attempting to get the info.
        /// If a failure occurred some or all of the information may be inaccurate or incomplete.
        /// </summary>
        public string ErrorMessage { get; }

        public ProjectFileInfo(
            string outputPath,
            string assemblyName,
            IEnumerable<string> commandLineArgs,
            IEnumerable<DocumentFileInfo> documents,
            IEnumerable<DocumentFileInfo> additionalDocuments,
            IEnumerable<ProjectFileReference> projectReferences,
            string errorMessage)
        {
            this.OutputFilePath = outputPath;
            this.AssemblyName = assemblyName;
            this.CommandLineArgs = commandLineArgs.ToImmutableArrayOrEmpty();
            this.Documents = documents.ToImmutableReadOnlyListOrEmpty();
            this.AdditionalDocuments = additionalDocuments.ToImmutableArrayOrEmpty();
            this.ProjectReferences = projectReferences.ToImmutableReadOnlyListOrEmpty();
            this.ErrorMessage = errorMessage;
        }
    }
}