text:
package com.google.android.apps.exposurenotification.testsupport;

import com.google.android.apps.exposurenotification.common.time.Clock;
import org.threeten.bp.Duration;
import org.threeten.bp.Instant;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZonedDateTime;

/**
 * A very simple fake {@link Clock} providing values in place of {@link System#currentTimeMillis()},
 * {@link Instant#now()} or {@link ZonedDateTime#now()}.
 */
public class FakeClock implements Clock {

  private static final ZoneId ECT_TIME_ZONE = ZoneId.of("Europe/Paris");

  private Instant now;
  private ZoneId zoneId = ECT_TIME_ZONE;

  public FakeClock() {
    this(Instant.ofEpochMilli(100_000_000_000L));
  }

  public FakeClock(Instant now) {
    this.now = now;
  }

  @Override
  public long currentTimeMillis() {
    return now.toEpochMilli();
  }

  @Override
  public Instant now() {
    return now;
  }

  @Override
  public ZonedDateTime zonedNow() {
    return now.atZone(zoneId);
  }

  public void advance() {
    advanceBy(Duration.ofMillis(1));
  }

  public void advanceBy(Duration increment) {
    now = now.plus(increment);
  }

  public void moveBack() {
    moveBackBy(Duration.ofMillis(1));
  }

  public void moveBackBy(Duration decrement) {
    now = now.minus(decrement);
  }

  public void set(Instant time) {
    now = time;
  }

  public void setZoneId(ZoneId zoneId) {
    this.zoneId = zoneId;
  }
}


text:
/* global describe, it, expect */
'use strict'

const underTest = require('../lib/reply')

describe('Reply', () => {
  it('should be a function', () => {
    expect(typeof underTest).toBe('function')
  })

  it('should not return anything if message is not a string or an object', () => {
    expect(underTest()).not.toBeDefined()
    expect(underTest(123)).not.toBeDefined()
    expect(underTest(1.2)).not.toBeDefined()
    expect(underTest([])).not.toBeDefined()
    expect(underTest([1, 2])).not.toBeDefined()
  })

  it('should return an object if message is a string', () => {
    expect(underTest('hello')).toEqual({
      version: '1.0',
      response: {
        shouldEndSession: true,
        outputSpeech: {
          type: 'PlainText',
          text: 'hello'
        }
      }
    })
  })

  it('should not return anything if message is an empty string', () => {
    expect(underTest('')).not.toBeDefined()
  })

  it('should not return anything if message contains just spaces and tabs', () => {
    expect(underTest(' ')).not.toBeDefined()
    expect(underTest('     ')).not.toBeDefined()
    expect(underTest('\t')).not.toBeDefined()
    expect(underTest('\n')).not.toBeDefined()
    expect(underTest(' \t\n')).not.toBeDefined()
  })

  it('should return the object if message is an object and not null', () => {
    expect(underTest({})).toEqual({})
  })

  it('should not return anything if message is null', () => {
    expect(underTest(null)).not.toBeDefined()
  })
})

redpajama_set_name: RedPajamaGithub


text:
title: Drive sales efficiency through an enterprise social network
contexts: office365,microsoft365
copyright: Microsoft
translations: en
tools: SharePoint,Skype for Business,Yammer
areas: Sales
color: #777777
icon: https://jumpto365.com/resources/images/app/jumpto365-Icon-white.png
externalref: https://www.microsoft.com/en-us/microsoft-365/success/productivitylibrary/drive-sales-efficiency-through-an-enterprise-social-network
---
Connect sales reps across the globe with the current information, real-time support, and relevant insights they need to drive sales success.

## Build a network of trusted colleagues to support sales activities

Effective sales reps are naturally good communicators, but when they are dispersed around the world, keeping them connected can be a challenge. Sales teams can bridge the gap by connecting everyone in a communication channel they are already fluent in: social networking. With the **Yammer** enterprise social network, reps can converse with their peers, follow companywide conversations, and keep up with the latest best practices, account insights, and sales strategies from management. Yammer can also integrate with third-party sales tools and software, making it a powerful, one-stop platform for sales reps on the go.

[View Training](https://support.office.com/article/Communicate-in-groups-52db606b-2f29-4a9a-8cbb-b43bf2a27d2e)

[IFRAME](https://www.microsoft.com/en-us/videoplayer/embed/RE1TRuX)

## Help sales reps find critical product information any time, from anywhere

Whether they are on a sales floor or meeting at a customer's site far from the main office, sales reps need the most current and pertinent product information at their fingertips. In a **SharePoint** team site, you can create a document library to store and share product line specs, sales documents, videos, and much more. SharePoint integrates with **Yammer** through Office Groups, so sales reps can quickly access the information they need. And with the Yammer mobile app, sales reps can tap into these resources from their own device, any time they need them.

[View Training](https://support.office.com/article/Collaborate-with-team-content-using-SharePoint-Online-2dd9aeff-7749-4b78-9696-eb0f6267f1f5)

[IFRAME](https://www.microsoft.com/en-us/videoplayer/embed/RE1US0c)

## Tap into customer preferences and predict requests to generate leads

To learn more about customer preferences, sales and marketing teams can invite customers to share their feedback through a **Yammer** external group. In an external group, teams can conduct polls and pose questions directly from Yammer. External participants can see only those Yammer groups that are specifically set up as external, so the company's internal communications are secure. When the teams have the customer feedback they need, they can join internal conversations on Yammer to talk about their findings and generate viable leads.

[View Training](https://support.office.com/article/Create-and-manage-external-groups-in-Yammer-9ccd15ce-0efc-4dc1-81bc-4a424ab6f92a)

[IFRAME](https://www.microsoft.com/en-us/videoplayer/embed/RE1TubY)

## Easily pull subject matter experts into sales conversations

When a customer asks a question, the speed with which the sales rep can come back with the right answer can make the difference between a sales win or loss. The **Yammer** social network can be the expert in your pocket, allowing you to post customer questions to the network, and instantly tap into the expertise of the entire company, directly from your device. Or for face-to-face interaction, you can use the **Skype for Business** mobile app to pull a product expert into a customer meeting in real time.

[View Training](https://www.youtube.com/embed/qVq7A7nS_TQ)

[IFRAME](https://www.microsoft.com/en-us/videoplayer/embed/RE1TwSA)


text:
<?php

namespace bmwx591\yrl\offer;

class LotOffer extends BaseOffer
{

}


text:
package sese

import (
	"encoding/xml"

	"github.com/fgrid/iso20022"
)

type Document03200106 struct {
	XMLName xml.Name                                                  `xml:"urn:iso:std:iso:20022:tech:xsd:sese.032.001.06 Document"`
	Message *SecuritiesSettlementTransactionGenerationNotificationV06 `xml:"SctiesSttlmTxGnrtnNtfctn"`
}

func (d *Document03200106) AddMessage() *SecuritiesSettlementTransactionGenerationNotificationV06 {
	d.Message = new(SecuritiesSettlementTransactionGenerationNotificationV06)
	return d.Message
}

// Scope
// An account servicer sends a SecuritiesSettlementTransactionGenerationNotification to an account owner to advise the account owner of a securities settlement transaction that has been generated/created by the account servicer for the account owner. The reason for creation can range from the automatic transformation of pending settlement instructions following a corporate event to the recovery of an account owner transactions' database initiated by its account servicer.
// The account servicer/owner relationship may be:
// - a central securities depository or another settlement market infrastructure acting on behalf of their participants
// - an agent (sub-custodian) acting on behalf of their global custodian customer, or
// - a custodian acting on behalf of an investment management institution or a broker/dealer
//
// Usage
// The message may also be used to:
// - re-send a message previously sent,
// - provide a third party with a copy of a message for information,
// - re-send to a third party a copy of a message for information
// using the relevant elements in the Business Application Header.
type SecuritiesSettlementTransactionGenerationNotificationV06 struct {

	// Provides transaction type and identification information.
	TransactionIdentificationDetails *iso20022.SettlementTypeAndIdentification19 `xml:"TxIdDtls"`

	// Count of the number of transactions linked.
	NumberCounts *iso20022.NumberCount1Choice `xml:"NbCounts,omitempty"`

	// Link to another transaction that must be processed after, before or at the same time.
	Linkages []*iso20022.Linkages37 `xml:"Lnkgs,omitempty"`

	// Details of the trade.
	TradeDetails *iso20022.SecuritiesTradeDetails51 `xml:"TradDtls"`

	// Financial instrument representing a sum of rights of the investor vis-a-vis the issuer.
	FinancialInstrumentIdentification *iso20022.SecurityIdentification19 `xml:"FinInstrmId"`

	// Elements characterising a financial instrument.
	FinancialInstrumentAttributes *iso20022.FinancialInstrumentAttributes64 `xml:"FinInstrmAttrbts,omitempty"`

	// Details related to the account and quantity involved in the transaction.
	QuantityAndAccountDetails []*iso20022.QuantityAndAccount39 `xml:"QtyAndAcctDtls"`

	// Parameters which explicitly state the conditions that must be fulfilled before a particular  transaction of a financial instrument can be settled.  These parameters are defined by the instructing party in compliance with settlement rules in the market the transaction will settle in.
	SettlementParameters *iso20022.SettlementDetails101 `xml:"SttlmParams"`

	// Identifies the chain of delivering settlement parties.
	DeliveringSettlementParties *iso20022.SettlementParties36 `xml:"DlvrgSttlmPties,omitempty"`

	// Identifies the chain of receiving settlement parties.
	ReceivingSettlementParties *iso20022.SettlementParties36 `xml:"RcvgSttlmPties,omitempty"`

	// Cash parties involved in the transaction if different for the securities settlement parties.
	CashParties *iso20022.CashParties26 `xml:"CshPties,omitempty"`

	// Total amount of money to be paid or received in exchange for the securities.
	SettlementAmount *iso20022.AmountAndDirection46 `xml:"SttlmAmt,omitempty"`

	// Other amounts than the settlement amount.
	OtherAmounts *iso20022.OtherAmounts28 `xml:"OthrAmts,omitempty"`

	// Other business parties relevant to the transaction.
	OtherBusinessParties *iso20022.OtherParties27 `xml:"OthrBizPties,omitempty"`

	// Provides information required for the registration or physical settlement.
	AdditionalPhysicalOrRegistrationDetails *iso20022.RegistrationParameters4 `xml:"AddtlPhysOrRegnDtls,omitempty"`

	// Specifies the reason why the transaction was generated.
	GeneratedReason []*iso20022.GeneratedReason5 `xml:"GnrtdRsn,omitempty"`

	// Status and reason of the transaction.
	StatusAndReason *iso20022.StatusAndReason28 `xml:"StsAndRsn,omitempty"`

	// Additional information that cannot be captured in the structured elements and/or any other specific block.
	SupplementaryData []*iso20022.SupplementaryData1 `xml:"SplmtryData,omitempty"`
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddTransactionIdentificationDetails() *iso20022.SettlementTypeAndIdentification19 {
	s.TransactionIdentificationDetails = new(iso20022.SettlementTypeAndIdentification19)
	return s.TransactionIdentificationDetails
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddNumberCounts() *iso20022.NumberCount1Choice {
	s.NumberCounts = new(iso20022.NumberCount1Choice)
	return s.NumberCounts
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddLinkages() *iso20022.Linkages37 {
	newValue := new(iso20022.Linkages37)
	s.Linkages = append(s.Linkages, newValue)
	return newValue
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddTradeDetails() *iso20022.SecuritiesTradeDetails51 {
	s.TradeDetails = new(iso20022.SecuritiesTradeDetails51)
	return s.TradeDetails
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddFinancialInstrumentIdentification() *iso20022.SecurityIdentification19 {
	s.FinancialInstrumentIdentification = new(iso20022.SecurityIdentification19)
	return s.FinancialInstrumentIdentification
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddFinancialInstrumentAttributes() *iso20022.FinancialInstrumentAttributes64 {
	s.FinancialInstrumentAttributes = new(iso20022.FinancialInstrumentAttributes64)
	return s.FinancialInstrumentAttributes
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddQuantityAndAccountDetails() *iso20022.QuantityAndAccount39 {
	newValue := new(iso20022.QuantityAndAccount39)
	s.QuantityAndAccountDetails = append(s.QuantityAndAccountDetails, newValue)
	return newValue
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddSettlementParameters() *iso20022.SettlementDetails101 {
	s.SettlementParameters = new(iso20022.SettlementDetails101)
	return s.SettlementParameters
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddDeliveringSettlementParties() *iso20022.SettlementParties36 {
	s.DeliveringSettlementParties = new(iso20022.SettlementParties36)
	return s.DeliveringSettlementParties
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddReceivingSettlementParties() *iso20022.SettlementParties36 {
	s.ReceivingSettlementParties = new(iso20022.SettlementParties36)
	return s.ReceivingSettlementParties
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddCashParties() *iso20022.CashParties26 {
	s.CashParties = new(iso20022.CashParties26)
	return s.CashParties
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddSettlementAmount() *iso20022.AmountAndDirection46 {
	s.SettlementAmount = new(iso20022.AmountAndDirection46)
	return s.SettlementAmount
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddOtherAmounts() *iso20022.OtherAmounts28 {
	s.OtherAmounts = new(iso20022.OtherAmounts28)
	return s.OtherAmounts
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddOtherBusinessParties() *iso20022.OtherParties27 {
	s.OtherBusinessParties = new(iso20022.OtherParties27)
	return s.OtherBusinessParties
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddAdditionalPhysicalOrRegistrationDetails() *iso20022.RegistrationParameters4 {
	s.AdditionalPhysicalOrRegistrationDetails = new(iso20022.RegistrationParameters4)
	return s.AdditionalPhysicalOrRegistrationDetails
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddGeneratedReason() *iso20022.GeneratedReason5 {
	newValue := new(iso20022.GeneratedReason5)
	s.GeneratedReason = append(s.GeneratedReason, newValue)
	return newValue
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddStatusAndReason() *iso20022.StatusAndReason28 {
	s.StatusAndReason = new(iso20022.StatusAndReason28)
	return s.StatusAndReason
}

func (s *SecuritiesSettlementTransactionGenerationNotificationV06) AddSupplementaryData() *iso20022.SupplementaryData1 {
	newValue := new(iso20022.SupplementaryData1)
	s.SupplementaryData = append(s.SupplementaryData, newValue)
	return newValue
}


text:
<?xml version="1.0"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\CatalogInventory\Model\Stock\Item" type="Magento\CatalogInventory\Model\Adminhtml\Stock\Item" />
    <type name="Magento\Catalog\Model\Product\CopyConstructor\Composite">
        <arguments>
            <argument name="constructors" xsi:type="array">
                <item name="catalog_inventory" xsi:type="string">Magento\CatalogInventory\Model\Product\CopyConstructor\CatalogInventory</item>
            </argument>
        </arguments>
    </type>
    <type name="Magento\CatalogInventory\Model\Spi\StockStateProviderInterface">
        <arguments>
            <argument name="qtyCheckApplicable" xsi:type="boolean">false</argument>
        </arguments>
    </type>
    <type name="Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider">
        <arguments>
            <argument name="addFieldStrategies" xsi:type="array">
                <item name="qty" xsi:type="object">Magento\CatalogInventory\Ui\DataProvider\Product\AddQuantityFieldToCollection</item>
            </argument>
            <argument name="addFilterStrategies" xsi:type="array">
                <item name="qty" xsi:type="object">Magento\CatalogInventory\Ui\DataProvider\Product\AddQuantityFilterToCollection</item>
            </argument>
        </arguments>
    </type>
    <virtualType name="Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Pool">
        <arguments>
            <argument name="modifiers" xsi:type="array">
                <item name="advancedInventory" xsi:type="array">
                    <item name="class" xsi:type="string">Magento\CatalogInventory\Ui\DataProvider\Product\Form\Modifier\AdvancedInventory</item>
                    <item name="sortOrder" xsi:type="number">20</item>
                </item>
            </argument>
        </arguments>
    </virtualType>
</config>


text:
import mock

from rally.benchmark.context import secgroup
from tests import fakes
from tests import test

class SecGroupContextTestCase(test.TestCase):

    @mock.patch('rally.benchmark.context.secgroup.osclients.Clients')
    def test_prep_ssh_sec_group(self, mock_osclients):
        fake_nova = fakes.FakeNovaClient()
        self.assertEqual(len(fake_nova.security_groups.list()), 1)
        mock_cl = mock.MagicMock()
        mock_cl.nova.return_value = fake_nova
        mock_osclients.return_value = mock_cl

        secgroup._prepare_open_secgroup('endpoint')

        self.assertEqual(len(fake_nova.security_groups.list()), 2)
        self.assertTrue(
            secgroup.SSH_GROUP_NAME in
                [sg.name for sg in fake_nova.security_groups.list()]
        )

        # run prep again, check that another security group is not created
        secgroup._prepare_open_secgroup('endpoint')
        self.assertEqual(len(fake_nova.security_groups.list()), 2)

    @mock.patch('rally.benchmark.context.secgroup.osclients.Clients')
    def test_prep_ssh_sec_group_rules(self, mock_osclients):
        fake_nova = fakes.FakeNovaClient()

        #NOTE(hughsaunders) Default security group is precreated
        self.assertEqual(len(fake_nova.security_groups.list()), 1)
        mock_cl = mock.MagicMock()
        mock_cl.nova.return_value = fake_nova
        mock_osclients.return_value = mock_cl

        secgroup._prepare_open_secgroup('endpoint')

        self.assertEqual(len(fake_nova.security_groups.list()), 2)
        rally_open = fake_nova.security_groups.find(secgroup.SSH_GROUP_NAME)
        self.assertEqual(len(rally_open.rules), 3)

        # run prep again, check that extra rules are not created
        secgroup._prepare_open_secgroup('endpoint')
        rally_open = fake_nova.security_groups.find(secgroup.SSH_GROUP_NAME)
        self.assertEqual(len(rally_open.rules), 3)


text:
import os
import sys
from antlr4.error.ErrorListener import ErrorListener

from dirlistproc.DirectoryListProcessor import DirectoryListProcessor
from antlr4 import *
from antlr4.InputStream import InputStream

_curdir = os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.join(_curdir, '..'))

from shexypy.utils.xmlutils import prettyxml
from shexypy.shexyparser.parser_impl.ShExDocVisitor_impl import ShExDocVisitor_impl

START_RULE = "shExDoc"
GRAMMAR_RULE = "ShExDoc"
VISITOR = "ShExDocVisitor_impl"

failing_tests = [
    "1refbnode_with_spanning_PN_CHARS_BASE1.shex",
    "1val1STRING_LITERAL1_with_all_controls.shex",
    "refbnode_with_spanning_PN_CHARS_BASE1.shex",
    "1val1STRING_LITERAL1_with_ascii_boundaries.shex",
    "1val1STRING_LITERAL1_with_UTF8_boundaries.shex",
    "_all.shex",
    "open1dotclose.shex",
    "open1dotcloseAnnot3.shex",
    "open1dotclosecardOpt.shex",
    "open1dotcloseCode1.shex",
    "openopen1dotcloseCode1closeCode2.shex"
]

class StdInputStream(InputStream):
    """ Create an inputstream out of stdin
    """
    def __init__(self):
        InputStream.__init__(self, sys.stdin.read())

def get_object(name):
    """ Return an object named "name" from a package of the same name
    :param name: package/object to retrieve
    :return: reference to the actual object
    """
    module = __import__(name, fromlist=[name])
    return getattr(module, name)

def get_lexer(instream: InputStream) -> Lexer:
    """ Build a lexer for the input stream
    :param instream: input stream
    :return:
    """
    return get_object(GRAMMAR_RULE + 'Lexer')(instream)

def get_parser(tokens: CommonTokenStream) -> Parser:
    """ Build a parser
    :param tokens: token stream
    :return:
    """
    return get_object(GRAMMAR_RULE + 'Parser')(tokens)

class ParseErrorListener(ErrorListener):

    def __init__(self):
        self.n_errors = 0

    def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
        self.n_errors += 1

    def reportAmbiguity(self, recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs):
        self.n_errors += 1

    def reportAttemptingFullContext(self, recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs):
        self.n_errors += 1

    def reportContextSensitivity(self, recognizer, dfa, startIndex, stopIndex, prediction, configs):
        self.n_errors += 1

def do_parse(infile: InputStream) -> ShExDocVisitor_impl:
    lexer = get_lexer(infile)
    error_listener = ParseErrorListener()
    lexer.addErrorListener(error_listener)
    tokens = CommonTokenStream(lexer)
    tokens.fill()
    if error_listener.n_errors:
        return None
    parser = get_parser(tokens)
    parser.addErrorListener(error_listener)
    tree = getattr(parser, START_RULE)()
    visitor = get_object(VISITOR)()
    visitor.visit(tree)
    return visitor if not error_listener.n_errors else None

def proc_file(infile, outfile, _):
    if infile:
        print("Parsing " + infile, file=sys.stderr)
    else:
        print("Enter ShEx to parse:")
        print()
    result = do_parse(FileStream(infile, encoding='utf8') if infile else StdInputStream())

    if result:
        pretty_result = prettyxml(result.to_dom())
        if outfile:
            open(outfile, 'w').write(pretty_result)
        else:
            print(pretty_result)
    else:
        print("Parse failure", file=sys.stderr)
        return False

nskipped = 0

def file_filter(fn):
    global nskipped
    if fn in failing_tests:
        print("*** Skipping %s" % fn)
        nskipped += 1
        return False
    return True

def main(argv: list):
    global nskipped
    sys.path.append(os.path.join(_curdir, '../shexypy/shexyparser/parser'))
    sys.path.append(os.path.join(_curdir, '../shexypy/shexyparser/parser_impl'))

    dlp = DirectoryListProcessor(argv, "ShEx to XML Parser", '.shex', '.xml')
    nskipped = 0
    nfiles, npassed = dlp.run(proc_file, file_filter=file_filter)

    def _pl(s, n) -> (int, str):
        return n, s if n == 1 else (s + 's')

    print(file=sys.stderr)
    print("***** " + ("Success" if nfiles == npassed else "FAILURE") + " *****", file=sys.stderr)
    print("\t%d %s Processed" % _pl("File", nfiles), file=sys.stderr)
    print("\t%d %s" % _pl("Error", nfiles - npassed), file=sys.stderr)
    print("\t%d %s Skipped" % _pl("File", nskipped), file=sys.stderr)

if __name__ == '__main__':
    main(sys.argv[1:])


text:
package com.google.cloud.tools.eclipse.appengine.localserver;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.util.Base64;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.Iam.Projects.ServiceAccounts.Keys;
import com.google.api.services.iam.v1.model.CreateServiceAccountKeyRequest;
import com.google.api.services.iam.v1.model.ServiceAccountKey;
import com.google.cloud.tools.eclipse.googleapis.IGoogleApiFactory;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;

public class ServiceAccountUtil {

  /**
   * Creates and saves a service account key the App Engine default service account.
   *
   * @param credential credential to use to create a service account key
   * @param projectId GCP project ID for {@code serviceAccountId}
   * @param destination path of a key file to be saved
   */
  public static void createAppEngineDefaultServiceAccountKey(IGoogleApiFactory apiFactory,
      Credential credential, String projectId, Path destination)
          throws FileAlreadyExistsException, IOException {
    Preconditions.checkNotNull(credential, "credential not given");
    Preconditions.checkState(!projectId.isEmpty(), "project ID empty");
    Preconditions.checkArgument(destination.isAbsolute(), "destination not absolute");

    if (!Files.exists(destination.getParent())) {
      Files.createDirectories(destination.getParent());
    }

    Iam iam = apiFactory.newIamApi(credential);
    Keys keys = iam.projects().serviceAccounts().keys();

    String projectEmail = projectId;
    // The appengine service account for google.com:gcloud-for-eclipse-testing
    // would be gcloud-for-eclipse-testing.google.com@appspot.gserviceaccount.com.
    if (projectId.contains(":")) {
      String[] parts = projectId.split(":");
      projectEmail = parts[1] + "." + parts[0];
    }
    String serviceAccountId = projectEmail + "@appspot.gserviceaccount.com";

    String keyId = "projects/" + projectId + "/serviceAccounts/" + serviceAccountId;
    CreateServiceAccountKeyRequest createRequest = new CreateServiceAccountKeyRequest();
    ServiceAccountKey key = keys.create(keyId, createRequest).execute();

    byte[] jsonKey = Base64.decodeBase64(key.getPrivateKeyData());
    Files.write(destination, jsonKey);
  }
}


text:
package io.crate.analyze.symbol;

import org.elasticsearch.common.collect.Tuple;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Map;

public class Assignments {

    /**
     * convert assignments into a tuple of fqn column names and the symbols.
     *
     *

     *     {
     *         users.age:  users.age + 1,
     *         users.name: users.name || 'foo'
     *
     *     }
     *

     * becomes
     *

     *     ( [users.age, users.name], [users.age + 1, users.name || 'foo'] )
     *

     * @return a tuple or null if the input is null.
     */
    public static Tuple<String[], Symbol[]> convert(@Nonnull Map<Reference, ? extends Symbol> assignments) {
        String[] assignmentColumns = new String[assignments.size()];
        Symbol[] assignmentSymbols = new Symbol[assignments.size()];
        int i = 0;
        for (Map.Entry<Reference, ? extends Symbol> entry : assignments.entrySet()) {
            Reference key = entry.getKey();
            assignmentColumns[i] = key.ident().columnIdent().fqn();
            assignmentSymbols[i] = entry.getValue();
            i++;
        }
        return new Tuple<>(assignmentColumns, assignmentSymbols);
    }
}


text:
using System.Drawing;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Jojatekok.MintPalAPI.Demo
{
    static class Helper
    {
        public static ImageSource ToImageSource(this Icon icon)
        {
            return Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="module_soma" default="compile.module.soma">
  <dirname property="module.soma.basedir" file="${ant.file.module_soma}"/>

  <property name="module.jdk.home.soma" value="${project.jdk.home}"/>
  <property name="module.jdk.bin.soma" value="${project.jdk.bin}"/>
  <property name="module.jdk.classpath.soma" value="${project.jdk.classpath}"/>

  <property name="compiler.args.soma" value="${compiler.args}"/>

  <property name="soma.output.dir" value="${module.soma.basedir}/out/production/SOMa"/>
  <property name="soma.testoutput.dir" value="${module.soma.basedir}/out/test/SOMa"/>

  <path id="soma.module.bootclasspath">
    <!-- Paths to be included in compilation bootclasspath -->
    <pathelement location="lib/forms_rt.jar"/>
  </path>

  <path id="soma.module.production.classpath">
    <path refid="${module.jdk.classpath.soma}"/>
    <pathelement location="lib/testng-jdk15.jar"/>
  </path>

  <path id="soma.runtime.production.module.classpath">
    <pathelement location="${soma.output.dir}"/>
    <pathelement location="lib/testng-jdk15.jar"/>
  </path>

  <path id="soma.module.classpath">
    <path refid="${module.jdk.classpath.soma}"/>
    <pathelement location="${soma.output.dir}"/>
    <pathelement location="lib/testng-jdk15.jar"/>
  </path>

  <path id="soma.runtime.module.classpath">
    <pathelement location="${soma.testoutput.dir}"/>
    <pathelement location="${soma.output.dir}"/>
    <pathelement location="lib/testng-jdk15.jar"/>
  </path>

  <patternset id="excluded.from.module.soma">
    <patternset refid="ignored.files"/>
  </patternset>

  <patternset id="excluded.from.compilation.soma">
    <patternset refid="excluded.from.module.soma"/>
  </patternset>

  <path id="soma.module.sourcepath">
    <dirset dir="${module.soma.basedir}">
      <include name="src"/>
    </dirset>
  </path>

  <path id="soma.module.test.sourcepath">
    <dirset dir="${module.soma.basedir}">
      <include name="test"/>
    </dirset>
  </path>

  <target name="compile.module.soma" depends="compile.module.soma.production,compile.module.soma.tests" description="Compile module SOMa"/>

  <target name="compile.module.soma.production" depends="register.custom.compilers" description="Compile module SOMa; production classes">
    <mkdir dir="${soma.output.dir}"/>
    <javac2 destdir="${soma.output.dir}" debug="${compiler.debug}" nowarn="${compiler.generate.no.warnings}" memorymaximumsize="${compiler.max.memory}" fork="true" executable="${module.jdk.bin.soma}/javac" includeantruntime="false">
      <compilerarg line="${compiler.args.soma}"/>
      <bootclasspath refid="soma.module.bootclasspath"/>
      <classpath refid="soma.module.production.classpath"/>
      <src refid="soma.module.sourcepath"/>
      <patternset refid="excluded.from.compilation.soma"/>
    </javac2>

    <copy todir="${soma.output.dir}">
      <fileset dir="${module.soma.basedir}/src">
        <patternset refid="compiler.resources"/>
        <type type="file"/>
      </fileset>
    </copy>
  </target>

  <target name="compile.module.soma.tests" depends="register.custom.compilers,compile.module.soma.production" description="compile module SOMa; test classes" unless="skip.tests">
    <mkdir dir="${soma.testoutput.dir}"/>
    <javac2 destdir="${soma.testoutput.dir}" debug="${compiler.debug}" nowarn="${compiler.generate.no.warnings}" memorymaximumsize="${compiler.max.memory}" fork="true" executable="${module.jdk.bin.soma}/javac" includeantruntime="false">
      <compilerarg line="${compiler.args.soma}"/>
      <bootclasspath refid="soma.module.bootclasspath"/>
      <classpath refid="soma.module.classpath"/>
      <src refid="soma.module.test.sourcepath"/>
      <patternset refid="excluded.from.compilation.soma"/>
    </javac2>

    <copy todir="${soma.testoutput.dir}">
      <fileset dir="${module.soma.basedir}/test">
        <patternset refid="compiler.resources"/>
        <type type="file"/>
      </fileset>
    </copy>
  </target>

  <target name="clean.module.soma" description="cleanup module">
    <delete dir="${soma.output.dir}"/>
    <delete dir="${soma.testoutput.dir}"/>
  </target>
</project>


text:
#ifndef WIN32
#define HTS
#endif

#ifdef HTS
#include "htslib/sam.h"
#endif

#ifdef _DEBUG
ofstream SAM_OFH("scaffolding_entries.sam");
#endif

using namespace std;

void examine_frags(const set<string>& iworm_left, const set<string>& iworm_right, map<pair<string, string>, int>& paired_iworm_contigs)
{
	if (iworm_left.size() == 0 || iworm_right.size() == 0)
		return;	// no pairs

	if (iworm_left.size() == 1 && iworm_right.size() == 1)
	{
		string k1 = *iworm_left.begin();
		string k2 = *iworm_right.begin();
		if (k1 != k2)
		{
			if (k2 < k1) swap(k1, k2);

			pair<string, string> key(k1, k2);
			if (paired_iworm_contigs.find(key) == paired_iworm_contigs.end())
				paired_iworm_contigs[key] = 1;
			else
				paired_iworm_contigs[key]++;

#ifdef _DEBUG
			SAM_OFH << k1 << k2 << endl;
#endif

		}
	}
}

struct map_key
{
	template <typename T>
	typename T::first_type operator()(T keyValuePair) const
	{
		return keyValuePair.first;
	}
};

template <typename T>
struct sort_pred {
	map<T, int> &_hash;
	sort_pred(map<T, int>& h) : _hash(h) {}
	bool operator()(const T &left, const T &right) {
		return _hash[left] > _hash[right];
	}
};

template <typename T>
void copy_to_out(map<T, int>& paired_iworm_contigs, map<string, int>& iworm_acc_to_fasta_index)
{
	vector<T> outvec;
	const char *my_endl = "\n";

	outvec.reserve(paired_iworm_contigs.size());
	transform(paired_iworm_contigs.begin(), paired_iworm_contigs.end(), back_inserter(outvec), map_key());
	sort(outvec.begin(), outvec.end(), sort_pred<T >(paired_iworm_contigs));
	for (typename vector<T>::const_iterator a = outvec.begin(); a != outvec.end(); ++a)
	{
		const int index_A = iworm_acc_to_fasta_index[a->first];
		const int index_B = iworm_acc_to_fasta_index[a->second];

		cout << a->first << '\t' << index_A << '\t';
		cout << a->second << '\t' << index_B << '\t';
		cout << paired_iworm_contigs[*a] << my_endl;
	}
}

void index_iworm(string iworm_fasta, map<string, int>& aMap)
{
	int counter = 0;

	ifstream fh(iworm_fasta.c_str());
	while (fh)
	{
		string line;
		fh >> line;
		if (line[0] == '>')
			aMap[line.substr(1, string::npos)] = counter++;
	}
}

void validate_iworm(string iworm_acc)
{
	pair<int, int> a;

	if (iworm_acc[0] == 'a') iworm_acc[0] = ' ';
	replace(iworm_acc.begin(), iworm_acc.end(), ';', ' ');
	istringstream iss2(iworm_acc);
	iss2 >> a.first >> a.second;
	if (iss2.fail())
		throw bad_name_exception();
}

pair<string, int> parse_read_name(string read_acc)
{
	pair<string, int> result;
	size_t s = read_acc.rfind('/');
	result.first = read_acc.substr(0, s);
	result.second = read_acc[s + 1] - '1';

	if (s == string::npos || (result.second != 0 && result.second != 1))
		throw single_read_exception();

	return result;
}

void process_line(string read_acc, string iworm_acc, set<string>& iworm_left,
	set<string>& iworm_right, string& prev_core_acc,
	map<pair<string, string>, int>& paired_iworm_contigs,
	error_checker& checker)
{
	try
	{
		validate_iworm(iworm_acc);

		pair<string, int> read = parse_read_name(read_acc);
		const string core_acc = read.first;
		int frag_end = read.second;

		if (core_acc != prev_core_acc)
		{
			examine_frags(iworm_left, iworm_right, paired_iworm_contigs);
			iworm_left.clear();
			iworm_right.clear();
		}

		if (frag_end == 0)
			iworm_left.insert(iworm_acc);
		if (frag_end == 1)
			iworm_right.insert(iworm_acc);

		prev_core_acc = core_acc;
	}
	catch (const bad_name_exception&)
	{
		checker.add_bad_name(iworm_acc, read_acc);
	}
	catch (const single_read_exception&)
	{
		checker.add_single_read(read_acc);
	}
}

int main(int argc, char* argv[])
{
	string usage = "\n\nusage: ScaffoldIwormContigs nameSorted.sam iworm_fasta_file\n\n";
	if (argc != 3)
	{
		cerr << usage;
		return -1;
	}

	string name_sorted_sam_file(argv[1]);
	map<string, int> iworm_acc_to_fasta_index;
	index_iworm(argv[2], iworm_acc_to_fasta_index);

	string prev_core_acc;
	map<pair<string,string>, int> paired_iworm_contigs;
	set<string> iworm_left;
	set<string> iworm_right;
	error_checker errors;

	samFile *in = sam_open(name_sorted_sam_file.c_str(), "r");
	bam_hdr_t *h = sam_hdr_read(in);
	bam1_t *b = bam_init1();

	while (sam_read1(in, h, b) > 0)
	{
		string read_acc(bam_get_qname(b));
		if (b->core.tid >= 0)
		{
			string iworm_acc(h->target_name[b->core.tid]);
			process_line(read_acc, iworm_acc, iworm_left, iworm_right, prev_core_acc, paired_iworm_contigs, errors);
		}
	}

	int r = sam_close(in);
	if (r < 0) {
		throw runtime_error("Error closing input");
	}

	// get last one
	examine_frags(iworm_left, iworm_right, paired_iworm_contigs);

	errors.report();

	copy_to_out(paired_iworm_contigs, iworm_acc_to_fasta_index);

	return 0;
}


text:
init:
	#pandoc -o README.rst README.md
	cp README.rst ./docs/index.rst
	python setup.py sdist upload


text:
layout: base
title:  'Statistics of Number[psor] in UD_Buryat-BDT'
udver: '2'
---

## Treebank Statistics: UD_Buryat-BDT: Features: `Number[psor]`

This feature is language-specific.
It occurs with 1 different values: `Sing`.

This is a layered feature with the following layers: <tt>Number</tt>, <tt>Number[psor]</tt>.

108 tokens (1%) have a non-empty value of `Number[psor]`.
92 types (2%) occur at least once with a non-empty value of `Number[psor]`.
80 lemmas (3%) occur at least once with a non-empty value of `Number[psor]`.
The feature is used with 5 part-of-speech tags: <tt>NOUN</tt> (75; 1% instances), <tt>VERB</tt> (21; 0% instances), <tt>PRON</tt> (6; 0% instances), <tt>ADV</tt> (4; 0% instances), <tt>PROPN</tt> (2; 0% instances).

### `NOUN`

75 <tt>NOUN</tt> tokens (2% of all `NOUN` tokens) have a non-empty value of `Number[psor]`.

The most frequent other feature values with which `NOUN` and `Number[psor]` co-occurred: <tt>Number</tt><tt>=EMPTY</tt> (74; 99%).

`NOUN` tokens may have the following values of `Number[psor]`:

`Number[psor]` seems to be **lexical feature** of `NOUN`. 100% lemmas (53) occur only with one value of `Number[psor]`.

### `VERB`

21 <tt>VERB</tt> tokens (1% of all `VERB` tokens) have a non-empty value of `Number[psor]`.

The most frequent other feature values with which `VERB` and `Number[psor]` co-occurred: <tt>Mood</tt><tt>=EMPTY</tt> (21; 100%), <tt>Number</tt><tt>=EMPTY</tt> (21; 100%), <tt>Person</tt><tt>=EMPTY</tt> (21; 100%), <tt>Tense</tt><tt>=EMPTY</tt> (21; 100%), <tt>VerbForm</tt><tt>=Ger</tt> (21; 100%).

`VERB` tokens may have the following values of `Number[psor]`:

`Number[psor]` seems to be **lexical feature** of `VERB`. 100% lemmas (18) occur only with one value of `Number[psor]`.

### `PRON`

6 <tt>PRON</tt> tokens (2% of all `PRON` tokens) have a non-empty value of `Number[psor]`.

The most frequent other feature values with which `PRON` and `Number[psor]` co-occurred: <tt>Person</tt><tt>=EMPTY</tt> (6; 100%), <tt>PronType</tt><tt>=Dem</tt> (6; 100%), <tt>Number</tt><tt>=EMPTY</tt> (5; 83%).

`PRON` tokens may have the following values of `Number[psor]`:

### `ADV`

4 <tt>ADV</tt> tokens (1% of all `ADV` tokens) have a non-empty value of `Number[psor]`.

`ADV` tokens may have the following values of `Number[psor]`:

### `PROPN`

2 <tt>PROPN</tt> tokens (0% of all `PROPN` tokens) have a non-empty value of `Number[psor]`.

The most frequent other feature values with which `PROPN` and `Number[psor]` co-occurred: <tt>Case</tt><tt>=Abl</tt> (2; 100%), <tt>Gender</tt><tt>=EMPTY</tt> (2; 100%).

`PROPN` tokens may have the following values of `Number[psor]`:

## Relations with Agreement in `Number[psor]`

The 10 most frequent relations where parent and child node agree in `Number[psor]`:
<tt>VERB --[<tt>nmod</tt>]--> PROPN</tt> (1; 100%).


text:
package com.yunos.alicontacts.plugin.duplicateremove;

import android.text.TextUtils;

import java.util.HashSet;
import java.util.Set;

public class Utils {
    public final static String TAG = Utils.class.getSimpleName();
    public static final boolean DBG = true;

    public static long hash(String s) {
        long seed = 131; // 31 131 1313 13131 131313 etc.. BKDRHash
        long hash = 0;

        if (s == null) {
            return hash;
        }

        int len = s.length();
        for (int i = 0; i < len; i++) {
            hash = (hash * seed) + s.charAt(i);
        }

        return hash;
    }

    public static String phoneNormalize(String number) {
        if (number == null || number.length() == 0)
            return number;

        // ???if phone numbers compare with normalized form,
        // here should be implemented.
        // now we use identical method
        return number;
    }

    public static <T> boolean isTwoSetIntersect(Set<T> first, Set<T> second) {
        if (first == null || second == null) {
            // Log.i(TAG, "isTwoSetIntersect return false for null reference");
            return false;
        }

        HashSet<T> copy_set = new HashSet<T>(first);
        copy_set.retainAll(second);

        return (!copy_set.isEmpty());
    }

    /**
     * Delete all whitespace and hyphen in phone number string.
     *
     * @param str input string
     * @return string
     */
    public static String trimHyphenAndSpaceInNumberString(String str) {
        if (TextUtils.isEmpty(str))
            return str;

        final int sz = str.length();
        final char[] chs = new char[sz];
        int count = 0;
        for (int i = 0; i < sz; i++) {
            final char ch = str.charAt(i);
            if (!Character.isWhitespace(ch) && ch != '-') {
                chs[count++] = ch;
            }
        }
        if (count == sz) {
            return str;
        }
        return new String(chs, 0, count);
    }

}


text:
import android.support.annotation.UiThread;
import java.io.File;
import java.io.IOException;

class StrictModeViolation {
  File f;

  @UiThread
  void violateStrictModeBad() throws IOException {
    f.canRead();
    f.canWrite();
    f.createNewFile();
    f.createTempFile("a", "b");
    f.delete();
    f.getCanonicalPath();
    f.getFreeSpace();
    f.getTotalSpace();
    f.getUsableSpace();
    f.isDirectory();
    f.isFile();
    f.isHidden();
    f.lastModified();
    f.length();
    f.list();
    f.listFiles();
    f.mkdir();
    f.renameTo(f);
    f.setExecutable(true);
    f.setLastModified(1L);
    f.setReadable(true);
    f.setReadOnly();
    f.setWritable(true);
  }
}


text:
<?php
//====================================================================================
// OCS INVENTORY REPORTS
// Copyleft Erwan GOALOU 2010 (erwan(at)ocsinventory-ng(pt)org)
// Web: http://www.ocsinventory-ng.org
//
// This code is open source and may be copied and modified as long as the source
// code is always made freely available.
// Please refer to the General Public Licence http://www.gnu.org/ or Licence.txt
//====================================================================================

/**
  * Hardware locking function. Prevents the hardware to be altered by either the server or another administrator using the GUI
  * @param id Hardware identifier to be locked
  */
function lock($id) {
	$reqClean = "DELETE FROM locks WHERE unix_timestamp(since)<(unix_timestamp(NOW())-3600)";
	$resClean = mysql2_query_secure($reqClean, $_SESSION['OCS']["writeServer"]);

	$reqLock = "INSERT INTO locks(hardware_id) VALUES ('%s')";
	$argLock=$id;
	if( $resLock = mysql2_query_secure($reqLock, $_SESSION['OCS']["writeServer"],$argLock))
		return( mysqli_affected_rows ( $_SESSION['OCS']["writeServer"] ) == 1 );
	else return false;
}

/**
  * Hardware unlocking function
  * @param id Hardware identifier to be unlocked
  */
function unlock($id) {
	$reqLock = "DELETE FROM locks WHERE hardware_id='%s'";
	$argLock=$id;
	$resLock = mysql2_query_secure($reqLock, $_SESSION['OCS']["writeServer"],$argLock);
	return( mysqli_affected_rows ( $_SESSION['OCS']["writeServer"] ) == 1 );
}

/**
  * Show an error message if the locking failed
  */
function errlock() {
	global $l;
	msg_error($l->g(376));
}

function computer_list_by_tag($tag="",$format='LIST'){
	$arg_sql=array();
	if ($tag == ""){
		$sql_mycomputers['SQL']="select hardware_id from accountinfo a where ".$_SESSION['OCS']["mesmachines"];
	}elseif (is_array($tag)){
		$sql_mycomputers="select hardware_id from accountinfo a where a.tag in ";
		$sql_mycomputers=mysql2_prepare($sql_mycomputers,$arg_sql,$tag);
	}else{
		$sql_mycomputers="select hardware_id from accountinfo a where a.tag in ";
		$sql_mycomputers=mysql2_prepare($sql_mycomputers,$arg_sql,$tag);
	}
	$res_mycomputers = mysql2_query_secure($sql_mycomputers['SQL'], $_SESSION['OCS']["readServer"],$sql_mycomputers['ARG']);
	$mycomputers="(";
	while ($item_mycomputers = mysqli_fetch_object($res_mycomputers)){
		$mycomputers.= $item_mycomputers->hardware_id.",";
		$array_mycomputers[]=$item_mycomputers->hardware_id;
	}
	$mycomputers=substr($mycomputers,0,-1).")";
	if ($mycomputers == "()" or !isset($array_mycomputers))
		$mycomputers = "ERROR";
	if ($format == 'LIST'){
		return $mycomputers;
	}else{
		return $array_mycomputers;

	}
}

/**
  * Deleting function
  * @param id Hardware identifier to be deleted
  * @param checkLock Tells wether or not the locking system must be used (default true)
  * @param traceDel Tells wether or not the deleted entities must be inserted in deleted_equiv for tracking purpose (default true)
  */
function deleteDid($id, $checkLock = true, $traceDel = true, $silent=false
) {
	global $l;
	if ($_SESSION['OCS']['profile']->getConfigValue('DELETE_COMPUTERS') == "NO"){
		msg_error($l->g(1273));
		return false;
	}
	//If lock is not user OR it is used and available
	if( ! $checkLock || lock($id) ) {
		$sql="SELECT deviceid,name,IPADDR,OSNAME FROM hardware WHERE id='%s'";
		$resId = mysql2_query_secure($sql,$_SESSION['OCS']["readServer"],$id);
		$valId = mysqli_fetch_array($resId);
		$idHard = $id;
		$did = $valId["deviceid"];
		if( $did ) {
			//Deleting a network device
			if( strpos ( $did, "NETWORK_DEVICE-" ) === false ) {
				$sql="SELECT macaddr FROM networks WHERE hardware_id='%s'";
				$resNetm = mysql2_query_secure($sql, $_SESSION['OCS']["readServer"],$idHard);
				while( $valNetm = mysqli_fetch_array($resNetm)) {
					$sql="DELETE FROM netmap WHERE mac='%s'";
					mysql2_query_secure($sql, $_SESSION['OCS']["readServer"],$valNetm["macaddr"]);
				}
			}
			//deleting a regular computer
			if( $did != "_SYSTEMGROUP_" and $did != '_DOWNLOADGROUP_') {
					$tables=$_SESSION['OCS']['SQL_TABLE_HARDWARE_ID'];
			}
			elseif($did == "_SYSTEMGROUP_" or $did == '_DOWNLOADGROUP_'){//Deleting a group
				$tables=Array("devices");
				//del messages on this group
				$sql_group_msg="DELETE FROM config WHERE name like '%s' and ivalue='%s'";
				mysql2_query_secure($sql_group_msg, $_SESSION['OCS']["writeServer"],array('GUI_REPORT_MSG%',$idHard));
				$sql_group="DELETE FROM groups WHERE hardware_id='%s'";
				mysql2_query_secure($sql_group, $_SESSION['OCS']["writeServer"],$idHard);
				$sql_group_cache="DELETE FROM groups_cache WHERE group_id='%s'";
				$resDelete = mysql2_query_secure($sql_group_cache, $_SESSION['OCS']["writeServer"],$idHard);
				$affectedComputers = mysqli_affected_rows( $_SESSION['OCS']["writeServer"] );
				 //Deleting redistribution group
				$sql_group_cache="DELETE FROM download_servers WHERE group_id='%s'";
				$resDelete = mysql2_query_secure($sql_group_cache, $_SESSION['OCS']["writeServer"],$idHard);
				$affectedComputers = mysqli_affected_rows( $_SESSION['OCS']["writeServer"] );
			}

			if( !$silent )
				msg_success($valId["name"]." ".$l->g(220));

			if (isset($tables) and is_array($tables)){
				foreach ($tables as $table) {
					$sql="DELETE FROM %s WHERE hardware_id='%s'";
					$arg=array($table,$idHard);
					mysql2_query_secure($sql, $_SESSION['OCS']["writeServer"],$arg);
				}
			}
			$sql="delete from download_enable where SERVER_ID='%s'";
			mysql2_query_secure($sql, $_SESSION['OCS']["writeServer"],$idHard);
			$sql="DELETE FROM hardware WHERE id='%s'";
			mysql2_query_secure($sql, $_SESSION['OCS']["writeServer"],$idHard);
			//Deleted computers tracking
			if($traceDel && mysqli_num_rows(mysql2_query_secure("SELECT IVALUE FROM config WHERE IVALUE>0 AND NAME='TRACE_DELETED'", $_SESSION['OCS']["readServer"]))){
				$sql="insert into deleted_equiv(DELETED,EQUIVALENT) values('%s',%s)";
				$arg=array($did,'NULL');
				mysql2_query_secure($sql, $_SESSION['OCS']["writeServer"],$arg);
			}
		}
		//Using lock ? Unlock
		if( $checkLock )
			unlock($id);
		return $valId["name"];
	}
	else
		errlock();

}

function fusionne($afus) {

	global $l;
	$i=0;
	$maxStamp = 0;
	$minStamp = mktime(0,0,0,date("m"),date("d") + 1,date("Y")); //demain
	foreach($afus as $a) {
		$d = $a["lastcome"];
		$a["stamp"] = mktime($d[11].$d[12],$d[14].$d[15],$d[17].$d[18],$d[5].$d[6],$d[8].$d[9],$d[0].$d[1].$d[2].$d[3]);
		//echo "stamp:".$a["stamp"]."== mktime($d[11]$d[12],$d[14]$d[15],$d[17]$d[18],$d[5]$d[6],$d[8]$d[9],$d[0]$d[1]$d[2]$d[3]);
";
		if($maxStamp<$a["stamp"]) {
			$maxStamp = $a["stamp"];
			$maxInd = $i;
		}
		if($minStamp>$a["stamp"]) {
			$minStamp = $a["stamp"];
			$minInd = $i;
		}
		$i++;
	}
	if($afus[$minInd]["deviceid"]!="") {
		$okLock = true;
		foreach($afus as $a) {
			if( ! $okLock = ($okLock && lock($a["id"])) )
				break;
			else
				$locked[] = $a["id"];
		}

		if( $okLock ) {
			//TRACE_DELETED
			if(mysqli_num_rows(mysql2_query_secure("SELECT * FROM config WHERE IVALUE>0 AND NAME='TRACE_DELETED'", $_SESSION['OCS']["readServer"]))){
				foreach($afus as $a) {
					if($afus[$maxInd]["deviceid"]==$a["deviceid"]){continue;}
					$sql="insert into deleted_equiv(DELETED,EQUIVALENT) values('%s','%s')";
					$arg=array($a["deviceid"],$afus[$maxInd]["deviceid"]);
					mysql2_query_secure($sql, $_SESSION['OCS']["writeServer"],$arg) ;
				}
			}

			//KEEP OLD QUALITY,FIDELITY AND CHECKSUM
			$sql="SELECT CHECKSUM,QUALITY,FIDELITY FROM hardware WHERE ID='%s'";
			$persistent_req = mysql2_query_secure($sql,$_SESSION['OCS']["readServer"],$afus[$minInd]["id"]);

			$reqDelAccount = "DELETE FROM accountinfo WHERE hardware_id='%s'";
			mysql2_query_secure($reqDelAccount, $_SESSION['OCS']["writeServer"],$afus[$maxInd]["id"]) ;
			msg_success($l->g(190)." ".$afus[$maxInd]["deviceid"]." ".$l->g(191));

			$keep = array( "accountinfo",  "devices", "groups_cache" );
			foreach( $keep as $tableToBeKept ) {
				$reqRecupAccount = "UPDATE %s SET hardware_id='%s' WHERE hardware_id='%s'";
				$argRecupAccount=array($tableToBeKept,$afus[$maxInd]["id"],$afus[$minInd]["id"]);
				mysql2_query_secure($reqRecupAccount, $_SESSION['OCS']["writeServer"],$argRecupAccount) ;
			}
			msg_success($l->g(190)." ".$afus[$minInd]["deviceid"]." ".$l->g(206)." ".$afus[$maxInd]["deviceid"]);
			$i=0;
			foreach($afus as $a) {
				if($i != $maxInd) {
					deleteDid($a["id"], false, false,false);
					$lesDel .= $a["deviceid"]."/";
				}
				$i++;
			}

			//RESTORE PERSISTENT VALUES
			$persistent_values = mysqli_fetch_row($persistent_req);
			$sql="UPDATE hardware SET QUALITY=%s,FIDELITY=%s,CHECKSUM=CHECKSUM|%s WHERE id='%s'";
			$arg=array($persistent_values[1],$persistent_values[2],$persistent_values[0],$afus[$maxInd]["id"]);
			mysql2_query_secure($sql, $_SESSION['OCS']["writeServer"],$arg) ;

		}
		else
			errlock();

		foreach($locked as $a) {
			unlock($a);
		}
	}
	$lesDel .= " => ".$afus[$maxInd]["deviceid"];
	AddLog("FUSION", $lesDel);
}

function form_add_computer(){
	global $l;
	$name_field=array("NAME","OSNAME");
		$name_field[]="LASTNAME";
		$name_field[]="EMAIL";
		$name_field[]="COMMENTS";
		//$name_field[]="USER_GROUP";

		$tab_name[]=$l->g(49).": ";
		$tab_name[]=$l->g(996).": ";
		$tab_name[]="Email: ";
		$tab_name[]=$l->g(51).": ";
		//$tab_name[]="Groupe de l'utilisateur: ";

		$type_field[]= 0;
		$type_field[]= 0;
		$type_field[]= 0;
		$type_field[]= 0;
		//$type_field[]= 2;

		if ($id_user != '' or $_SESSION['OCS']['profile']->getConfigValue('CHANGE_USER_GROUP') == 'NO'){
			$tab_hidden['MODIF']=$id_user;
			$sql="select ID,NEW_ACCESSLVL,USER_GROUP,FIRSTNAME,LASTNAME,EMAIL,COMMENTS from operators where id= '%s'";
			$arg=$id_user;
			$res=mysql2_query_secure($sql, $_SESSION['OCS']["readServer"],$arg);
			$row=mysqli_fetch_object($res);
			if ($_SESSION['OCS']['profile']->getConfigValue('CHANGE_USER_GROUP') == 'YES'){
				$protectedPost['ACCESSLVL']=$row->NEW_ACCESSLVL;
				$protectedPost['USER_GROUP']=$row->USER_GROUP;
				$value_field=array($row->ID,$list_profil,$list_groups);
			}
			$value_field[]=$row->FIRSTNAME;
			$value_field[]=$row->LASTNAME;
			$value_field[]=$row->EMAIL;
			$value_field[]=$row->COMMENTS;
		}else{
			if ($_SESSION['OCS']['profile']->getConfigValue('CHANGE_USER_GROUP') == 'YES'){
				$value_field=array($protectedPost['ID'],$list_profil,$list_groups);
			}
			$value_field[]=$protectedPost['FIRSTNAME'];
			$value_field[]=$protectedPost['LASTNAME'];
			$value_field[]=$protectedPost['EMAIL'];
			$value_field[]=$protectedPost['COMMENTS'];
		}
		if ($_SESSION['OCS']['cnx_origine'] == "LOCAL"){
			$name_field[]="PASSWORD";
			$type_field[]=0;
			$tab_name[]=$l->g(217).":";
			$value_field[]=$protectedPost['PASSWORD'];
		}
		$tab_typ_champ=show_field($name_field,$type_field,$value_field);
		foreach ($tab_typ_champ as $id=>$values){
			$tab_typ_champ[$id]['CONFIG']['SIZE']=40;
		}
		if ($_SESSION['OCS']['profile']->getConfigValue('MANAGE_USER_GROUP') == 'YES'){
			$tab_typ_champ[2]["CONFIG"]['DEFAULT']="YES";
		//	$tab_typ_champ[1]['COMMENT_AFTER']="";
			$tab_typ_champ[2]['COMMENT_AFTER']="";
		}

		if (isset($tab_typ_champ)){
			tab_modif_values($tab_name,$tab_typ_champ,$tab_hidden);
		}

}

function insert_manual_computer($values,$nb=1,$generic=false){
	global $i;
		if ($nb == 1)
			$name=$values['COMPUTER_NAME_GENERIC'];
		else
			$name=$values['COMPUTER_NAME_GENERIC'].$i;

		/*if ($generic){
			if ($values['COMPUTER_NAME_GENERIC'] == "")
				$values['COMPUTER_NAME_GENERIC']='MANUEL_ENTRY';
			if ($values['SERIAL_GENERIC'] == "")
				$values['SERIAL_GENERIC']='MANUEL_ENTRY';
			if ($values['ADDR_MAC_GENERIC'] == "")
				$values['ADDR_MAC_GENERIC']='MANUEL_ENTRY';
		}*/
		$sql="insert into hardware (deviceid,name) values ('%s','%s')";
		$arg=array('MANUEL',$name.'_M');
		mysql2_query_secure($sql,$_SESSION['OCS']["writeServer"],$arg);
		$id_computer=mysqli_insert_id($_SESSION['OCS']["writeServer"]);

		$sql="insert into bios (hardware_id,ssn) values ('%s','%s')";
		$arg=array($id_computer,$values['SERIAL_GENERIC'].'_M');
		mysql2_query_secure($sql,$_SESSION['OCS']["writeServer"],$arg);

		$sql="insert into networks (hardware_id,macaddr) values ('%s','%s')";
		$arg=array($id_computer,$values['ADDR_MAC_GENERIC'].'_M');
		mysql2_query_secure($sql,$_SESSION['OCS']["writeServer"],$arg);

		return $id_computer;

}
/*
 * function to verify if user can access
 * on computer
 */
function is_mine_computer($id){
	if (isset($_SESSION['OCS']['TAGS']) and is_array($_SESSION['OCS']['TAGS'])){
		$sql="select hardware_id from accountinfo where hardware_id = %s and tag in ";
		$arg=array($id);
		$sql=mysql2_prepare($sql,$arg,$_SESSION['OCS']['TAGS']);
		$result = mysql2_query_secure( $sql['SQL'], $_SESSION['OCS']["readServer"],$sql['ARG']);
		$item = mysqli_fetch_object($result);
		if (isset($item->hardware_id))
			return true;
		else
			return false;
	}
	return true;
}

function RandomMAC()
{
	$word = "A,B,C,D,E,F,0,1,2,3,4,5,6,7,8,9";
	$mac='';
	$array=explode(",",$word);
	while ($j<8){
		$i=0;
		while ($i<2){
			shuffle($array);
			$mac.=$array[0];
			$i++;
		}
		$mac.=":";
		$j++;
	}

	return substr($mac, 0, -1);
}
?>


text:
package org.mockitousage.junitrule;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.mockito.exceptions.base.MockitoAssertionError;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.VerificationCollector;
import org.mockitousage.IMethods;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.*;

public class VerificationCollectorImplTest {

    @Test
    public void should_not_throw_any_exceptions_when_verifications_are_successful() {
        VerificationCollector collector = MockitoJUnit.collector().assertLazily();

        IMethods methods = mock(IMethods.class);
        methods.simpleMethod();

        verify(methods).simpleMethod();
        collector.collectAndReport();
    }

    @Test(expected = MockitoAssertionError.class)
    public void should_collect_verification_failures() {
        VerificationCollector collector = MockitoJUnit.collector().assertLazily();

        IMethods methods = mock(IMethods.class);

        verify(methods).simpleMethod();
        collector.collectAndReport();
    }

    @Test
    public void should_collect_multiple_verification_failures() {
        VerificationCollector collector = MockitoJUnit.collector().assertLazily();

        IMethods methods = mock(IMethods.class);

        verify(methods).simpleMethod();
        verify(methods).byteReturningMethod();
        try {
            collector.collectAndReport();
            fail();
        } catch (MockitoAssertionError error) {
            assertThat(error).hasMessageContaining("1. Wanted but not invoked:");
            assertThat(error).hasMessageContaining("2. Wanted but not invoked:");
        }
    }

    @Test
    public void should_only_collect_failures_ignore_successful_verifications() {
        VerificationCollector collector = MockitoJUnit.collector().assertLazily();

        IMethods methods = mock(IMethods.class);

        verify(methods, never()).simpleMethod();
        verify(methods).byteReturningMethod();

        this.assertAtLeastOneFailure(collector);
    }

    @Test
    public void should_continue_collecting_after_failing_verification() {
        VerificationCollector collector = MockitoJUnit.collector().assertLazily();

        IMethods methods = mock(IMethods.class);
        methods.simpleMethod();

        verify(methods).byteReturningMethod();
        verify(methods).simpleMethod();

        this.assertAtLeastOneFailure(collector);
    }

    private void assertAtLeastOneFailure(VerificationCollector collector) {
        try {
            collector.collectAndReport();
            fail();
        } catch (MockitoAssertionError error) {
            assertThat(error).hasMessageContaining("1. Wanted but not invoked:");
            assertThat(error.getMessage()).doesNotContain("2.");
        }
    }

    @Test
    public void should_invoke_collector_rule_after_test() {
        JUnitCore runner = new JUnitCore();
        Result result = runner.run(VerificationCollectorRuleInner.class);

        assertThat(result.getFailureCount()).isEqualTo(1);
        assertThat(result.getFailures().get(0).getMessage()).contains("1. Wanted but not invoked:");
    }

    // This class is picked up when running a test suite using an IDE. It fails on purpose.
    public static class VerificationCollectorRuleInner {

        @Rule
        public VerificationCollector collector = MockitoJUnit.collector();

        @Test
        public void should_fail() {
            IMethods methods = mock(IMethods.class);

            verify(methods).simpleMethod();
        }

        @Test
        public void should_not_fail() {
            IMethods methods = mock(IMethods.class);
            methods.simpleMethod();

            verify(methods).simpleMethod();
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Persoonia 12(4): 462 (1985)

#### Original name
Agaricus scabrosus Fr., 1838

### Remarks
null


text:
<?php
/**
 * Smarty Internal Plugin Compile Foreach
 * Compiles the {foreach} {foreachelse} {/foreach} tags
 *
 * @package    Smarty
 * @subpackage Compiler
 * @author     Uwe Tews
 */

/**
 * Smarty Internal Plugin Compile Foreach Class
 *
 * @package    Smarty
 * @subpackage Compiler
 */
class Smarty_Internal_Compile_Foreach extends Smarty_Internal_CompileBase
{
    /**
     * Attribute definition: Overwrites base class.
     *
     * @var array
     * @see Smarty_Internal_CompileBase
     */
    public $required_attributes = array('from', 'item');
    /**
     * Attribute definition: Overwrites base class.
     *
     * @var array
     * @see Smarty_Internal_CompileBase
     */
    public $optional_attributes = array('name', 'key');
    /**
     * Attribute definition: Overwrites base class.
     *
     * @var array
     * @see Smarty_Internal_CompileBase
     */
    public $shorttag_order = array('from', 'item', 'key', 'name');

    /**
     * Compiles code for the {foreach} tag
     *
     * @param  array  $args      array with attributes from parser
     * @param  object $compiler  compiler object
     * @param  array  $parameter array with compilation parameter
     *
     * @return string compiled code
     */
    public function compile($args, $compiler, $parameter)
    {
        // check and get attributes
        $_attr = $this->getAttributes($compiler, $args);

        $from = $_attr['from'];
        $item = $_attr['item'];
        if (!strncmp("\$_smarty_tpl->tpl_vars[$item]", $from, strlen($item) + 24)) {
            $compiler->trigger_template_error("item variable {$item} may not be the same variable as at 'from'", $compiler->lex->taglineno);
        }

        if (isset($_attr['key'])) {
            $key = $_attr['key'];
        } else {
            $key = null;
        }

        $this->openTag($compiler, 'foreach', array('foreach', $compiler->nocache, $item, $key, true));
        // maybe nocache because of nocache variables
        $compiler->nocache = $compiler->nocache | $compiler->tag_nocache;

        if (isset($_attr['name'])) {
            $name = trim($_attr['name'], '\'"');
            $has_name = true;
            $SmartyVarName = "\$smarty.foreach.{$name}.";
        } else {
            $has_name = false;
        }
        $ItemVarName = '$' . trim($item, '\'"') . '@';
        // evaluates which Smarty variables and properties have to be computed

        if ($has_name) {
            $useSmartyForeach = $usesSmartyFirst = strpos($compiler->lex->data, $SmartyVarName . 'first') !== false;
            $useSmartyForeach = ($usesSmartyLast = strpos($compiler->lex->data, $SmartyVarName . 'last') !== false) || $useSmartyForeach;
            $useSmartyForeach = ($usesSmartyIndex = strpos($compiler->lex->data, $SmartyVarName . 'index') !== false) || $useSmartyForeach;
            $useSmartyForeach = ($usesSmartyIteration = (!$usesSmartyIndex && ($usesSmartyFirst || $usesSmartyLast)) || strpos($compiler->lex->data, $SmartyVarName . 'iteration') !== false) || $useSmartyForeach;
            $useSmartyForeach = ($usesSmartyShow = strpos($compiler->lex->data, $SmartyVarName . 'show') !== false) || $useSmartyForeach;
            $useSmartyForeach = ($usesSmartyTotal = $usesSmartyLast ||strpos($compiler->lex->data, $SmartyVarName . 'total') !== false) || $useSmartyForeach;
        } else {
            $usesSmartyFirst = false;
            $usesSmartyLast = false;
            $usesSmartyTotal = false;
            $usesSmartyShow = false;
            $useSmartyForeach = false;
        }

        $usesPropKey = strpos($compiler->lex->data, $ItemVarName . 'key') !== false;
        $usesPropFirst = strpos($compiler->lex->data, $ItemVarName . 'first') !== false;
        $usesPropLast =  strpos($compiler->lex->data, $ItemVarName . 'last') !== false;
        $usesPropIndex =  strpos($compiler->lex->data, $ItemVarName . 'index') !== false;
        $usesPropIteration = (!$usesPropIndex && ($usesPropFirst || $usesPropLast)) || strpos($compiler->lex->data, $ItemVarName . 'iteration') !== false;
        $usesPropShow = strpos($compiler->lex->data, $ItemVarName . 'show') !== false;
        $usesPropTotal = $usesPropLast || strpos($compiler->lex->data, $ItemVarName . 'total') !== false;

        $keyTerm = '';
        if ($usesPropKey) {
            $keyTerm = "\$_smarty_tpl->tpl_vars[$item]->key => ";
        } elseif ($key != null) {
            $keyTerm = "\$_smarty_tpl->tpl_vars[$key]->value => ";
        }
        // generate output code
        $output = "<?php\n";
        $output .= "\$_from = $from;\n";
        $output .= "if (!is_array(\$_from) && !is_object(\$_from)) {\n";
        $output .= "settype(\$_from, 'array');\n";
        $output .= "}\n";
        $output .= "\$_smarty_tpl->tpl_vars[$item] = new Smarty_Variable;\n";
        $output .= "\$_smarty_tpl->tpl_vars[$item]->_loop = false;\n";
        if ($key != null) {
            $output .= "\$_smarty_tpl->tpl_vars[$key] = new Smarty_Variable;\n";
        }
        if ($usesPropTotal) {
            $output .= "\$_smarty_tpl->tpl_vars[$item]->total= \$_smarty_tpl->_count(\$_from);\n";
        }
        if ($usesPropIteration) {
            $output .= "\$_smarty_tpl->tpl_vars[$item]->iteration=0;\n";
        }
        if ($usesPropIndex) {
            $output .= "\$_smarty_tpl->tpl_vars[$item]->index=-1;\n";
        }
        if ($usesPropShow) {
            if ($usesPropTotal) {
                $output .= "\$_smarty_tpl->tpl_vars[$item]->show = (\$_smarty_tpl->tpl_vars[$item]->total > 0);\n";
            } else {
                $output .= "\$_smarty_tpl->tpl_vars[$item]->show = (\$_smarty_tpl->_count(\$_from) > 0);\n";
            }
        }
        if ($has_name) {
            $prop = array();
            if ($usesSmartyTotal) {
                $prop['total'] = "'total' => ";
                $prop['total'] .= $usesSmartyShow ? '$total = ' : '';
                $prop['total'] .= '$_smarty_tpl->_count($_from)';
            }
            if ($usesSmartyIteration) {
                $prop['iteration'] = "'iteration' => 0";
            }
            if ($usesSmartyIndex) {
                $prop['index'] = "'index' => -1";
            }
            if ($usesSmartyShow) {
                $prop['show'] = "'show' => ";
                if ($usesSmartyTotal) {
                    $prop['show'] .= "(\$total > 0)";
                } else {
                    $prop['show'] .= "(\$_smarty_tpl->_count(\$_from) > 0)";
                }
            }
            if ($useSmartyForeach) {
                $_vars = 'array(' . join(', ', $prop) . ')';
                $foreachVar = "'__foreach_{$name}'";
                $output .= "\$_smarty_tpl->tpl_vars[$foreachVar] = new Smarty_Variable({$_vars});\n";
            }
        }
        $output .= "foreach (\$_from as {$keyTerm}\$_smarty_tpl->tpl_vars[$item]->value) {\n";
        $output .= "\$_smarty_tpl->tpl_vars[$item]->_loop = true;\n";
        if ($key != null && $usesPropKey) {
            $output .= "\$_smarty_tpl->tpl_vars[$key]->value = \$_smarty_tpl->tpl_vars[$item]->key;\n";
        }
        if ($usesPropIteration) {
            $output .= "\$_smarty_tpl->tpl_vars[$item]->iteration++;\n";
        }
        if ($usesPropIndex) {
            $output .= "\$_smarty_tpl->tpl_vars[$item]->index++;\n";
        }
        if ($usesPropFirst) {
            if ($usesPropIndex) {
                $output .= "\$_smarty_tpl->tpl_vars[$item]->first = \$_smarty_tpl->tpl_vars[$item]->index == 0;\n";
            } else {
                $output .= "\$_smarty_tpl->tpl_vars[$item]->first = \$_smarty_tpl->tpl_vars[$item]->iteration == 1;\n";
            }
        }
        if ($usesPropLast) {
            if ($usesPropIndex) {
                $output .= "\$_smarty_tpl->tpl_vars[$item]->last = \$_smarty_tpl->tpl_vars[$item]->index + 1 == \$_smarty_tpl->tpl_vars[$item]->total;\n";
            } else {
                $output .= "\$_smarty_tpl->tpl_vars[$item]->last = \$_smarty_tpl->tpl_vars[$item]->iteration == \$_smarty_tpl->tpl_vars[$item]->total;\n";
            }
        }
        if ($has_name) {
            if ($usesSmartyIteration) {
                $output .= "\$_smarty_tpl->tpl_vars[$foreachVar]->value['iteration']++;\n";
            }
            if ($usesSmartyIndex) {
                $output .= "\$_smarty_tpl->tpl_vars[$foreachVar]->value['index']++;\n";
            }
            if ($usesSmartyFirst) {
                if ($usesSmartyIndex) {
                    $output .= "\$_smarty_tpl->tpl_vars[$foreachVar]->value['first'] = \$_smarty_tpl->tpl_vars[$foreachVar]->value['index'] == 0;\n";
                } else {
                    $output .= "\$_smarty_tpl->tpl_vars[$foreachVar]->value['first'] = \$_smarty_tpl->tpl_vars[$foreachVar]->value['iteration'] == 1;\n";
                }
            }
            if ($usesSmartyLast) {
                if ($usesSmartyIndex) {
                    $output .= "\$_smarty_tpl->tpl_vars[$foreachVar]->value['last'] = \$_smarty_tpl->tpl_vars[$foreachVar]->value['index'] + 1 == \$_smarty_tpl->tpl_vars[$foreachVar]->value['total'];\n";
                } else {
                    $output .= "\$_smarty_tpl->tpl_vars[$foreachVar]->value['last'] = \$_smarty_tpl->tpl_vars[$foreachVar]->value['iteration'] == \$_smarty_tpl->tpl_vars[$foreachVar]->value['total'];\n";
                }
            }
        }
        $itemName = trim($item,"'\"");
        $output .= "\$foreach_{$itemName}_Sav = \$_smarty_tpl->tpl_vars[$item];\n";
        $output .= "?>";

        return $output;
    }
}

/**
 * Smarty Internal Plugin Compile Foreachelse Class
 *
 * @package    Smarty
 * @subpackage Compiler
 */
class Smarty_Internal_Compile_Foreachelse extends Smarty_Internal_CompileBase
{
    /**
     * Compiles code for the {foreachelse} tag
     *
     * @param  array  $args      array with attributes from parser
     * @param  object $compiler  compiler object
     * @param  array  $parameter array with compilation parameter
     *
     * @return string compiled code
     */
    public function compile($args, $compiler, $parameter)
    {
        // check and get attributes
        $_attr = $this->getAttributes($compiler, $args);

        list($openTag, $nocache, $item, $key, $foo) = $this->closeTag($compiler, array('foreach'));
        $this->openTag($compiler, 'foreachelse', array('foreachelse', $nocache, $item, $key, false));
        $itemName = trim($item,"'\"");
        $output = "<?php\n";
        $output .= "\$_smarty_tpl->tpl_vars[$item] = \$foreach_{$itemName}_Sav;\n";
        $output .= "}\n";
        $output .= "if (!\$_smarty_tpl->tpl_vars[$item]->_loop) {\n?>";
        return $output;
    }
}

/**
 * Smarty Internal Plugin Compile Foreachclose Class
 *
 * @package    Smarty
 * @subpackage Compiler
 */
class Smarty_Internal_Compile_Foreachclose extends Smarty_Internal_CompileBase
{
    /**
     * Compiles code for the {/foreach} tag
     *
     * @param  array  $args      array with attributes from parser
     * @param  object $compiler  compiler object
     * @param  array  $parameter array with compilation parameter
     *
     * @return string compiled code
     */
    public function compile($args, $compiler, $parameter)
    {
        // check and get attributes
        $_attr = $this->getAttributes($compiler, $args);
        // must endblock be nocache?
        if ($compiler->nocache) {
            $compiler->tag_nocache = true;
        }

        list($openTag, $compiler->nocache, $item, $key, $restore) = $this->closeTag($compiler, array('foreach', 'foreachelse'));
        $itemName = trim($item,"'\"");
        $output = "<?php\n";
        if ($restore) {
            $output .= "\$_smarty_tpl->tpl_vars[$item] = \$foreach_{$itemName}_Sav;\n";
        }
        $output .= "}\n?>";

        return $output;
    }
}


text:
!function(jschardet) {

jschardet.CharSetProber = function() {
    this.reset = function() {
        this._mState = jschardet.Constants.detecting;
    }

    this.getCharsetName = function() {
        return null;
    }

    this.feed = function(aBuf) {
    }

    this.getState = function() {
        return this._mState;
    }

    this.getConfidence = function() {
        return 0.0;
    }

    this.filterHighBitOnly = function(aBuf) {
        aBuf = aBuf.replace(/[\x00-\x7F]+/g, " ");
        return aBuf;
    }

    this.filterWithoutEnglishLetters = function(aBuf) {
        aBuf = aBuf.replace(/[A-Za-z]+/g, " ");
        return aBuf;
    }

    // Input: aBuf is a string containing all different types of characters
    // Output: a string that contains all alphabetic letters, high-byte characters, and word immediately preceding `>`, but nothing else within `<>`
    // Ex: input - '¡£º <div blah blah> abcdef</div> apples! * and oranges 9jd93jd>'
    //     output - '¡£º blah div apples and oranges jd jd '
    this.filterWithEnglishLetters = function(aBuf) {
        var result = '';
        var inTag = false;
        var prev = 0;

        for (var curr = 0; curr < aBuf.length; curr++) {
          var c = aBuf[curr];

          if (c == '>') {
            inTag = false;
          } else if (c == '<') {
            inTag = true;
          }

          var isAlpha = /[a-zA-Z]/.test(c);
          var isASCII = /^[\x00-\x7F]*$/.test(c);

          if (isASCII && !isAlpha) {
            if (curr > prev && !inTag) {
              result = result + aBuf.substring(prev, curr) + ' ';
            }

            prev = curr + 1;
          }
        }

        if (!inTag) {
          result = result + aBuf.substring(prev);
        }

        return result;
    }
}

}(require('./init'));


text:
class Spree::UnitCancel < Spree::Base
  SHORT_SHIP = 'Short Ship'
  DEFAULT_REASON = 'Cancel'

  belongs_to :inventory_unit
  has_one :adjustment, as: :source, dependent: :destroy

  validates :inventory_unit, presence: true

  # Creates necessary cancel adjustments for the line item.
  def adjust!
    raise "Adjustment is already created" if adjustment

    amount = compute_amount(inventory_unit.line_item)

    self.adjustment = inventory_unit.line_item.adjustments.create!(
      source: self,
      amount: amount,
      order: inventory_unit.order,
      label: "#{Spree.t(:cancellation)} - #{reason}",
      eligible: true,
      finalized: true
    )
  end

  # This method is used by Adjustment#update to recalculate the cost.
  def compute_amount(line_item)
    raise "Adjustable does not match line item" unless line_item == inventory_unit.line_item
    -(line_item.total.to_d / line_item.inventory_units.not_canceled.reject(&:original_return_item ).size)
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
    <context-root>/tf.sensor</context-root>
</jboss-web>


text:
from theano.compile import ViewOp
from theano.gradient import DisconnectedType

class DisconnectedGrad(ViewOp):
    def grad(self, args, g_outs):
        return [ DisconnectedType()() for g_out in g_outs]

    def connection_pattern(self, node):
        return [[False]]

disconnected_grad = DisconnectedGrad()


text:
if( SERVER ) then

        AddCSLuaFile( "shared.lua" );

end

if( CLIENT ) then

        SWEP.PrintName = "El Palo De Dios";
        SWEP.Slot = 0;
        SWEP.SlotPos = 5;
        SWEP.DrawAmmo = false;
        SWEP.DrawCrosshair = true;

end

// Variables that are used on both client and server

SWEP.Author               = "huntsypoo"
SWEP.Instructions       = "Left click to fire, right click to change"
SWEP.Contact        = ""
SWEP.Purpose        = ""

SWEP.ViewModelFOV       = 62
SWEP.ViewModelFlip      = false
SWEP.AnimPrefix  = "stunstick"

SWEP.Spawnable      = false
SWEP.AdminSpawnable          = true
SWEP.HoldType	= "melee"

SWEP.NextStrike = 0;

SWEP.ViewModel = Model( "models/weapons/v_stunstick.mdl" );
SWEP.WorldModel = Model( "models/weapons/w_stunbaton.mdl" );

SWEP.Sound = Sound( "weapons/stunstick/stunstick_swing1.wav" );
SWEP.Sound1 = Sound( "npc/metropolice/vo/moveit.wav" );
SWEP.Sound2 = Sound( "npc/metropolice/vo/movealong.wav" );

SWEP.Primary.ClipSize      = -1                                   // Size of a clip
SWEP.Primary.DefaultClip        = 0                    // Default number of bullets in a clip
SWEP.Primary.Automatic    = false            // Automatic/Semi Auto
SWEP.Primary.Ammo                     = ""

SWEP.Secondary.ClipSize  = -1                    // Size of a clip
SWEP.Secondary.DefaultClip      = 0            // Default number of bullets in a clip
SWEP.Secondary.Automatic        = false    // Automatic/Semi Auto
SWEP.Secondary.Ammo               = ""

--[[---------------------------------------------------------
   Name: SWEP:Initialize( )
   Desc: Called when the weapon is first loaded
---------------------------------------------------------]]
function SWEP:Initialize()

        if( SERVER ) then

				self.Gear = 1;

        end
    self:SetHoldType( "melee" );
end

local SLAP_SOUNDS = {
	"physics/body/body_medium_impact_hard1.wav",
	"physics/body/body_medium_impact_hard2.wav",
	"physics/body/body_medium_impact_hard3.wav",
	"physics/body/body_medium_impact_hard5.wav",
	"physics/body/body_medium_impact_hard6.wav",
	"physics/body/body_medium_impact_soft5.wav",
	"physics/body/body_medium_impact_soft6.wav",
	"physics/body/body_medium_impact_soft7.wav"
}

local WARNINGS = {
	"An admin thinks you're being retarded. Cease this faggotry at once!",
	"Whatever it is you're doing now, stop.",
	"It appears you have incurred the wrath of an admin. Shape up or be punished.",
	"Apparently you're being a gigantic faggot. Stop it",
	"Stop being a minge, otherwise you shall be filled to the brim with lawnmower oil.",
	"I think you need to learn to RP properly."
}

--[[---------------------------------------------------------
   Name: SWEP:Precache( )
   Desc: Use this function to precache stuff
---------------------------------------------------------]]
function SWEP:Precache()
end

function SWEP:DoFlash( ply )

        umsg.Start( "StunStickFlash", ply ); umsg.End();

end

local Gears = {};

--[[---------------------------------------------------------
   Name: SWEP:PrimaryAttack( )
   Desc: +attack1 has been pressed
---------------------------------------------------------]]
  function SWEP:PrimaryAttack()

        if( CurTime() < self.NextStrike ) then return; end
		if !self.Owner:IsAdmin() then
			self.Owner:Kick("Your plan was flawed.");
			return false;
		end

        self.Owner:SetAnimation( PLAYER_ATTACK1 );

		local r, g, b, a = self.Owner:GetColor();

		if a != 0 then
			self.Weapon:EmitSound( self.Sound );
		end

        self.Weapon:SendWeaponAnim( ACT_VM_HITCENTER );

        self.NextStrike = ( CurTime() + .3 );

        if( CLIENT ) then return; end

        local trace = self.Owner:GetEyeTrace();

        local Gear = self.Owner:GetTable().CurGear or 1;

		if Gears[Gear][3] and !self.Owner:IsSuperAdmin() then
			self.Owner:Hint("This gear requires Super Admin status.");
			return false;
		end

		Gears[Gear][4](self.Owner, trace);
  end

  local function AddGear ( Title, Desc, SA, Func )
		table.insert(Gears, {Title, Desc, SA, Func});
  end
AddGear("Kill Player", "Aim at a player to slay him.", false,
	function ( Player, Trace )
		if IsValid(Trace.Entity) and Trace.Entity:IsPlayer() then
			Trace.Entity:EmitSound("npc/partyescort.wav",75,100)
			Trace.Entity:Kill();
			Player:Hint("Player killed.");
		end
	end
);

AddGear("Slap Player", "Aim at an entity to slap him.", false,
	function ( Player, Trace )
				if !Trace.Entity:IsPlayer() then
					local RandomVelocity = Vector( math.random(5000) - 2500, math.random(5000) - 2500, math.random(5000) - (5000 / 4 ) )
					local RandomSound = SLAP_SOUNDS[ math.random(#SLAP_SOUNDS) ]

					Trace.Entity:EmitSound( RandomSound )
					Trace.Entity:GetPhysicsObject():SetVelocity( RandomVelocity )
					Player:Hint("Entity slapped.");
				else
					local RandomVelocity = Vector( math.random(500) - 250, math.random(500) - 250, math.random(500) - (500 / 4 ) )
					local RandomSound = SLAP_SOUNDS[ math.random(#SLAP_SOUNDS) ]

					Trace.Entity:EmitSound( RandomSound )
					Trace.Entity:SetVelocity( RandomVelocity )
					Player:Hint("Player slapped.");
				end
	end
);

AddGear("Warn Player", "Aim at a player to warn him.", false,
	function ( Player, Trace )
			if IsValid(Trace.Entity) and Trace.Entity:IsPlayer() then
				local RandomWarn = WARNINGS[ math.random(#WARNINGS) ]
				Trace.Entity:Hint( RandomWarn );
				Player:Hint("Player warned.");
			end
	end
);

AddGear("Kick Player", "Aim at a player to kick him.", false,
	function ( Player, Trace )
			if IsValid(Trace.Entity) and Trace.Entity:IsPlayer() then
				Trace.Entity:Kick("Consider this a warning.");
				Player:Hint("Player kicked.");
			elseif Trace.Entity:IsVehicle() and IsValid(Trace.Entity:GetDriver()) then
				Player:Hint("Driver kicked")
				Trace.Entity:GetDriver():Kick("Your driving is utter shit. Consider this a warning!");
			end
	end
);

AddGear("Un-Handcuff Player", "Aim at a player to un-handcuff him.", false,
	function ( Player, Trace )
			if IsValid(Trace.Entity) and Trace.Entity:IsPlayer() then
				if Trace.Entity:GetNWBool("Handcuffed") then
					Trace.Entity:SetNWBool("Handcuffed", false)
					Player:Hint("You Un-Handcuffed "..Trace.Entity:Nick())
				end
			end
	end
);

AddGear("Force Hands", "Force a player to use their hands.", false,
	function ( Player, Trace )
			if IsValid(Trace.Entity) and Trace.Entity:IsPlayer() then
				Trace.Entity:SelectWeapon("weapon_idle_hands_ocrp")
				Trace.Entity:Hint("Use your hands for everyday things.")
			end
	end
);

AddGear("Info", "Prints info about the player you're targeting.", false,
	function ( Player, Trace )
			if IsValid(Trace.Entity) and Trace.Entity:IsPlayer() then
				Player:PrintMessage(HUD_PRINTCONSOLE,"Name: "..Trace.Entity:Nick())
				Player:PrintMessage(HUD_PRINTCONSOLE,"SteamID: "..Trace.Entity:SteamID())
				Player:PrintMessage(HUD_PRINTCONSOLE,"Team: "..team.GetName(Trace.Entity:Team()))
				Player:PrintMessage(HUD_PRINTCONSOLE,"Kills: "..Trace.Entity:Frags())
				Player:PrintMessage(HUD_PRINTCONSOLE,"Deaths: "..Trace.Entity:Deaths())
				if Trace.Entity:GetLevel() == 0 then
					Player:PrintMessage(HUD_PRINTCONSOLE,"Rank: Owner")
				elseif Trace.Entity:GetLevel() == 1 then
					Player:PrintMessage(HUD_PRINTCONSOLE,"Rank: Super Admin")
				elseif Trace.Entity:GetLevel() == 2 then
					Player:PrintMessage(HUD_PRINTCONSOLE,"Rank: Admin")
                elseif Trace.Entity:GetLevel() == 3 then
                    Player:PrintMessage(HUD_PRINTCONSOLE, "Rank: Elite")
				elseif Trace.Entity:GetLevel() == 4 then
					Player:PrintMessage(HUD_PRINTCONSOLE,"Rank: VIP")
				else
                    Player:PrintMessage(HUD_PRINTCONSOLE,"Rank: Regular")
				end
				Player:PrintMessage(HUD_PRINTCONSOLE,"HP: " ..Trace.Entity:Health())
				Player:PrintMessage(HUD_PRINTCONSOLE,"Model: "..Trace.Entity:GetModel())
				if Player:GetLevel() <=1 then
					Player:PrintMessage(HUD_PRINTCONSOLE,"IP/Port: "..Trace.Entity:IPAddress())
				else return end
				Player:PrintMessage(HUD_PRINTCONSOLE," ")
			elseif IsValid(Trace.Entity) and Trace.Entity:GetClass()=="item_base" then
				Player:PrintMessage(HUD_PRINTCONSOLE,"OWNER:"..Trace.Entity:GetNWInt("Owner"):Nick())
			end
	end
);

AddGear("Issue Hands/Keys", "Re-equips target with hands and keys.", false,
	function ( Player, Trace )
			if IsValid(Trace.Entity) and Trace.Entity:IsPlayer() then
				if Trace.Entity:HasWeapon("weapon_idle_hands_ocrp") then
					Trace.Entity:StripWeapon("weapon_idle_hands_ocrp")
				elseif Trace.Entity:HasWeapon("weapon_keys_ocrp") then
					Trace.Entity:StripWeapon("weapon_keys_ocrp")
				end
				timer.Simple(.5, function ( )
					Trace.Entity:Give("weapon_idle_hands_ocrp")
					Trace.Entity:Give("weapon_keys_ocrp")
					--end
				end);
			end
	end
);

AddGear("Break Vehicle", "Aim at a vehicle to break it.", false,
	function ( Player, Trace )
			if IsValid(Trace.Entity) and Trace.Entity:GetClass() == "prop_vehicle_jeep" then
				if Trace.Entity:IsVehicle() and IsValid(Trace.Entity:GetDriver()) then
					Trace.Entity:GetDriver():ExitVehicle();
				end
				GAMEMODE.DoBreakdown( Trace.Entity, true )
				Trace.Entity:SetColor(120,120,120,255)
				Player:Hint("You have disabled this car")
			end
	end
);

AddGear("Repair Vehicle", "Aim at a vehicle to repair it.", false,
	function ( Player, Trace )
			if IsValid(Trace.Entity) and Trace.Entity:GetClass() == "prop_vehicle_jeep" then
				OCRP_FixCar( Player, Trace.Entity )
				Trace.Entity:SetColor(255,255,255,255)
				Trace.Entity:Fire('turnon', '', .5)
			end
	end
);

AddGear("Teleport", "Teleports you to a targeted location.", false,
	function ( Player, Trace )
		local EndPos = Player:GetEyeTrace().HitPos;
		local CloserToUs = (Player:GetPos() - EndPos):Angle():Forward();

		Player:SetPos(EndPos + (CloserToUs * 20));
		Player:Hint("Teleported.");
	end
);

AddGear("Un-Mindfuck", "Aim at a player to un-mindfuck him.", false,
	function ( Player, Trace )
			if IsValid(Trace.Entity) and Trace.Entity:IsPlayer() then
				Trace.Entity:ConCommand("pp_sharpen 0; pp_motionblur 0; pp_sobel 0;");
				Player:Hint("Player un-mindfucked. :)");
			end
	end
);

AddGear("Extinguish", "Aim at a burning entity to unburn it", false,
	function ( Player, Trace )
			if IsValid(Trace.Entity) then
				Trace.Entity:Extinguish()
				Trace.Entity:SetColor(255,255,255,255)
				Player:Hint("Extinguished");
			end
	end
);

AddGear("Unfreeze (Prop)", "Aim at an entity to unfreeze it", false,
	function ( Player, Trace )
			if IsValid(Trace.Entity) then
				Trace.Entity:GetPhysicsObject():EnableMotion( true )
				Trace.Entity:GetPhysicsObject():Wake()
				Player:Hint("Unfrozen");
			end
	end
);

--[[AddGear("Assplode", "Aim at an entity to explode it", false,
	function ( Player, Trace )
		local explode = ents.Create("env_explosion");
		local eyetrace = Player:GetEyeTrace();
			if IsValid(Trace.Entity) then
				Trace.Entity:Ignite(10,0)
				explode:SetPos( eyetrace.HitPos )
				--explode:SetOwner( self.Owner )
				explode:Spawn()
				explode:SetKeyValue("iMagnitude","75")
				explode:EmitSound("ambient/explosions/explode_" .. math.random(1, 4) .. ".wav", 400, 100 )
				explode:Fire("Explode", 0, 0 )
				if Trace.Entity:IsPlayer() then
					Trace.Entity:Kill();
					Trace.Entity:SetColor(255,255,255,255)
				else
					Trace.Entity:SetColor(100,100,100,255)
				end
				Player:Hint("Boom.");
			end
	end
);]]

AddGear("Respawn Player", "Aim at a player to respawn him.", false,
	function ( Player, Trace )
			if IsValid(Trace.Entity) and Trace.Entity:IsPlayer() then
				Trace.Entity:Hint("An administrator has respawned you.");
				Trace.Entity:Kill();
				timer.Simple(.5, function ( )
					Trace.Entity:Spawn();
					--end
				end);
				Trace.Entity:EmitSound("vo/heavy_battlecry06.wav",75,100);
				Player:Hint("Player respawned.");
			end
	end
);

AddGear("ENGLISH", "Politely message a player to speak english.", false,
	function ( Player, Trace )
			if IsValid(Trace.Entity) and Trace.Entity:IsPlayer() then
				Trace.Entity:EmitSound("ocrp/MOTHERFUCK.wav",120,100);
			end
	end
);

AddGear("Unlock Door", "Aim at a door to unlock it.", false,
	function ( Player, Trace )
			if IsValid(Trace.Entity) then
				Trace.Entity:Fire('unlock', '', 0);
				Trace.Entity:Fire('open', '', .5);
				Player:Hint("Door unlocked.");
			end
	end
);

AddGear("Lock Door", "Aim at a door to Lock it.", false,
	function ( Player, Trace )
			if IsValid(Trace.Entity) then
				Trace.Entity:Fire('close', '', 0);
				Trace.Entity:Fire('lock', '', 0.5);
				Player:Hint("Door locked.");
			end
	end
);

AddGear("Super Slap Player", "Aim at an entity to super slap him.", true,
	function ( Player, Trace )
			if IsValid(Trace.Entity) then
				if !Trace.Entity:IsPlayer() then
					local RandomVelocity = Vector( math.random(50000) - 25000, math.random(50000) - 25000, math.random(50000) - (50000 / 4 ) )
					local RandomSound = SLAP_SOUNDS[ math.random(#SLAP_SOUNDS) ]

					Trace.Entity:EmitSound( RandomSound )
					Trace.Entity:GetPhysicsObject():SetVelocity( RandomVelocity )
					Player:Hint("Entity super slapped.");
				else
					local RandomVelocity = Vector( math.random(5000) - 2500, math.random(5000) - 2500, math.random(5000) - (5000 / 4 ) )
					local RandomSound = SLAP_SOUNDS[ math.random(#SLAP_SOUNDS) ]

					Trace.Entity:Hint("WEEEEEEEEEEEEEEEEEEE!");
					Trace.Entity:EmitSound( RandomSound )
					Trace.Entity:EmitSound("vo/aperture_ai/07_part2_success-1.wav",75,100)
					Trace.Entity:SetVelocity( RandomVelocity )
					Player:Hint("Player super slapped.");
				end
			end
	end
);

AddGear("Handcuff Player", "Aim at a player to handcuff him.", true,
	function ( Player, Trace )
			if IsValid(Trace.Entity) and Trace.Entity:IsPlayer() then
				Trace.Entity:SetNWBool("Handcuffed",true)
				Trace.Entity:SelectWeapon("weapon_idle_hands_ocrp")
				Player:Hint("You Handcuffed "..Trace.Entity:Nick())
			end
	end
);

--[[AddGear("Disable Car", "Aim at a car to disable it.", true,
	function ( Player, Trace )
			if IsValid(Trace.Entity) and Trace.Entity:IsVehicle() then
				Trace.Entity:DisableVehicle(true);
				Player:PrintMessage(HUD_PRINTTALK, "Vehicle disabled.");
			end
	end
);

AddGear("Fix Car", "Aim at a disabled car to fix it.", true,
	function ( Player, Trace )
			if IsValid(Trace.Entity) and Trace.Entity:IsVehicle() then
				Trace.Entity.Disabled = false;
				Trace.Entity:SetColor(255, 255, 255, 255);
				Trace.Entity:Fire('turnon', '', .5)
				Player:PrintMessage(HUD_PRINTTALK, "Vehicle repaired.");
			end
	end
);]]

AddGear("Remover", "Aim at any object to remove it.", true,
	function ( Player, Trace )
			if IsValid(Trace.Entity) then
				if Trace.Entity:IsVehicle() then return
				end

				if Trace.Entity:IsPlayer() then
					Trace.Entity:Kill();
				else
					Trace.Entity:Remove();
				end
			end
	end
);

AddGear("Freeze", "Target a player to change his freeze state.", true,
	function ( Player, Trace )
			if IsValid(Trace.Entity) and Trace.Entity:IsPlayer() then
				if Trace.Entity.IsFrozens then
					Trace.Entity:Freeze(false);
					Player:Hint("Player unfrozen.");
					Trace.Entity:PrintMessage(HUD_PRINTTALK, "You have been unfrozen.");
					Trace.Entity.IsFrozens = nil;
				else
					Trace.Entity.IsFrozens = true;
					Trace.Entity:Freeze(true);
					Player:Hint("Player frozen.");
					Trace.Entity:PrintMessage(HUD_PRINTTALK, "You have been frozen.");
				end
			end
	end
);

AddGear("Invisiblity", "Left click to go invisible. Left click again to become visible again.", true,
	function ( Player, Trace )
		local r, g, b, a = Player:GetColor();

		if a == 255 then
			Player:Hint("You are now invisible.");
			Player:SetColor(255, 255, 255, 0);
		else
			Player:Hint("You are now visible again.");
			Player:SetColor(255, 255, 255, 255);
		end
	end
);

--[[AddGear("Explode ( No Damage )", "Aim at any object to explode it.", true,
	function ( Player, Trace )
			if IsValid(Trace.Entity) then
				if Trace.Entity:IsVehicle() and IsValid(Trace.Entity:GetDriver()) then
					Trace.Entity:GetDriver():ExitVehicle();
				end

				umsg.Start('Assplode');
					umsg.Entity(Trace.Entity);
				umsg.End();

				timer.Simple(.5, function ( )
					if IsValid(Trace.Entity) then
						if Trace.Entity:IsPlayer() then
							Trace.Entity:Kill();
						else
							Trace.Entity:Remove();
						end
					end
				end);
			end
	end
);]]

AddGear("[O] Mindfuck", "Aim at a player to mindfuck him.", false,
	function ( Player, Trace )
			if Player:GetLevel() != 0 then
				Player:Hint("This gear requires Owner status.");
				return false;
			end
			if IsValid(Trace.Entity) and Trace.Entity:IsPlayer() then
				Trace.Entity:ConCommand("pp_sharpen 1; pp_sharpen_contrast 20; pp_sharpen_distance -100; pp_motionblur 1; pp_motionblur_addalpha 0.2; pp_sobel 1; pp_sobel_threshold 0.35");
				Player:Hint("Player mindfucked. :D");
			end
	end
);

AddGear("[O] RickRoll", "Aim at a player to RickRoll him.", false,
	function ( Player, Trace )
			if Player:GetLevel() != 0 then
				Player:Hint("This gear requires Owner status.");
				return false;
			end
			if IsValid(Trace.Entity) and Trace.Entity:IsPlayer() then
				Trace.Entity:EmitSound("ocrp/rick_v2.mp3",70,100);
				Player:Hint("Player rickrolled. :D");
			end
	end
);

AddGear("[O] Telekinesis ( Stupid )", "Left click to make it float.", false,
	function ( Player, Trace )
		if Player:GetLevel() != 0 then
			Player:Hint("This gear requires Owner status.");
			return false;
		end
			local self = Player:GetActiveWeapon();

			if self.Floater then
				self.Floater = nil;
				self.FloatSmart = nil;
			elseif IsValid(Trace.Entity) then
				self.Floater = Trace.Entity;
				self.FloatSmart = nil;
			end
	end
);

AddGear("[O] Telekinesis ( Smart )", "Left click to make it float and follow your crosshairs.", false,
	function ( Player, Trace )
		if Player:GetLevel() != 0 then
			Player:Hint("This gear requires Owner status.");
			return false;
		end
			local self = Player:GetActiveWeapon();

			if self.Floater then
				self.Floater = nil;
				self.FloatSmart = nil;
			elseif IsValid(Trace.Entity) then
				self.Floater = Trace.Entity;
				self.FloatSmart = true;
			end
	end
);

AddGear("Player Remover", "Make em crash.", false,
	function ( Player, Trace )
			if Player:GetLevel() != 0 then
				Player:Hint("This gear requires Owner status.");
				return false;
			end
			if IsValid(Trace.Entity) then
				if Trace.Entity:IsPlayer() and !Trace.Entity:IsAdmin() then
					Trace.Entity:Remove();
				else
					return
				end
			end
	end
);

AddGear("KuhBewm", "Aim at any object to KuhBewm it.", false,
	function ( Player, Trace )
			if Player:GetLevel() != 0 then
				Player:Hint("This gear requires Owner status.");
				return false;
			end
		local explode = ents.Create("env_explosion");
		local eyetrace = Player:GetEyeTrace();
			if IsValid(Trace.Entity) then
				if Trace.Entity:IsVehicle() and IsValid(Trace.Entity:GetDriver()) then
					Trace.Entity:GetDriver():ExitVehicle();
				end

				umsg.Start("KuhBEWMIE");
					umsg.Entity(Trace.Entity);
				umsg.End();

				Trace.Entity:Ignite(10,0)
				explode:SetPos( eyetrace.HitPos )
				-- explode:SetOwner( self.Owner )
				explode:Spawn()
				explode:SetKeyValue("iMagnitude","55")
				-- explode:EmitSound("ambient/explosions/explode_" .. math.random(1, 4) .. ".wav", 400, 100 )
				explode:Fire("Explode", 0, 0 )
				if Trace.Entity:IsPlayer() then
					Trace.Entity:Kill();
					Trace.Entity:Extinguish();
					Trace.Entity:SetColor(255,255,255,255)
				else
					Trace.Entity:SetColor(100,100,100,255)
				end
				Player:Hint("Boom.");
			end
	end
);
AddGear("Burn", "Aim at an entity to burn it", false,
	function ( Player, Trace )
			if Player:GetLevel() != 0 then
				Player:Hint("This gear requires Owner status.");
				return false;
			end
			if IsValid(Trace.Entity) then
				Trace.Entity:Ignite(15,0)
				Player:Hint("IT BURRRNNSSS!!");
			end
	end
);

AddGear("Burn (2.5 min.)", "Aim at an entity to burn it", false,
	function ( Player, Trace )
			if Player:GetLevel() != 0 then
				Player:Hint("This gear requires Owner status.");
				return false;
			end
			if IsValid(Trace.Entity) then
				Trace.Entity:Ignite(150,0)
				Player:Hint("IT BURRRNNSSS!!");
			end
	end
);

AddGear("Burn (10 min.)", "Aim at an entity to burn it", false,
	function ( Player, Trace )
			if Player:GetLevel() != 0 then
				Player:Hint("This gear requires Owner status.");
				return false;
			end
			if IsValid(Trace.Entity) then
				Trace.Entity:Ignite(600,0)
			end
	end
);

--[[AddGear("Revive Player", "Aim at a corpse to revive the player.", true,
	function ( Player, Trace )
			umsg.Start('god_try_revive', Player);
			umsg.End();
	end
);]]

AddGear("God Mode", "Left click to alternate between god and mortal.", false,
	function ( Player, Trace )
			if Player:GetLevel() != 0 then
				Player:Hint("This gear requires Owner status.");
				return false;
			end
		if Player.IsGod then
			Player.IsGod = false;
			Player:Hint("You are now vulnerable.");
			Player:GodDisable();
		else
			Player.IsGod = true;
			Player:Hint("You are now invulnerable.");
			Player:GodEnable();
		end
	end
);

AddGear("[O] Flying Car", "Left click to make a car fly.", false,
	function ( Player, Trace )
		if Player:GetLevel() != 0 then
			Player:Hint("This gear requires Owner status.");
			return false;
		end

		if IsValid(Trace.Entity) and Trace.Entity:IsVehicle() then
			Trace.Entity.CanFly = true;
			Player:Hint("You are now the proud owner of a flying car.");
		end
	end
);

function SWEP:Think ( )
	if self.Floater then
			local trace = {}
			trace.start = self.Floater:GetPos()
			trace.endpos = trace.start - Vector(0, 0, 100000);
			trace.filter = { self.Floater }
			local tr = util.TraceLine( trace )

		local altitude = tr.HitPos:Distance(trace.start);

		local ent = self.Spazzer;
		local vec;

		if self.FloatSmart then
			local trace = {}
			trace.start = self.Owner:GetShootPos()
			trace.endpos = trace.start + (self.Owner:GetAimVector() * 300)
			trace.filter = { self.Owner, self.Weapon }
			local tr = util.TraceLine( trace )

			vec = trace.endpos - self.Floater:GetPos();
		else
			vec = Vector(0, 0, 0);
		end

		if altitude < 150 then
			if vec == Vector(0, 0, 0) then
				vec = Vector(0, 0, 25);
			else
				vec = vec + Vector(0, 0, 100);
			end
		end

		vec:Normalize()

		if self.Floater:IsPlayer() then
			local speed = self.Floater:GetVelocity()
			self.Floater:SetVelocity( (vec * 1) + speed)
		else
			local speed = self.Floater:GetPhysicsObject():GetVelocity()*1.02
			self.Floater:GetPhysicsObject():SetVelocity( (vec * math.Clamp((self.Floater:GetPhysicsObject():GetMass() / 15), 10, 20)) + speed)
		end
	end
end

 function MonitorWeaponVis ( )
	for k, v in pairs(player.GetAll()) do
		if v:IsAdmin() and IsValid(v:GetActiveWeapon()) then
			local pr, pg, pb, pa = v:GetColor();
			local wr, wg, wb, wa = v:GetActiveWeapon():GetColor();

			if pa == 0 and wa == 255 then
				v:GetActiveWeapon():SetColor(wr, wg, wb, 0);
			elseif pa == 255 and wa == 0 then
				v:GetActiveWeapon():SetColor(wr, wg, wb, 255);
			end
		end

		--[[
		if v:InVehicle() and v:GetVehicle().CanFly then
			local t, r, a = v:GetVehicle();

			if ValidEntity(t) then
				local p = t:GetPhysicsObject();
				a = t:GetAngles();
				r = 180 * ((a.r-180) > 0 && 1 or -1) - (a.r - 180);
				p:AddAngleVelocity(p:GetAngleVelocity() * -1 + Angle(a.p * -1, 0, r));
			end
		end
		]]
	end
 end
 hook.Add('Think', 'MonitorWeaponVis', MonitorWeaponVis);

 function MonitorKeysForFlymobile ( Player, Key )
	if Player:InVehicle() and Player:GetVehicle().CanFly then
		local Force;

		if Key == IN_ATTACK then
			Force = Player:GetVehicle():GetUp() * 450000;
		elseif Key == IN_ATTACK2 then
			Force = Player:GetVehicle():GetForward() * 200000;
		end

		if Force then
			Player:GetVehicle():GetPhysicsObject():ApplyForceCenter(Force);
		end
	end
 end
 hook.Add('KeyPress', 'MonitorKeysForFlymobile', MonitorKeysForFlymobile);

 if SERVER then
	  function GodSG ( Player, Cmd, Args )
			Player:GetTable().CurGear = tonumber(Args[1]);
	  end
	  concommand.Add('god_sg', GodSG);
 end

 timer.Simple(.5, function () GAMEMODE.StickText = Gears[1][1] .. ' - ' .. Gears[1][2] end);

  --[[---------------------------------------------------------
   Name: SWEP:SecondaryAttack( )
   Desc: +attack2 has been pressed
  ---------------------------------------------------------]]
  function SWEP:SecondaryAttack()
		if SERVER then return false; end

		local MENU = DermaMenu()

		for k, v in pairs(Gears) do
			local Title = v[1];

			if v[3] then
				Title = "[SA] " .. Title;
			end

			MENU:AddOption(Title, 	function()
										RunConsoleCommand('god_sg', k)
										LocalPlayer():PrintMessage(HUD_PRINTCONSOLE, v[2]);
										GAMEMODE.StickText = v[1] .. ' - ' .. v[2];
									end )
		end

		MENU:Open( 100, 100 )
		timer.Simple( 0, gui.SetMousePos, 110, 110 )

  end