text:
from myuw_selenium.test.myuw import link

# Dictionary of resource links.
resLinks = {
    'seattle': {
        'academics' : {
            'Registration' : [
                link('Academic Calendar', 'http://www.washington.edu/students/reg/calendar.html'),
                link('Course Catalog', 'http://www.washington.edu/students/crscat/'),
                link('Degree Audit Reporting System (DARS)', 'https://sdb.admin.washington.edu/students/uwnetid/dars.asp'),
                link('MyPlan', 'https://uwstudent.washington.edu/student/myplan'),
                link('Registration', 'https://sdb.admin.washington.edu/students/uwnetid/register.asp'),
                link('Schedule Finder', 'https://sdb.admin.washington.edu/timeschd/uwnetid/findschd.asp'),
                link('UW Seattle Time Schedule', 'http://www.washington.edu/students/timeschd/')
            ],
            'Advising & Tutoring' : [
                link('Career Center', 'http://careers.washington.edu/'),
                link('Center for Learning and Undergraduate Enrichment (CLUE)', 'http://depts.washington.edu/aspuw/clue/home/'),
                link('International Student Services (ISS)', 'http://iss.washington.edu/'),
                link('Odegaard Writing & Research Center', 'http://depts.washington.edu/owrc'),
                link('Undergraduate Academic Advising (Pre-major)', 'http://www.washington.edu/uaa/advising/'),
                link('Study Abroad', 'http://studyabroad.washington.edu/'),
            ],
            'Grades & Transcripts' : [
                link('GPA Calculator', 'http://www.washington.edu/uaa/advising/general-education-requirements/gpa-calculator/'),
                link('Grade Report', 'https://sdb.admin.washington.edu/students/uwnetid/grades.asp'),
                link('Order Official Transcripts', 'https://sdb.admin.washington.edu/students/uwnetid/official.asp'),
                link('Unofficial Transcript', 'https://sdb.admin.washington.edu/students/uwnetid/unofficial.asp')
            ],
            'Libraries' : [
                link('Electronic Course Reserves', 'https://eres.lib.washington.edu/'),
                link('UW Libraries', 'http://lib.washington.edu/')
            ],
            'Graduation' : [
                link('Application for Graduation', 'http://www.washington.edu/students/reg/grad.html')
            ]
        },
        'finances' : {
            'Financial Aid' : [
                link('Financial Aid and Scholarships', 'http://www.washington.edu/students/osfa/'),
                link('Financial Aid Status', 'https://sdb.admin.washington.edu/students/uwnetid/finaidstatus.asp')
            ],
            'Taxes' : [
                link('Form 1098-T', 'https://sdb.admin.washington.edu/sisStudents/uwnetid/irs1098tconsent.aspx'),
                link('Student Tax Information', 'http://f2.washington.edu/fm/sfs/tax')
            ],
            'Tuition' : [
                link('Tuition Overview', 'http://f2.washington.edu/fm/sfs/tuition')
            ]
        },
        'studentcampuslife' : {
            'Housing & Dining' : [
                link('Add Funds to Husky Card', 'https://www.hfs.washington.edu/olco/Secure/AccountSummary.aspx'),
                link('Campus Dining', 'https://www.hfs.washington.edu/dining/'),
                link('Check HFS Balance', 'https://www.hfs.washington.edu/myhfs/ledger.aspx'),
                link('Student Housing', 'https://www.hfs.washington.edu/housing/')
            ],
            'Health & Wellness' : [
                link('Counseling Center', 'http://www.washington.edu/counseling/'),
                link('Hall Health Center', 'http://depts.washington.edu/hhpccweb/'),
                link('Recreational Sports Programs (IMA)', 'http://depts.washington.edu/ima/'),
                link('Student Health Insurance', 'http://www.washington.edu/ship/')
            ],
            'Support Services' : [
                link('Disability Resources', 'http://www.washington.edu/admin/dso/uw-resources.html'),
                link('Diversity Resources', 'http://www.washington.edu/omad/'),
                link('New Student Orientation', 'http://fyp.washington.edu/getting-started-at-the-university-of-washington/'),
                link('Q Center', 'http://depts.washington.edu/qcenter/wordpress/'),
                link("Women's Center", 'http://depts.washington.edu/womenctr/'),
                link('SafeCampus', 'http://www.washington.edu/safecampus/'),
                link('Sexual Assault & Relationship Violence Information Service (SARIS)', 'http://www.washington.edu/students/saris/'),
                link('Student Legal Services', 'http://depts.washington.edu/slsuw/')
            ],
            'Campus Retail' : [
                link('HUB', 'http://hub.washington.edu/'),
                link('University Book Store', 'http://www.bookstore.washington.edu/student_faculty/student_faculty.taf?verba=uwseattle')
            ],
            'Transportation' : [
                link('Accessibility Guide', 'http://www.washington.edu/admin/ada/newada.php'),
                link('Campus Map', 'http://www.washington.edu/maps/'),
                link('Getting to Seattle Campus', 'http://www.washington.edu/facilities/transportation/commuterservices/')
            ],
            'Rules & Regulations' : [
                link('Family Educational Rights and Privacy Act (FERPA) - Privacy of Student Information', 'http://www.washington.edu/students/reg/ferpa.html'),
                link('Office of Scholarly Integrity (OSI)', 'https://ap.washington.edu/osi/'),
                link('Student Conduct Code', 'http://www.washington.edu/cssc/student-conduct-overview/student-code-of-conduct/')
            ],
        },
        'eventsactivities' : {
            'Events' : [
                link('Campus Event Calendar', 'http://www.washington.edu/calendar/'),
                link('HUB Events', 'http://depts.washington.edu/thehub/hub-events/today-in-the-hub/')
            ],
            'Student Clubs & Organizations' : [
                link('Registered Student Organizations (RSO) Directory', 'https://uws-community.symplicity.com/index.php?s=student_group')
            ],
            'Stay Connected' : [
                link('Campus News', 'http://www.washington.edu/news/'),
                link('UW Facebook Page', 'http://www.facebook.com/UofWA'),
                link('UW YouTube Channel', 'http://www.youtube.com/user/uwhuskies'),
                link('UW Instagram', 'http://instagram.com/uofwa'),
                link('UW Twitter', 'http://twitter.com/UW'),
                link('UW LinkedIn', 'http://www.linkedin.com/company/university-of-washington'),
            ]
        },
        'toolssoftware' : {
            'Teaching & Learning Tools' : [
                link('Canvas LMS', 'http://canvas.uw.edu/'),
                link('Catalyst Web Tools', 'https://catalyst.uw.edu/'),
                link('Notify.UW', 'https://notify.uw.edu/'),
                link('Panopto', 'https://panopto.uw.edu/'),
                link('SpaceScout Study Space Finder', 'http://spacescout.uw.edu/seattle'),
                link('Tableau Data Analysis Software', 'http://www.washington.edu/itconnect/wares/uware/tableau-software/'),
                link('Tegrity', 'https://uw.tegrity.com/'),
            ],
            'Email & UW NetID' : [
                link('Alpine Mail', 'http://alpine.washington.edu/'),
                link('Email Forwarding', 'https://uwnetid.washington.edu/manage/?forward'),
                link('Gmail', 'https://mail.google.com/a/uw.edu'),
                link('Manage UW NetID Account', 'https://uwnetid.washington.edu/manage/')
            ],
            'Directory' : [
                link('UW Directory', 'http://www.washington.edu/home/directories.html')
            ]
        },
        'employment' : {
            '' : [
                link('Career Center', 'http://careers.washington.edu/'),
                link('Employee Self-Service (ESS)', 'https://www.washington.edu/ess/'),
                link('Husky Jobs', 'https://washington-csm.symplicity.com/students/index.php'),
                link('Student Employment in the Libraries', 'http://www.lib.washington.edu/about/employment/students')
            ]
        }
    },
    'bothell' : {
        'academics' : {
            'Registration' : [
                link('Bothell Academic Calendar', 'http://www.uwb.edu/calendars'),
                link('Course Catalog', 'http://www.washington.edu/students/crscatb/'),
                link('Degree Audit Reporting System (DARS)', 'https://sdb.admin.washington.edu/students/uwnetid/dars.asp'),
                link('MyPlan', 'https://uwstudent.washington.edu/student/myplan'),
                link('Registration', 'https://sdb.admin.washington.edu/students/uwnetid/register.asp'),
                link('Schedule Finder', 'https://sdb.admin.washington.edu/timeschd/uwnetid/findschd.asp'),
                link('UW Bothell Time Schedule', 'http://www.uwb.edu/registration/time')
            ],
            'Advising & Tutoring' : [
                link('Career Services', 'http://www.bothell.washington.edu/careers'),
                link('International Student Services (ISS)', 'http://www.uwb.edu/iss'),
                link('Study Abroad', 'http://www.uwb.edu/globalinitiatives/abroad'),
                link('Undergraduate Academic Advising (Pre-major)', 'http://www.uwb.edu/cusp/advising'),
                link('Writing and Communication Center (WaCC)', 'http://www.uwb.edu/wacc'),
            ],
            'Grades & Transcripts' : [
                link('Bothell Faculty and Staff Directory', 'http://www.uwb.edu/directory'),
                link('GPA Calculator', 'http://www.washington.edu/uaa/advising/general-education-requirements/gpa-calculator/'),
                link('Grade Report', 'https://sdb.admin.washington.edu/students/uwnetid/grades.asp'),
                link('Unofficial Transcript', 'https://sdb.admin.washington.edu/students/uwnetid/unofficial.asp')
            ],
            'Libraries' : [
                link('Electronic Course Reserves', 'https://eres.bothell.washington.edu/'),
                link('UW Bothell Library', 'http://library.uwb.edu/')
            ],
            'Graduation' : [
                link('Applying for Graduation', 'https://www.uwb.edu/registration/graduation/apply')
            ],
        },
        'finances' : {
            'Financial Aid' : [
                link('Financial Aid and Scholarships', 'http://www.bothell.washington.edu/financialaid'),
                link('Financial Aid Status', 'https://sdb.admin.washington.edu/students/uwnetid/finaidstatus.asp')
            ],
            'Taxes' : [
                link('Form 1098-T', 'https://sdb.admin.washington.edu/sisStudents/uwnetid/irs1098tconsent.aspx'),
                link('Student Tax Information', 'http://f2.washington.edu/fm/sfs/tax')
            ],
            'Tuition' : [
                link('Tuition Overview', 'http://f2.washington.edu/fm/sfs/tuition')
            ]
        },
        'studentcampuslife' : {
            'Housing & Dining' : [
                link('Add Funds to Husky Card', 'https://www.hfs.washington.edu/olco/Secure/AccountSummary.aspx'),
                link('Campus Dining', 'http://www.uwb.edu/food'),
                link('Check HFS Balance', 'https://www.hfs.washington.edu/myhfs/ledger.aspx'),
                link('Student Housing', 'http://www.uwb.edu/housing')
            ],
            'Health & Wellness' : [
                link('Counseling Services', 'http://www.uwb.edu/studentservices/counseling'),
                link('Student Health Resource', 'http://www.uwb.edu/studentservices/health-matters'),
                link('Recreation and Wellness', 'http://www.uwb.edu/studentlife/rec-wellness'),
                link('Student Health Insurance', 'http://www.uwb.edu/studentservices/insurance')
            ],
            'Support Services' : [
                link('Disability Resources for Students (DRS)', 'http://www.bothell.washington.edu/studentservices/drs'),
                link('Diversity Resources', 'http://www.uwb.edu/diversity'),
                link('Orientation & Transition Programs', 'http://www.bothell.washington.edu/orientation'),
                link('Q Center', 'http://depts.washington.edu/qcenter/wordpress/'),
                link("Women's Center", 'http://depts.washington.edu/womenctr/'),
                link('SafeCampus', 'http://www.washington.edu/safecampus/uwb/'),
                link('Security & Campus Safety: Sexual Assualts', 'http://www.uwb.edu/getattachment/admin/procedures/sexualassaultspolicy.pdf'),
            ],
            'Campus Retail' : [
                link('Student Success Center', 'http://www.uwb.edu/studentservices/ssc'),
                link('University Book Store', 'http://www.bookstore.washington.edu/student_faculty/student_faculty.taf?verba=uwbothell')
            ],
            'Transportation' : [
                link('Mobility Map', 'http://www.uwb.edu/getattachment/admin/emergency/mobility.pdf'),
                link('Campus Map', 'http://www.uwb.edu/visitors/uw-bothell-map.pdf'),
                link('Getting to Bothell Campus', 'https://www.uwb.edu/admin/transportation')
            ],
            'Rules & Regulations' : [
                link('Family Educational Rights and Privacy Act (FERPA) - Privacy of Student Information', 'http://www.washington.edu/students/reg/ferpa.html'),
                link('Student Guide to Academic Integrity', 'http://www.uwb.edu/academic/policies/academicconduct/student-guide'),
                link('Student Conduct and Responsibility', 'http://www.uwb.edu/studentservices/studentconduct')
            ],
        },
        'eventsactivities' : {
            'Events' : [
                link('Campus Event Calendar', 'https://www.uwb.edu/calendar'),
                link('Student Life Event Calendar', 'http://www.uwb.edu/studentlife/events')
            ],
            'Student Clubs & Organizations' : [
                link('Club Directory', 'http://www.bothell.washington.edu/studentlife/clubs/directory')
            ],
            'Stay Connected' : [
                link('Campus News', 'http://www.uwb.edu/news'),
                link('UW Bothell Facebook Page', 'http://www.facebook.com/uwbothell'),
                link('UW Bothell YouTube Channel', 'http://www.youtube.com/user/uwbothell'),
                link('UW Bothell Instagram', 'http://instagram.com/UW_BOTHELL'),
                link('UW Bothell Twitter', 'http://twitter.com/UWBothell'),
                link('UW Bothell LinkedIn', 'https://www.linkedin.com/groups/University-Washington-Bothell-92858?home=&gid=92858')
            ]
        },
        'toolssoftware' : {
            'Teaching & Learning Tools' : [
                link('Canvas LMS', 'http://canvas.uw.edu/'),
                link('Catalyst Web Tools', 'https://catalyst.uw.edu/'),
                link('Notify.UW', 'https://notify.uw.edu/'),
                link('Tableau Data Analysis Software', 'http://www.washington.edu/itconnect/wares/uware/tableau-software/'),
                link('Tegrity', 'https://uw.tegrity.com/'),
                link('Panopto', 'https://panopto.uw.edu/')
            ],
            'Email & UW NetID' : [
                link('Gmail', 'https://mail.google.com/a/uw.edu'),
                link('Alpine Mail', 'http://alpine.washington.edu/'),
                link('Email Forwarding', 'https://uwnetid.washington.edu/manage/?forward'),
                link('Manage UW NetID Account', 'https://uwnetid.washington.edu/manage/')
            ],
            'Directory' : [
                link('Bothell Faculty and Staff Directory', 'http://www.uwb.edu/directory')
            ]
        },
        'employment' : {
            '' : [
                link('Career Services', 'http://www.bothell.washington.edu/careers'),
                link('Employee Self-Service (ESS)', 'https://www.washington.edu/ess/'),
                link('Husky Jobs', 'https://washington-csm.symplicity.com/students/index.php'),
                link('Student Employment in the Libraries', 'http://www.lib.washington.edu/about/employment/students')
            ]
        }
    },
    'tacoma' : {
        'academics' : {
            'Registration' : [
                link('Academic Calendar', 'http://www.washington.edu/students/reg/calendar.html'),
                link('Course Catalog', 'http://www.washington.edu/students/crscatt/'),
                link('Degree Audit Reporting System (DARS)', 'https://sdb.admin.washington.edu/students/uwnetid/dars.asp'),
                link('MyPlan', 'https://uwstudent.washington.edu/student/myplan'),
                link('Registration', 'https://sdb.admin.washington.edu/students/uwnetid/register.asp'),
                link('Schedule Finder', 'http://www.tacoma.washington.edu/enrollment_apps/timeschedule/search.cfm'),
                link('UW Tacoma Time Schedule', 'http://www.tacoma.uw.edu/uwt/enrollment-services/time-schedule-registration-guide')
            ],
            'Advising & Tutoring' : [
                link('Career Development', 'http://www.tacoma.washington.edu/studentaffairs/SS/cde_about.cfm'),
                link('Teaching and Learning Center', 'http://www.tacoma.uw.edu/teaching-learning-center/teaching-learning-center'),
                link('International Student Services (ISS)', 'http://www.tacoma.uw.edu/uwt/taxonomy/term/252'),
                link('Academic Writing Resources', 'http://www.tacoma.uw.edu/teaching-and-learning-center/writing-resources-0'),
                link('Undergraduate Academic Advising (Pre-major)', 'http://www.tacoma.uw.edu/advising'),
                link('Study Abroad', 'http://www.tacoma.uw.edu/international-programs/international-programs')
            ],
            'Grades & Transcripts' : [
                link('GPA Calculator', 'http://www.washington.edu/uaa/advising/general-education-requirements/gpa-calculator/'),
                link('Grade Report', 'https://sdb.admin.washington.edu/students/uwnetid/grades.asp'),
                link('Order Official Transcripts', 'https://sdb.admin.washington.edu/students/uwnetid/official.asp'),
                link('Unofficial Transcript', 'https://sdb.admin.washington.edu/students/uwnetid/unofficial.asp')
            ],
            'Libraries' : [
                link('Electronic Course Reserves', 'https://ereserves.tacoma.washington.edu/'),
                link('UW Tacoma Library', 'http://www.tacoma.uw.edu/library')
            ],
            'Graduation' : [
                link('Applying to Graduate', 'http://www.tacoma.uw.edu/uwt/enrollment-services/applying-graduate')
            ]
        },
        'finances' : {
            'Financial Aid' : [
                link('Financial Aid and Scholarships', 'http://www.tacoma.uw.edu/uwt/financial-aid'),
                link('Financial Aid Status', 'https://sdb.admin.washington.edu/students/uwnetid/finaidstatus.asp')
            ],
            'Taxes' : [
                link('Form 1098-T', 'https://sdb.admin.washington.edu/sisStudents/uwnetid/irs1098tconsent.aspx'),
                link('Student Tax Information', 'http://f2.washington.edu/fm/sfs/tax')
            ],
            'Tuition' : [
                link('Tuition Overview', 'http://f2.washington.edu/fm/sfs/tuition')
            ]
        },
        'studentcampuslife' : {
            'Housing & Dining' : [
                link('Add Funds to Husky Card', 'https://www.hfs.washington.edu/olco/Secure/AccountSummary.aspx'),
                link('Campus Dining', 'http://www.tacoma.uw.edu/uwt/convenience-store/welcome-0'),
                link('Check HFS Balance', 'https://www.hfs.washington.edu/myhfs/ledger.aspx'),
                link('Housing', 'http://www.tacoma.uw.edu/housing')
            ],
            'Health & Wellness' : [
                link('Student Counseling Center', 'http://www.tacoma.washington.edu/studentaffairs/SHW/scc_about.cfm'),
                link('Student Health Services (SHS)', 'http://www.tacoma.washington.edu/studentaffairs/SHW/shs_healthservices_about.cfm'),
                link('Recreation & Fitness', 'http://www.tacoma.washington.edu/studentaffairs/SI/rec_fit_about.cfm'),
                link('Student Health Insurance', 'http://www.tacoma.uw.edu/ses/health/insurance')
            ],
            'Support Services' : [
                link('Disability Support Services (DSS)', 'http://www.tacoma.washington.edu/studentaffairs/SHW/dss_about.cfm'),
                link('Diversity Resources', 'http://www.tacoma.uw.edu/diversity'),
                link('New Student Orientation', 'http://www.tacoma.washington.edu/studentaffairs/SS/nsp_nso.cfm'),
                link('Q Center', 'http://depts.washington.edu/qcenter/wordpress/'),
                link("Women's Center", 'http://depts.washington.edu/womenctr/'),
                link('SafeCampus', 'http://www.washington.edu/safecampus/uwt/'),
                link('Campus Safety & Security', 'http://www.tacoma.uw.edu/uwt/administrative-services/campus-safety')
            ],
            'Campus Retail' : [
                link('Dawg House Student Lounge', 'http://www.tacoma.washington.edu/studentaffairs/SI/rec_fit_lounge.cfm'),
                link('University Book Store', 'http://www.bookstore.washington.edu/student_faculty/student_faculty.taf?verba=uwtacoma')
            ],
            'Transportation' : [
                link('Accessibility Guide', 'http://www.tacoma.washington.edu/studentaffairs/SHW/dss_access.cfm'),
                link('Campus Map', 'http://www.tacoma.uw.edu/campus-map/campus-map'),
                link('Getting to Tacoma Campus', 'http://www.tacoma.uw.edu/getting-campus/getting-campus')
            ],
            'Rules & Regulations' : [
                link('Family Educational Rights and Privacy Act (FERPA) - Privacy of Student Information', 'http://www.washington.edu/students/reg/ferpa.html'),
                link('Student Conduct', 'http://www.tacoma.washington.edu/studentaffairs/SI/conduct_about.cfm')
            ]
        },
        'toolssoftware' : {
            'Teaching & Learning Tools' : [
                link('Canvas LMS', 'http://canvas.uw.edu/'),
                link('Catalyst Web Tools', 'https://catalyst.uw.edu/'),
                link('Notify.UW', 'https://notify.uw.edu/'),
                link('SpaceScout Study Space Finder', 'http://spacescout.uw.edu/tacoma'),
                link('Tableau Data Analysis Software', 'http://www.washington.edu/itconnect/wares/uware/tableau-software/'),
                link('Tegrity', 'https://uw.tegrity.com/'),
                link('Panopto', 'https://panopto.uw.edu/')
            ],
            'Email & UW NetID' : [
                link('Gmail', 'https://mail.google.com/a/uw.edu'),
                link('Alpine Mail', 'http://alpine.washington.edu/'),
                link('Email Forwarding', 'https://uwnetid.washington.edu/manage/?forward'),
                link('Manage UW NetID Account', 'https://uwnetid.washington.edu/manage/')
            ],
            'Directory' : [
                link('UW Directory', 'http://www.washington.edu/home/directories.html')
            ]
        },
        'eventsactivities' : {
            'Events' : [
                link('Campus Event Calendar', 'http://www.tacoma.uw.edu/calendar/calendar')
            ],
            'Student Clubs & Organizations' : [
                link('UW Tacoma Clubs & Organizations', 'https://dawgden.tacoma.uw.edu/Organizations')
            ],
            'Stay Connected' : [
                link('Campus News', 'http://www.tacoma.uw.edu/news/news-information'),
                link('UW Tacoma Facebook Page', 'http://www.facebook.com/uwtacoma'),
                link('UW Tacoma YouTube Channel', 'http://www.youtube.com/user/uwTacomaAdvancement')
            ]
        },
        'employment' : {
            '' : [
                link('Career Development', 'http://www.tacoma.washington.edu/studentaffairs/ss/cde_about.cfm'),
                link('Employee Self-Service (ESS)', 'https://www.washington.edu/ess/'),
                link('Husky Jobs', 'https://washington-csm.symplicity.com/students/index.php'),
                link('Student Employment in the Libraries', 'http://www.lib.washington.edu/about/employment/students')
            ]
        }
    }
}

# Everything should be sorted alphabetically in subcategories
for campus in resLinks.values():
    for page in campus.values():
        for subcat in page.values():
            subcat.sort()

# While testing the tests, remove known failures as we go
#resLinks['seattle'].pop('studentcampuslife')


text:
namespace Luce
{
	namespace Threading
	{
		struct Mutex::Data_
		{
			HANDLE Handle_;
		};

		Mutex::Mutex()
		{
			Value_ = new Mutex::Data_;
			Value_->Handle_ = CreateMutex(NULL, FALSE, NULL);
		}
		Mutex::~Mutex()
		{
			CloseHandle(Value_->Handle_);
			delete Value_;
		}

		void Mutex::Lock()
		{
			WaitForSingleObject(Value_->Handle_, INFINITE);
		}
		void Mutex::Unlock()
		{
			ReleaseMutex(Value_->Handle_);
		}
		bool Mutex::TryLock()
		{
			if (WaitForSingleObject(Value_->Handle_, 0) == WAIT_OBJECT_0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		void* Mutex::NativeHandle()
		{
			return Value_->Handle_;
		}
	}
}
#endif

redpajama_set_name: RedPajamaGithub


text:
import Airtable from 'airtable'
import config from '../config'
import { logger } from './resources'

const base = new Airtable({ apiKey: config.airtable.apiKey }).base(
  config.airtable.baseId,
)
const table = base(config.airtable.tableName)

export function createRecord(record) {
  return table.create(record)
}

export async function listRecords(filter) {
  let records = []
  await table
    .select({
      filterByFormula: filter || '',
    })
    .eachPage((recordsPage, fetchNextPage) => {
      records = [...records, ...recordsPage]
      fetchNextPage()
    })
  records = records.map(record => {
    let recordInfo = record.fields
    recordInfo.id = record.getId()
    return recordInfo
  })
  return records
}

export async function updateRecord(userChannel, notifications) {
  const filter = "({channel_id} = '" + userChannel + "')"
  const records = await listRecords(filter)
  const recordId = records[0].id
  await table.update(recordId, { notifications })
  logger.devLog('Notifications updated for channel ' + userChannel)
}

export async function updateChannelId(recordId, channelId) {
  await table.update(recordId, { channel_id: channelId })
  logger.devLog('Channel updated ' + channelId)
}


text:
<Configure id="Server" class="org.eclipse.jetty.server.Server">
    <!--https://www.eclipse.org/jetty/documentation/9.4.x/jetty-maven-plugin.html-->
    <Call name="setAttribute">for
        <Arg>org.eclipse.jetty.server.Request.maxFormContentSize</Arg>
        <Arg>5000000</Arg>
    </Call>
    <Call name="setAttribute">for
        <Arg>org.eclipse.jetty.server.Request.maxFormKeys</Arg>
        <Arg>5000000</Arg>
    </Call>
</Configure>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="superheroes_names">
        <item>"Superman"</item>
        <item>"Batman"</item>
        <item>"Wonder Woman"</item>
        <item>"Flash"</item>
        <item>"Green Lantern"</item>
        <item>"Aquaman"</item>
        <item>"Martian Manhunter"</item>
        <item>"Green Arrow"</item>
    </array>
    <array name="superheroes_history">
        <item>"Superman is born Kal-El on the alien planet Krypton. His parents, Jor-El and Lara become aware of Krypton's impending destruction and Jor-El begins constructing a
            spacecraft that would carry Kal-El to Earth. During Krypton's last moments, Jor-El
            places young Kal-El in the spacecraft and launches it. Jor-El and Lara die as the
            spacecraft barely escapes Krypton's fate. The explosion transforms planetary debris into
            kryptonite, a radioactive substance that is lethal to superpowered (as by Earth's yellow
            sun) Kryptonians.

            The spacecraft lands in the rural United States, where it is found by a passing
            motorist. Jonathan and Martha Kent adopt Kal-El and name him Clark Kent. As Clark grows
            up on Earth, he and his adoptive parents discover that he has superhuman powers. The
            Kents teach Clark to use these powers responsibly to help others and fight crime.

            Clark keeps his powers secret in order to protect his family and friends, who might be
            endangered by his criminal enemies. In order to use his powers to help humanity, Clark
            creates the alter ego of Superman. A number of elements are added to each identity to
            keep them distinct enough to prevent the casual observer from matching them. Superman
            wears a characteristic red and blue costume with a letter \S\ emblem and a cape. Clark
            Kent takes to wearing glasses, styling his hair differently, changing his body language,
            significantly altering his voice, and wearing looser clothing and suits that hide his
            physique.

            Clark Kent moves to Metropolis and takes a job as a reporter at the Daily Planet, where
            he meets his friends and co-workers, Lois Lane, Jimmy Olsen and Editor Perry White.
            Superman becomes the subject of frequent headline stories written by Lois, and the two
            become romantically attracted to each other."
        </item>

        <item>"Bruce Wayne is born to Dr. Thomas Wayne and his wife Martha, two very wealthy and
            charitable Gotham City socialites. Bruce is brought up in Wayne Manor, and leads a happy
            and privileged existence until the age of eight, when his parents are killed by a
            small-time criminal named Joe Chill while on their way home from a movie theater. That
            night, Bruce Wayne swears an oath to spend his life fighting crime. He engages in
            intense intellectual and physical training; however, he realizes that these skills alone
            would not be enough. \Criminals are a superstitious cowardly lot,\ Wayne remarks, \so my
            disguise must be able to strike terror into their hearts. I must be a creature of the
            night, black, terrible...\ As if responding to his desires, a bat suddenly flies through
            the window, inspiring Bruce to take on the persona of Batman."
        </item>

        <item>"Diana was a member of a tribe of women named the Amazons, native to Paradise Island
            and a secluded island set in the middle of a vast ocean. Captain Steve Trevor's plane
            crashes on the island and he is found alive but unconscious by Diana and a fellow
            Amazon. Diana has him nursed back to health and falls in love with him. A competition is
            held amongst all the Amazons by Diana's mother, the Queen of the Amazons Hippolyte, in
            order to determine who is the most worthy of all the women; Hippolyte charges the winner
            with the responsibility of delivering Captain Steve Trevor back to man's world and to
            fight for justice. Hippolyte forbids Diana from entering the competition, but she takes
            part nonetheless, wearing a mask to conceal her identity. She wins the competition and
            reveals herself, surprising Hippolyte, who ultimately gives in to Diana's wish to go to
            Man's World. She then safely returns Steve Trevor back to his home and is awarded a
            special dress made by her mother for her new role as Wonder Woman.

            Coming to America for the first time, Wonder Woman comes upon a weeping army nurse named
            Diana Prince. Inquiring about her state, she finds that the nurse wanted to leave for
            South America with her fiancé but was unable to due to shortage of money. As both of
            them looked identical and Wonder Woman needed a job and a valid identity to look after
            Steve (who was admitted in the same army hospital), she gives her the money she had
            earned earlier to help her go to her fiance in exchange for her credentials. The nurse
            reveals her name as Diana Prince, and thus, Wonder Woman's secret identity was created,
            and she began working as a nurse in the army."
        </item>

        <item>"Barry Allen is a police scientist (his job title was changed to a forensic scientist
            in The Flash: Iron Heights one-shot) with a reputation for being very slow, deliberate,
            and frequently late, which frustrates his fiancee, Iris West. One night, as he is
            preparing to leave work, a lightning bolt shatters a case of chemicals and spills them
            all over Allen. As a result, Allen finds that he can run extremely fast and has matching
            reflexes.
            He dons a set of red tights sporting a lightning bolt, dubs himself the Flash, (after
            his childhood comic book hero, Jay Garrick), and becomes Central City's resident
            costumed crimefighter. Central City University professor Ira West (Iris' adoptive
            father) designed Allen's costume (reminiscent of the Fawcett Captain Marvel) and the
            ring which stores it while Allen is in his civilian identity. The ring can eject the
            compressed clothing when Allen needs it and suck it back in with the aid of a special
            gas that shrinks the suit. In addition, Allen invented the cosmic treadmill, a device
            that allowed for precise time travel and was used in many stories. Allen was so well
            liked that nearly all speedsters that come after him are constantly compared to him."
        </item>

        <item>"Green Lantern is a superhero and an intergalactic police officer in the DC Universe.
            The weapon he wields is a power ring that translates his ideas into green energy using
            the strength of his willpower. He is a member of the Green Lantern Corps, an
            organization created by the Guardians of the Universe that has established thousands of
            members distributed throughout each space sector. There have been several assigned to
            the planet Earth in Sector 2814.

            Alan Scott was the original Green Lantern of the Golden Age, and a member of the Justice
            Society of America. Although he is not a member of the Corps, he taps into the same
            energy using the magical Starheart. Hal Jordan was the first human Corps member, and is
            known as possibly the greatest of all time because he never gives up under any
            circumstances. He received his ring from his predecessor the dying alien Abin Sur, and
            was a founding member of the Justice League of America."
        </item>

        <item>"Aquaman, also known as Arthur Curry and Orin, is a superhero and the ruler of the
            seas. As the king of Atlantis and other undersea territories, he technically controls
            most of the planet. His abilities include super-strength, durability, super-speed,
            staying underwater indefinitely, and telepathy, which he uses to communicate with
            sea-life. His aquatic nature means he requires water regularly at the risk of
            dehydration, although he is perfectly capable of staying on land for extended periods.
            The Aquaman Family also includes his wife Mera and his side-kicks Aqualad and Aquagirl,
            along with a number of others, fighting together against villains. He is also a founding
            member of the Justice League of America. Arthur Joseph Curry was his successor after the
            original died, and had his own adventures for several years, until Orin was resurrected
            during Blackest Night and reclaimed his title."
        </item>

        <item>"Martian Manhunter, also known as J'onn J'onzz and John Jones, is a superhero from the
            planet Mars and the last surviving member of his race. A martian holocaust killed his
            wife and daughter, nearly driving him mad, until he was brought to Earth in an accident
            caused by scientist Saul Erdel. His natural abilities include super-strength,
            super-speed, invulnerability, flight, shape-shifting, intangibility and telepathy. He
            has been a member of almost every incarnation of the Justice League of America. Although
            he holds great reverence for his homeworld, he has come to greatly respect his adopted
            world as well and protects it as his home. In his secret identity, to blend into
            humanity, he is a gritty hard-boiled police officer."
        </item>

        <item>"Green Arrow is a vigilante superhero who fights crime using archery, technology, and
            martial arts. In his secret identity he is politician and billionaire Oliver Queen, a
            hot-headed social activist and owner of Queen Industries. Black Canary is his long-time
            love interest and Speedy is his side-kick. The extended family of heroes who work with
            him call themselves Team Arrow. Oliver was killed in an explosion at one point and
            remained dead for many years until he was resurrected during the Quiver storyline. He
            has been a member of the Justice League and the Outsiders."
        </item>
    </array>
</resources>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>br.unicamp.ic.lsd.mercurius</groupId>
	<artifactId>basket-mgr</artifactId>
	<packaging>pom</packaging>

	<parent>
		<groupId>br.unicamp.ic.lsd</groupId>
		<artifactId>mercurius</artifactId>
		<version>1.3</version>
	</parent>

	<name>Basket Manager</name>

	<modules>
		<module>basket-mgr-spec</module>
		<module>basket-mgr-impl</module>
	</modules>
</project>


text:
<?php
/**
 * SS_Cache provides a bunch of static functions wrapping the Zend_Cache system in something a little more
 * easy to use with the SilverStripe config system.
 *
 * A Zend_Cache has both a frontend (determines how to get the value to cache, and how to serialize it for storage)
 * and a backend (handles the actual storage).
 *
 * Rather than require library code to specify the backend directly, cache consumers provide a name for the cache
 * backend they want. The end developer can then specify which backend to use for each name in their project's
 * _config.php. They can also use 'all' to provide a backend for all named caches
 *
 * End developers provide a set of named backends, then pick the specific backend for each named cache. There is a
 * default File cache set up as the 'default' named backend, which is assigned to 'all' named caches
 *
 * USING A CACHE
 *
 * $cache = SS_Cache::factory('foo') ; // foo is any name (try to be specific), and is used to get configuration & storage info
 *
 * if (!($result = $cache->load($cachekey))) {
 * 	$result = caluate some how;
 * 	$cache->save($result);
 * }
 *
 * return $result;
 *
 * Normally there's no need to remove things from the cache - the cache backends clear out entries based on age & maximum
 * allocated storage. If you include the version of the object in the cache key, even object changes don't need any invalidation
 *
 * DISABLING CACHING IN DEV MOVE
 *
 * (in _config.php)
 *
 * if (Director::isDev()) SS_Cache::set_cache_lifetime('any', -1, 100);
 *
 * USING MEMCACHED AS STORE
 *
 * (in _config.php)
 *
 * SS_Cache::add_backend('primary_memcached', 'Memcached',
 * 	array('host' => 'localhost', 'port' => 11211, 'persistent' => true, 'weight' => 1, 'timeout' => 5, 'retry_interval' => 15, 'status' => true, 'failure_callback' => '' )
 * );
 *
 * SS_Cache::pick_backend('primary_memcached', 'any', 10);
 * SS_Cache::pick_backend('default', 'aggregate', 20); // Aggregate needs a backend with tag support, which memcached doesn't provide
 *
 * USING APC AND FILE AS TWO LEVEL STORE
 *
 * (in _config.php)
 *
 * SS_Cache::add_backend('two-level', 'TwoLevels', array(
 * 	'slow_backend' => 'File',
 * 	'fast_backend' => 'Apc',
 * 	'slow_backend_options' => array('cache_dir' => TEMP_FOLDER . DIRECTORY_SEPARATOR . 'cache')
 * ));
 *
 * SS_Cache::pick_backend('two-level', 'any', 10); // No need for special backend for aggregate - TwoLevels with a File slow backend supports tags
 *
 * @author hfried
 * @package sapphire
 * @subpackage core
 */
class SS_Cache {

	protected static $backends = array();
	protected static $backend_picks = array();

	protected static $cache_lifetime = array();

	/**
	 * Initialize the 'default' named cache backend
	 */
	protected static function init(){
		if (!isset(self::$backends['default'])) {
			$cachedir = TEMP_FOLDER . DIRECTORY_SEPARATOR . 'cache';
			if (!is_dir($cachedir)) mkdir($cachedir);
			self::$backends['default'] = array('File', array('cache_dir' => TEMP_FOLDER . DIRECTORY_SEPARATOR . 'cache'));
		}
	}

	/**
	 * Add a new named cache backend
	 *
	 * @param string $name The name of this backend as a freeform string
	 * @param string $type The Zend_Cache backend ('File' or 'Sqlite' or ...)
	 * @param array $options The Zend_Cache backend options (see http://framework.zend.com/manual/en/zend.cache.html)
	 * @return none
	 */
	static function add_backend($name, $type, $options=array()) {
		self::init();
		self::$backends[$name] = array($type, $options);
	}

	/**
	 * Pick a named cache backend for a particular named cache
	 *
	 * @param string $name The name of the backend, as passed as the first argument to add_backend
	 * @param string $for The name of the cache to pick this backend for (or 'any' for any backend)
	 * @param integer $priority The priority of this pick - the call with the highest number will be the actual backend picked.
	 *                          A backend picked for a specific cache name will always be used instead of 'any' if it exists, no matter the priority.
	 * @return none
	 */
	static function pick_backend($name, $for, $priority=1) {
		self::init();

		$current = -1;
		if (isset(self::$backend_picks[$for])) $current = self::$backend_picks[$for]['priority'];

		if ($priority >= $current) self::$backend_picks[$for] = array('name' => $name, 'priority' => $priority);
	}

	/**
	 * Set the cache lifetime for a particular named cache
	 *
	 * @param string $for The name of the cache to set this lifetime for (or 'any' for all backends)
	 * @param integer $lifetime The lifetime of an item of the cache, in seconds, or -1 to disable caching
	 * @param integer $priority The priority. The highest priority setting is used. Unlike backends, 'any' is not special in terms of priority.
	 */
	static function set_cache_lifetime($for, $lifetime=600, $priority=1) {
		self::init();

		$current = -1;
		if (isset(self::$cache_lifetime[$for])) $current = self::$cache_lifetime[$for]['priority'];

		if ($priority >= $current) self::$cache_lifetime[$for] = array('lifetime' => $lifetime, 'priority' => $priority);
	}

	/**
	 * Build a cache object
	 * @param string $for The name of the cache to build the cache object for
	 * @param string $frontend (optional) The type of Zend_Cache frontend to use. Output is almost always the best
	 * @param array $frontendOptions (optional) Any frontend options to use.
	 *
	 * @return The cache object. It has been partitioned so that actions on the object
	 *	won't affect cache objects generated with a different $for value, even those using the same Zend_Backend
	 *
	 * -- Cache a calculation
	 *
	 * if (!($result = $cache->load($cachekey))) {
	 * 	$result = caluate some how;
	 * 	$cache->save($result);
	 * }
	 *
	 * return $result;
	 *
	 * -- Cache captured output
	 *
	 * if (!($cache->start($cachekey))) {
	 *
	 * 	// output everything as usual
	 * 	echo 'Hello world! ';
	 * 	echo 'This is cached ('.time().') ';
	 *
	 * 	$cache->end(); // output buffering ends
	 * }
	 *
	 * -- Invalidate an element
	 *
	 * $cache->remove($cachekey);
	 *
	 * -- Clear the cache (warning - this clears the entire backend, not just this named cache partition)
	 *
	 * $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
	 *
	 * See the Zend_Cache documentation at http://framework.zend.com/manual/en/zend.cache.html for more
	 *
	 */
	static function factory($for, $frontend='Output', $frontendOptions=null) {
		self::init();

		$backend_name = 'default'; $backend_priority = -1;
		$cache_lifetime = 600; $lifetime_priority = -1;

		foreach (array('any', $for) as $name) {
			if (isset(self::$backend_picks[$name]) && self::$backend_picks[$name]['priority'] > $backend_priority) {
				$backend_name = self::$backend_picks[$name]['name'];
				$backend_priority = self::$backend_picks[$name]['priority'];
			}

			if (isset(self::$cache_lifetime[$name]) && self::$cache_lifetime[$name]['priority'] > $lifetime_priority) {
				$cache_lifetime = self::$cache_lifetime[$name]['lifetime'];
				$lifetime_priority = self::$cache_lifetime[$name]['priority'];
			}
		}

		$backend = self::$backends[$backend_name];

		$basicOptions = array('cache_id_prefix' => $for);

		if ($cache_lifetime >= 0) $basicOptions['lifetime'] = $cache_lifetime;
		else $basicOptions['caching'] = false;

		$frontendOptions = $frontendOptions ? array_merge($basicOptions, $frontendOptions) : $basicOptions;

		require_once 'Zend/Cache.php';
		return Zend_Cache::factory($frontend, $backend[0], $frontendOptions, $backend[1]);
	}
}


text:
package pw.anisimov.adverto.api

import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.{HttpHeader, HttpResponse}
import akka.http.scaladsl.model.headers.{Origin, `Access-Control-Allow-Credentials`, `Access-Control-Allow-Methods`, `Access-Control-Allow-Origin`}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{Directive0, MethodRejection, RejectionHandler}

/**
 * https://gist.github.com/pcting/2e65c36f868c5cee7d6a#file-akkahttpcorssupport-scala
 */
trait CorsSupport {

  protected def corsAllowOrigins: List[String]

  protected def corsAllowedHeaders: List[String]

  protected def corsAllowCredentials: Boolean

  protected def optionsCorsHeaders: List[HttpHeader]

  protected def corsRejectionHandler(allowOrigin: `Access-Control-Allow-Origin`) = RejectionHandler
    .newBuilder().handle {
    case MethodRejection(supported) =>
      complete(HttpResponse().withHeaders(
        `Access-Control-Allow-Methods`(OPTIONS, supported) ::
          allowOrigin ::
          optionsCorsHeaders
      ))
  }
    .result()

  private def originToAllowOrigin(origin: Origin): Option[`Access-Control-Allow-Origin`] =
    if (corsAllowOrigins.contains("*") || corsAllowOrigins.contains(origin.value())) {
      origin.origins.headOption.map(`Access-Control-Allow-Origin`.apply)
    }
    else {
      None
    }

  def cors[T]: Directive0 = mapInnerRoute { route => context =>
    ((context.request.method, context.request.header[Origin].flatMap(originToAllowOrigin)) match {
      case (OPTIONS, Some(allowOrigin)) =>
        handleRejections(corsRejectionHandler(allowOrigin)) {
          respondWithHeaders(allowOrigin, `Access-Control-Allow-Credentials`(corsAllowCredentials)) {
            route
          }
        }
      case (_, Some(allowOrigin)) =>
        respondWithHeaders(allowOrigin, `Access-Control-Allow-Credentials`(corsAllowCredentials)) {
          route
        }
      case (_, _) =>
        route
    })(context)
  }
}


text:
/*
 * @test
 * @bug 6863465
 * @summary  javac doesn't detect circular subclass dependencies via qualified names
 * @run main TestCircularClassfile
 */

import java.io.*;
import java.net.URI;
import java.util.Arrays;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;

import com.sun.source.util.JavacTask;
import java.util.EnumSet;

public class TestCircularClassfile {

    enum ClassName {
        A("A"),
        B("B"),
        C("C"),
        OBJECT("Object");

        String name;

        ClassName(String name) {
            this.name = name;
        }
    }

    static class JavaSource extends SimpleJavaFileObject {

        final static String sourceStub = "class #C extends #S {}";

        String source;

        public JavaSource(ClassName clazz, ClassName sup) {
            super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
            source = sourceStub.replace("#C", clazz.name).replace("#S", sup.name);
        }

        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return source;
        }
    }

    public static void main(String... args) throws Exception {
        int count = 0;
        for (ClassName clazz : EnumSet.of(ClassName.A, ClassName.B, ClassName.C)) {
            for (ClassName sup : EnumSet.of(ClassName.A, ClassName.B, ClassName.C)) {
                if (sup.ordinal() < clazz.ordinal()) continue;
                check("sub_"+count++, clazz, sup);
            }
        }
    }

    static JavaSource[] initialSources = new JavaSource[] {
            new JavaSource(ClassName.A, ClassName.OBJECT),
            new JavaSource(ClassName.B, ClassName.A),
            new JavaSource(ClassName.C, ClassName.B)
        };

    static String workDir = System.getProperty("user.dir");

    static void check(String destPath, ClassName clazz, ClassName sup) throws Exception {
        File destDir = new File(workDir, destPath); destDir.mkdir();
        final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
        JavacTask ct = (JavacTask)tool.getTask(null, null, null,
                Arrays.asList("-d", destPath), null, Arrays.asList(initialSources));
        ct.generate();
        File fileToRemove = new File(destPath, clazz.name + ".class");
        fileToRemove.delete();
        JavaSource newSource = new JavaSource(clazz, sup);
        DiagnosticChecker checker = new DiagnosticChecker();
        ct = (JavacTask)tool.getTask(null, null, checker,
                Arrays.asList("-cp", destPath), null, Arrays.asList(newSource));
        ct.analyze();
        if (!checker.errorFound) {
            throw new AssertionError(newSource.source);
        }
    }

    static class DiagnosticChecker implements DiagnosticListener<JavaFileObject> {

        boolean errorFound = false;

        public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
            if (diagnostic.getKind() == Diagnostic.Kind.ERROR &&
                    diagnostic.getCode().equals("compiler.err.cyclic.inheritance")) {
                errorFound = true;
            }
        }
    }
}


text:
package com.limitskyapps.aranya2014;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;

public class AboutUs extends FragmentActivity implements ActionBar.TabListener{

	private ViewPager viewPager;
    private TabsPagerAdapter_AboutUs mAdapter;
    private ActionBar bar;

    private String[] tabs = { "TU", "Aranya", "CSR" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_about_us);

        // Initilization
        viewPager = (ViewPager) findViewById(R.id.pager);
        bar = getActionBar();

		bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00bf8f")));
		bar.setTitle("About Us");
		bar.setDisplayHomeAsUpEnabled(true);

        mAdapter = new TabsPagerAdapter_AboutUs(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);

        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Adding Tabs
        for (String tab_name : tabs) {
            bar.addTab(bar.newTab().setText(tab_name)
                    .setTabListener(this));
        }

        /**
         * on swiping the viewpager make respective tab selected
         * */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                bar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // on tab selected
        // show respected fragment view
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    }

}


text:
<?php

namespace ElkArte\Menu;

/**
 * Class MenuItem
 *
 * This class implements a standard way of setting/getting menu params
 *
 * @package ElkArte\Menu
 */
abstract class MenuItem
{
	/** @var string $label Text label for this subsection. */
	protected $label = '';

	/** @var string $counter Index of counter specified in the menu options. */
	protected $counter = '';

	/** @var string $url URL to use for this menu item. */
	protected $url = '';

	/** @var string[] $permission Array of permissions to check for this subsection. */
	protected $permission = [];

	/** @var bool $enabled Bool to say whether this should be enabled. */
	protected $enabled = true;

	/**
	 * @param array $arr
	 * @param string $sa
	 *
	 * @return MenuItem
	 */
	public static function buildFromArray($arr, $sa = '')
	{
		$obj = new static();

		// Prepare
		$arr = $obj->camelCaseKeys($arr);
		$arr['permission'] = isset($arr['permission']) ? (array) $arr['permission'] : [];

		// Fetch the protected and public vars of this abstract + extended
		$vars = get_object_vars($obj);

		// Call the setters, using the defined class vars, with the supplied menu values
		foreach (array_replace($vars, array_intersect_key($arr, $vars)) as $var => $val)
		{
			$obj->{'set' . ucfirst($var)}($val);
		}

		// Account for any special setters
		$obj->buildMoreFromArray($arr, $sa);

		return $obj;
	}

	/**
	 * Renames array keys from under_score to underScore camelCase
	 *
	 * @param array $arr
	 *
	 * @return array
	 */
	private function camelCaseKeys($arr)
	{
		$keys = array_keys($arr);
		foreach ($keys as $key)
		{
			$keynew = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key))));
			if (!isset($arr[$keynew]))
			{
				$arr[$keynew] = $arr[$key];
				unset($arr[$key]);
			}
		}

		return $arr;
	}

	/**
	 * Get the label
	 *
	 * @return string
	 */
	public function getLabel()
	{
		return $this->label;
	}

	/**
	 * Set the label
	 *
	 * @param string $label
	 *
	 * @return MenuItem
	 */
	public function setLabel($label)
	{
		$this->label = $label;

		return $this;
	}

	/**
	 * Get the current counter
	 *
	 * @return string
	 */
	public function getCounter()
	{
		return $this->counter;
	}

	/**
	 * Set the counter
	 *
	 * @param string $counter
	 *
	 * @return MenuItem
	 */
	public function setCounter($counter)
	{
		$this->counter = $counter;

		return $this;
	}

	/**
	 * Get the url value
	 *
	 * @return string
	 */
	public function getUrl()
	{
		return $this->url;
	}

	/**
	 * Set the url value
	 *
	 * @param string $url
	 *
	 * @return MenuItem
	 */
	public function setUrl($url)
	{
		$this->url = $url;

		return $this;
	}

	/**
	 * Get the permissions
	 *
	 * @return string[]
	 */
	public function getPermission()
	{
		return $this->permission;
	}

	/**
	 * Set the permissions
	 *
	 * @param string[] $permission
	 *
	 * @return MenuItem
	 */
	public function setPermission($permission)
	{
		$this->permission = $permission;

		return $this;
	}

	/**
	 * Get if the item is enabled
	 *
	 * @return bool
	 */
	public function isEnabled()
	{
		return $this->enabled;
	}

	/**
	 * Set if the item is enabled
	 *
	 * @param bool $enabled
	 *
	 * @return MenuItem
	 */
	public function setEnabled($enabled)
	{
		$this->enabled = $enabled;

		return $this;
	}
}


text:
package com.miraclewong.volleydemo;

import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.toolbox.ImageLoader;

/**
 * Created by miraclewong on 15/12/20.
 */
public class BitmapCache implements ImageLoader.ImageCache {

    public LruCache<String, Bitmap> cache;
    public int max = 10 * 1024 * 1024;          //10M的缓存

    // 构造方法

    public BitmapCache() {
        cache = new LruCache<String, Bitmap>(max){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes()*value.getHeight();
            }
        };
    }

    @Override
    public Bitmap getBitmap(String url) {
        return cache.get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        cache.put(url,bitmap);
    }
}


text:
export const styles = `
:host {
  --background: #FFF;
  --borderRadius: 4px;
  --color: #333;
  --fontFamily: 'Arial', 'Helvetica', sans-serif;
  --padding: 8px 8px 36px 8px;
  --buttonBottomMargin: 8px;
  --buttonSideMargin: 4px;
  --buttonActiveColor: #444;
  --buttonHoverColor: #666;
  --buttonInactiveColor: #AAA;
  --contentBorderRadius: 0px;

  position: relative;
  align-items: center;
  justify-content: center;
  display: flex;
  flex-direction: column;
  outline: none;
  z-index: 1;
  overflow: auto;

  padding: var(--padding);
  border-radius: var(--borderRadius);
  font-family: var(--fontFamily);
  background: var(--background);
}

#container {
  color: var(--color);
  overflow: hidden;
  border-radius: var(--contentBorderRadius);
  display: block;
  cursor: pointer;
  -webkit-tap-highlight-color: rgba(0,0,0,0);
}

slot {
  display: flex;
  overflow-x: scroll;
  scroll-snap-type: x mandatory;
  scrollbar-width: none;
}

slot::-webkit-scrollbar {
  display: none;
}

::slotted(*) {
  flex: 1 0 auto;
  scroll-snap-align: start;
}

#buttons {
  display: flex;
  height: 20px;
  align-items: center;
  justify-content: center;
  position: absolute;
  bottom: var(--buttonBottomMargin);
}

#buttons button {
  margin: 0 var(--buttonSideMargin);
  font-size: 0;
  width: 18px;
  height: 18px;
  position: relative;
  background: none;
  border: none;
  cursor: pointer;
}

#buttons button::after {
  content: '';
  background: var(--buttonInactiveColor);
  width: 8px;
  height: 8px;
  border-radius: 50%;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

#buttons button::after:hover {
  background: var(--buttonHoverColor);
}

#buttons button.active::after {
  background: var(--buttonActiveColor);
}
`;

export const html = `

  <slot></slot>

`;


text: module.exports = require('./lib/scouter-nodejs');


text:
define(['exports', 'module', 'react', 'classnames'], function (exports, module, _react, _classnames) {
  'use strict';

  var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

  var _React = _interopRequireDefault(_react);

  var _classNames = _interopRequireDefault(_classnames);

  var Table = _React['default'].createClass({
    displayName: 'Table',

    propTypes: {
      striped: _React['default'].PropTypes.bool,
      bordered: _React['default'].PropTypes.bool,
      condensed: _React['default'].PropTypes.bool,
      hover: _React['default'].PropTypes.bool,
      responsive: _React['default'].PropTypes.bool
    },

    render: function render() {
      var classes = {
        'table': true,
        'table-striped': this.props.striped,
        'table-bordered': this.props.bordered,
        'table-condensed': this.props.condensed,
        'table-hover': this.props.hover
      };
      var table = _React['default'].createElement(
        'table',
        _extends({}, this.props, { className: (0, _classNames['default'])(this.props.className, classes) }),
        this.props.children
      );

      return this.props.responsive ? _React['default'].createElement(
        'div',
        { className: 'table-responsive' },
        table
      ) : table;
    }
  });

  module.exports = Table;
});


text:
package serverlogger

import (
	"errors"
	"fmt"
	"log"
	"os"
	"regexp"
	"runtime"
	"strings"
	"sync"
	"time"

	liblog "github.com/Cloud-Foundations/Dominator/lib/log"
	"github.com/Cloud-Foundations/Dominator/lib/logbuf"
	"github.com/Cloud-Foundations/Dominator/lib/srpc"
	"github.com/Cloud-Foundations/Dominator/lib/srpc/serverutil"
	proto "github.com/Cloud-Foundations/Dominator/proto/logger"
)

type loggerMapT struct {
	*serverutil.PerUserMethodLimiter
	sync.Mutex
	loggerMap map[string]*Logger
}

type grabWriter struct {
	data []byte
}

var loggerMap *loggerMapT = &loggerMapT{
	loggerMap: make(map[string]*Logger),
	PerUserMethodLimiter: serverutil.NewPerUserMethodLimiter(
		map[string]uint{
			"Debug":         1,
			"Print":         1,
			"SetDebugLevel": 1,
			"Watch":         1,
		}),
}

func init() {
	srpc.RegisterName("Logger", loggerMap)
}

func getCallerName(depth int) string {
	if pc, _, _, ok := runtime.Caller(depth); !ok {
		return "UNKNOWN"
	} else if fi := runtime.FuncForPC(pc); fi == nil {
		return "UNKNOWN"
	} else if splitName := strings.Split(fi.Name(), "."); len(splitName) < 1 {
		return "UNKNOWN"
	} else {
		return splitName[len(splitName)-1]
	}
}

func (w *grabWriter) Write(p []byte) (int, error) {
	w.data = p
	return len(p), nil
}

func newLogger(name string, options logbuf.Options, flags int) *Logger {
	loggerMap.Lock()
	defer loggerMap.Unlock()
	if _, ok := loggerMap.loggerMap[name]; ok {
		panic("logger already exists: " + name)
	}
	circularBuffer := logbuf.NewWithOptions(options)
	logger := &Logger{
		circularBuffer: circularBuffer,
		flags:          flags,
		level:          int16(*initialLogDebugLevel),
		streamers:      make(map[*streamerType]struct{}),
	}
	if logger.level < -1 {
		logger.level = -1
	}
	logger.maxLevel = logger.level
	// Ensure this satisfies the published interface.
	var debugLogger liblog.FullDebugLogger
	debugLogger = logger
	_ = debugLogger
	loggerMap.loggerMap[name] = logger
	return logger
}

func (l *Logger) checkAuth(authInfo *srpc.AuthInformation) error {
	if authInfo.HaveMethodAccess {
		return nil
	}
	if accessChecker := l.accessChecker; accessChecker == nil {
		return errors.New("no access to resource")
	} else if accessChecker(getCallerName(3), authInfo) {
		return nil
	} else {
		return errors.New("no access to resource")
	}
}

func (l *Logger) debug(level int16, v ...interface{}) {
	if l.maxLevel >= level {
		l.log(level, fmt.Sprint(v...), false)
	}
}

func (l *Logger) debugf(level int16, format string, v ...interface{}) {
	if l.maxLevel >= level {
		l.log(level, fmt.Sprintf(format, v...), false)
	}
}

func (l *Logger) debugln(level int16, v ...interface{}) {
	if l.maxLevel >= level {
		l.log(level, fmt.Sprintln(v...), false)
	}
}

func (l *Logger) fatals(msg string) {
	l.log(-1, msg, true)
	os.Exit(1)
}

func (l *Logger) log(level int16, msg string, dying bool) {
	buffer := &grabWriter{}
	rawLogger := log.New(buffer, "", l.flags)
	rawLogger.Output(4, msg)
	if l.level >= level {
		l.circularBuffer.Write(buffer.data)
	}
	recalculateLevels := false
	l.mutex.Lock()
	defer l.mutex.Unlock()
	for streamer := range l.streamers {
		if streamer.debugLevel >= level &&
			(streamer.includeRegex == nil ||
				streamer.includeRegex.Match(buffer.data)) &&
			(streamer.excludeRegex == nil ||
				!streamer.excludeRegex.Match(buffer.data)) {
			select {
			case streamer.output <- buffer.data:
			default:
				delete(l.streamers, streamer)
				close(streamer.output)
				recalculateLevels = true
			}
		}
	}
	if dying {
		for streamer := range l.streamers {
			delete(l.streamers, streamer)
			close(streamer.output)
		}
		l.circularBuffer.Flush()
		time.Sleep(time.Millisecond * 10)
	} else if recalculateLevels {
		l.updateMaxLevel()
	}
}

func (l *Logger) makeStreamer(request proto.WatchRequest) (
	*streamerType, error) {
	if request.DebugLevel < -1 {
		request.DebugLevel = -1
	}
	streamer := &streamerType{debugLevel: request.DebugLevel}
	if request.ExcludeRegex != "" {
		var err error
		streamer.excludeRegex, err = regexp.Compile(request.ExcludeRegex)
		if err != nil {
			return nil, err
		}
	}
	if request.IncludeRegex != "" {
		var err error
		streamer.includeRegex, err = regexp.Compile(request.IncludeRegex)
		if err != nil {
			return nil, err
		}
	}
	return streamer, nil
}

func (l *Logger) panics(msg string) {
	l.log(-1, msg, true)
	panic(msg)
}

func (l *Logger) prints(msg string) {
	l.log(-1, msg, false)
}

func (l *Logger) setLevel(maxLevel int16) {
	if maxLevel < -1 {
		maxLevel = -1
	}
	l.level = maxLevel
	l.mutex.Lock()
	l.updateMaxLevel()
	l.mutex.Unlock()
}

func (l *Logger) updateMaxLevel() {
	maxLevel := l.level
	for streamer := range l.streamers {
		if streamer.debugLevel > maxLevel {
			maxLevel = streamer.debugLevel
		}
	}
	l.maxLevel = maxLevel
}

func (l *Logger) watch(conn *srpc.Conn, streamer *streamerType) {
	channel := make(chan []byte, 256)
	streamer.output = channel
	l.mutex.Lock()
	l.streamers[streamer] = struct{}{}
	l.updateMaxLevel()
	l.mutex.Unlock()
	timer := time.NewTimer(time.Millisecond * 100)
	flushPending := false
	closeNotifier := conn.GetCloseNotifier()
	for keepGoing := true; keepGoing; {
		select {
		case <-closeNotifier:
			keepGoing = false
			break
		case data, ok := <-channel:
			if !ok {
				keepGoing = false
				break
			}
			if _, err := conn.Write(data); err != nil {
				keepGoing = false
				break
			}
			if !flushPending {
				timer.Reset(time.Millisecond * 100)
				flushPending = true
			}
		case <-timer.C:
			if conn.Flush() != nil {
				keepGoing = false
				break
			}
			flushPending = false
		}
	}
	if flushPending {
		conn.Flush()
	}
	l.mutex.Lock()
	delete(l.streamers, streamer)
	l.updateMaxLevel()
	l.mutex.Unlock()
	// Drain the channel.
	for {
		select {
		case <-channel:
		default:
			return
		}
	}
}

func (t *loggerMapT) getLogger(name string,
	authInfo *srpc.AuthInformation) (*Logger, error) {
	loggerMap.Lock()
	defer loggerMap.Unlock()
	if logger, ok := loggerMap.loggerMap[name]; !ok {
		return nil, errors.New("unknown logger: " + name)
	} else if err := logger.checkAuth(authInfo); err != nil {
		return nil, err
	} else {
		return logger, nil
	}
}

func (t *loggerMapT) Debug(conn *srpc.Conn,
	request proto.DebugRequest, reply *proto.DebugResponse) error {
	authInfo := conn.GetAuthInformation()
	if logger, err := t.getLogger(request.Name, authInfo); err != nil {
		return err
	} else {
		logger.Debugf(request.Level, "Logger.Debug(%d): %s\n",
			request.Level, strings.Join(request.Args, " "))
		return nil
	}
}

func (t *loggerMapT) Print(conn *srpc.Conn,
	request proto.PrintRequest,
	reply *proto.PrintResponse) error {
	authInfo := conn.GetAuthInformation()
	if logger, err := t.getLogger(request.Name, authInfo); err != nil {
		return err
	} else {
		logger.Println("Logger.Print():", strings.Join(request.Args, " "))
		return nil
	}
}

func (t *loggerMapT) SetDebugLevel(conn *srpc.Conn,
	request proto.SetDebugLevelRequest,
	reply *proto.SetDebugLevelResponse) error {
	authInfo := conn.GetAuthInformation()
	if logger, err := t.getLogger(request.Name, authInfo); err != nil {
		return err
	} else {
		logger.Printf("Logger.SetDebugLevel(%d)\n", request.Level)
		logger.SetLevel(request.Level)
		return nil
	}
}

func (t *loggerMapT) Watch(conn *srpc.Conn) error {
	var request proto.WatchRequest
	if err := conn.Decode(&request); err != nil {
		return err
	}
	authInfo := conn.GetAuthInformation()
	if logger, err := t.getLogger(request.Name, authInfo); err != nil {
		return conn.Encode(proto.WatchResponse{Error: err.Error()})
	} else if streamer, err := logger.makeStreamer(request); err != nil {
		return conn.Encode(proto.WatchResponse{Error: err.Error()})
	} else {
		if err := conn.Encode(proto.WatchResponse{}); err != nil {
			return err
		}
		if err := conn.Flush(); err != nil {
			return err
		}
		logger.watch(conn, streamer)
		return srpc.ErrorCloseClient
	}
}


text:
deployer
========

php-git deployer built on Yii


text:
**Server-Sent Events for iOS and Mac**

## What does it do?

It creates a long-lived, unidirectional HTTP channel between your Cocoa app and a web server so that your app can receive events from the server.

### Client Code

Subscribing to a _named event_ is done via the `addEventListener:handler:` method, as shown below:

```
NSURL *serverURL = [NSURL URLWithString:@"http://127.0.0.1:8000/"];
EventSource *source = [EventSource eventSourceWithURL:serverURL];
[source addEventListener:@"hello_event" handler:^(Event *e) {
    NSLog(@"%@: %@", e.event, e.data);
}];
[source open];
```

It's super simple and will be familiar to anyone who has seen any Server-Sent Events JavaScript code.

There's a `onMessage:` method that will receive all message events from the server. Additionally, there are `onOpen:` and `onError:` methods to receive open and error events.

Re-connections to the server are automatic and graceful, even if the server goes go.

### Server Code

This is a simple [Node.js](http://nodejs.org/) app that will generate the Server-Sent Events. The events are created at a rate of one per second.

```
var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, { 'Transfer-Encoding': 'chunked', 'Content-Type': 'text/event-stream' });

    setInterval(function() {
        var now = new Date().getTime();
        var payload = 'event: hello_event\ndata: {"message":"' + now + '"}\n\n';
        res.write(payload);
    }, 1000);
}).listen(8000);
```

The payload above doesn't include an `id` parameter, but if you include one it will be available in the `Event` object in your Cocoa code.

### Contact

[Oleg Komaristov](http://github.com/oleg-komaristov)

or original implementation author:

[Neil Cowburn](http://github.com/neilco)
[@neilco](https://twitter.com/neilco)

## License

[MIT license](http://neil.mit-license.org)

Copyright (c) 2013 Neil Cowburn (http://github.com/neilco/)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
from framework.plugin_loader import get_config
from plugins.tff_backend.plugin_consts import NAMESPACE

def get_tf_token_api_key():
    return get_config(NAMESPACE).rogerthat.token_api_key

def get_grid_api_key():
    return get_config(NAMESPACE).rogerthat.grid_api_key

def get_mazraa_api_key():
    return get_config(NAMESPACE).rogerthat.mazraa_api_key


text:
<?php

declare(strict_types=1);

namespace Doctrine\Tests\Mocks;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema\AbstractSchemaManager;

/**
 * Mock class for AbstractSchemaManager.
 */
class SchemaManagerMock extends AbstractSchemaManager
{
    /**
     * @param \Doctrine\DBAL\Connection $conn
     */
    public function __construct(Connection $conn)
    {
        parent::__construct($conn);
    }

    /**
     * {@inheritdoc}
     */
    protected function _getPortableTableColumnDefinition($tableColumn)
    {
    }
}


text:
RSpec.describe "Queue" do

  #
  # Environment
  #

  let(:connection) { MarchHare.connect }
  let(:channel)    { connection.create_channel }

  after :each do
    channel.close
    connection.close
  end

  context "that exists" do
    it "can be deleted" do
      q    = channel.queue("")
      q.delete
    end
  end

  context "that DOES NOT exist" do
    it "raises NO exception (as of RabbitMQ 3.2)" do
      ch = connection.create_channel
      q  = ch.queue("")

      q.delete(true, true)
      # No exception as of RabbitMQ 3.2. MK.
      q.delete(true, true)
    end
  end
end


text:
package operators;
//: operators/RoundingNumbers.java
// Rounding floats and doubles.
import static net.mindview.util.Print.*;

public class RoundingNumbers {
  public static void main(String[] args) {
    double above = 0.7, below = 0.4;
    float fabove = 0.7f, fbelow = 0.4f;
    print("Math.round(above): " + Math.round(above));
    print("Math.round(below): " + Math.round(below));
    print("Math.round(fabove): " + Math.round(fabove));
    print("Math.round(fbelow): " + Math.round(fbelow));
  }
} /* Output:
Math.round(above): 1
Math.round(below): 0
Math.round(fabove): 1
Math.round(fbelow): 0
*///:~


text:
/**
 * Created by dxc on 2016/9/2.
 */
'use strict';

Object.defineProperty(exports, '__esModule', {
    value: true
});

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var Life = (function (_Component) {
    _inherits(Life, _Component);

    function Life() {
        _classCallCheck(this, Life);

        _get(Object.getPrototypeOf(Life.prototype), 'constructor', this).apply(this, arguments);

        this.state = {};
    }

    _createClass(Life, [{
        key: 'componentWillMount',

        //渲染前调用一次,这个时候DOM结构还没有渲染。fv
        value: function componentWillMount() {}

        //渲染完成后调用一次,这个时候DOM结构已经渲染了。这个时候就可以初始化其他框架的设置了,如果利用jQuery绑定事件等等。
    }, {
        key: 'componentDidMount',
        value: function componentDidMount() {}

        //初始化渲染不会调用,在接收到新的props时,会调用这个方法。
    }, {
        key: 'componentWillReceiveProps',
        value: function componentWillReceiveProps() {}

        //初始化渲染不会调用,接收到新的props或state时调用。
    }, {
        key: 'shouldComponentUpdate',
        value: function shouldComponentUpdate() {}

        //初始化渲染不会调用,更新前调用。
    }, {
        key: 'componentWillUpdate',
        value: function componentWillUpdate() {}

        //初始化渲染不会调用,更新后调用。
    }, {
        key: 'componentDidUpdate',
        value: function componentDidUpdate() {}

        //组件移除前调用。
    }, {
        key: 'componentWillUnmount',
        value: function componentWillUnmount() {}

        //对于被初始化挂载到 CSSTransitionGroup 的组件,它和 componentDidMount() 在相同时间被调用 。它将会阻塞其它动画发生,直到callback被调用。它只会在CSS TransitionGroup 初始化渲染时被调用。
    }, {
        key: 'componentWillAppear',
        value: function componentWillAppear(callback) {
            setTimeout(callback, 0);
        }

        //在传给componentWillAppear的回调函数被调用后调用。
    }, {
        key: 'componentDidAppear',
        value: function componentDidAppear() {}

        //对于被添加到已存在的 CSSTransitionGroup 的组件,它和 componentDidUpdate() 在相同时间被调用 。它将会阻塞其它动画发生,直到callback被调用。它不会在 CSSTransitionGroup 初始化渲染时被调用。
    }, {
        key: 'componentWillEnter',
        value: function componentWillEnter(callback) {
            setTimeout(callback, 0);
        }

        //在传给 componentWillEnter 的回调函数被调用之后调用。
    }, {
        key: 'componentDidEnter',
        value: function componentDidEnter() {}

        //在子级从 ReactCSSTransitionGroup 中移除时调用。虽然子级被移除了,ReactTransitionGroup 将会保持它在DOM中,直到callback被调用。
    }, {
        key: 'componentWillLeave',
        value: function componentWillLeave(callback) {}

        //在willLeave callback 被调用的时候调用(与 componentWillUnmount 同一时间)。
    }, {
        key: 'componentDidLeave',
        value: function componentDidLeave() {}

        //组件接收到新的props时会调用,一般在组件嵌套中比较常见,单一组件state变化是不会执行这个函数的
    }, {
        key: 'render',
        value: function render() {
            return _react2['default'].createElement(
                'div',
                null,
                '生命周期'
            );
        }
    }], [{
        key: 'propTypes',
        value: {},
        enumerable: true
    }, {
        key: 'defaultProps',
        value: {},
        enumerable: true
    }]);

    return Life;
})(_react.Component);

exports['default'] = Life;
module.exports = exports['default'];


text:
namespace safe_browsing {
class SafeBrowsingUrlCheckerImpl;
}

// A tab helper that uses Safe Browsing to check whether URLs that are being
// navigated to are unsafe.
class SafeBrowsingTabHelper
    : public web::WebStateUserData<SafeBrowsingTabHelper> {
 public:
  ~SafeBrowsingTabHelper() override;

  SafeBrowsingTabHelper(const SafeBrowsingTabHelper&) = delete;
  SafeBrowsingTabHelper& operator=(const SafeBrowsingTabHelper&) = delete;

 private:
  friend class web::WebStateUserData<SafeBrowsingTabHelper>;

  // Queries the Safe Browsing database using SafeBrowsingUrlCheckerImpls but
  // doesn't do anything with the result yet. This class may be constructed on
  // the UI thread but otherwise must only be used and destroyed on the IO
  // thread.
  class UrlCheckerClient : public base::SupportsWeakPtr<UrlCheckerClient> {
   public:
    UrlCheckerClient();
    ~UrlCheckerClient();

    UrlCheckerClient(const UrlCheckerClient&) = delete;
    UrlCheckerClient& operator=(const UrlCheckerClient&) = delete;

    // Queries the database using the given |url_checker|, for a request with
    // the given |url| and the given HTTP |method|. After receiving a result
    // from the database, runs the given |callback| on the UI thread with the
    // result.
    void CheckUrl(
        std::unique_ptr<safe_browsing::SafeBrowsingUrlCheckerImpl> url_checker,
        const GURL& url,
        const std::string& method,
        base::OnceCallback<void(web::WebStatePolicyDecider::PolicyDecision)>
            callback);

   private:
    // Called by |url_checker| with the initial result of performing a url
    // check. |url_checker| must be non-null. This is an implementation of
    // SafeBrowsingUrlCheckerImpl::NativeUrlCheckCallBack. |slow_check_notifier|
    // is an out-parameter; when a non-null value is passed in, it is set to a
    // callback that receives the final result of the url check.
    void OnCheckUrlResult(
        safe_browsing::SafeBrowsingUrlCheckerImpl* url_checker,
        safe_browsing::SafeBrowsingUrlCheckerImpl::NativeUrlCheckNotifier*
            slow_check_notifier,
        bool proceed,
        bool showed_interstitial);

    // Called by |url_checker| with the final result of performing a url check.
    // |url_checker| must be non-null. This is an implementation of
    // SafeBrowsingUrlCheckerImpl::NativeUrlCheckNotifier.
    void OnCheckComplete(safe_browsing::SafeBrowsingUrlCheckerImpl* url_checker,
                         bool proceed,
                         bool showed_interstitial);

    // This maps SafeBrowsingUrlCheckerImpls that have started but not completed
    // a url check to the callback that should be invoked once the url check is
    // complete.
    base::flat_map<
        std::unique_ptr<safe_browsing::SafeBrowsingUrlCheckerImpl>,
        base::OnceCallback<void(web::WebStatePolicyDecider::PolicyDecision)>,
        base::UniquePtrComparator>
        active_url_checkers_;
  };

  // A WebStatePolicyDecider that queries the SafeBrowsing database on each
  // request, always allows the request, but uses the result of the
  // SafeBrowsing check to determine whether to allow the corresponding
  // response.
  class PolicyDecider : public web::WebStatePolicyDecider,
                        public base::SupportsWeakPtr<PolicyDecider> {
   public:
    PolicyDecider(web::WebState* web_state,
                  UrlCheckerClient* url_checker_client);

    ~PolicyDecider() override;

    // Notifies the policy decider that a new main frame document has been
    // loaded.
    void UpdateForMainFrameDocumentChange();

   private:
    // Represents a single Safe Browsing query URL, along with the corresponding
    // decision once it's received, and the callback to invoke once the decision
    // is known.
    struct MainFrameUrlQuery {
      explicit MainFrameUrlQuery(const GURL& url);
      MainFrameUrlQuery(MainFrameUrlQuery&& query);
      MainFrameUrlQuery& operator=(MainFrameUrlQuery&& other);
      ~MainFrameUrlQuery();

      GURL url;
      base::Optional<web::WebStatePolicyDecider::PolicyDecision> decision;
      web::WebStatePolicyDecider::PolicyDecisionCallback response_callback;
    };

    // Represents the policy decision for a URL loaded in a sub frame.
    // ShouldAllowRequest() is not executed for consecutive loads of the same
    // URL, so it's possible for multiple sub frames to load the same URL and
    // share the policy decision generated from a single ShouldAllowRequest()
    // call.  If multiple ShouldAllowResponse() calls are received before the
    // url check has finished, they are added to |response_callbacks|.
    struct SubFrameUrlQuery {
      SubFrameUrlQuery();
      SubFrameUrlQuery(SubFrameUrlQuery&& decision);
      ~SubFrameUrlQuery();

      base::Optional<web::WebStatePolicyDecider::PolicyDecision> decision;
      std::list<web::WebStatePolicyDecider::PolicyDecisionCallback>
          response_callbacks;
    };

    // web::WebStatePolicyDecider implementation
    web::WebStatePolicyDecider::PolicyDecision ShouldAllowRequest(
        NSURLRequest* request,
        const web::WebStatePolicyDecider::RequestInfo& request_info) override;
    void ShouldAllowResponse(
        NSURLResponse* response,
        bool for_main_frame,
        web::WebStatePolicyDecider::PolicyDecisionCallback callback) override;

    // Implementations of ShouldAllowResponse() for main frame and sub frame
    // navigations.
    void HandleMainFrameResponsePolicy(
        const GURL& url,
        web::WebStatePolicyDecider::PolicyDecisionCallback callback);
    void HandleSubFrameResponsePolicy(
        const GURL& url,
        web::WebStatePolicyDecider::PolicyDecisionCallback callback);

    // Returns the appropriate UrlCheck callback for |request_info|.
    web::WebStatePolicyDecider::PolicyDecisionCallback GetUrlCheckCallback(
        const GURL& url,
        const web::WebStatePolicyDecider::RequestInfo& request_info);

    // Callback invoked when a main frame query for |url| has finished with
    // |decision|.
    void OnMainFrameUrlQueryDecided(
        const GURL& url,
        web::WebStatePolicyDecider::PolicyDecision decision);

    // Callback invoked when a sub frame url query for the NavigationItem with
    // |navigation_item_id| has finished with |decision|.
    void OnSubFrameUrlQueryDecided(
        const GURL& url,
        int navigation_item_id,
        web::WebStatePolicyDecider::PolicyDecision decision);

    // The URL checker client used to check navigation safety on the IO thread.
    UrlCheckerClient* url_checker_client_;
    // The pending query for the main frame navigation, if any.
    base::Optional<MainFrameUrlQuery> pending_main_frame_query_;
    // A map associating the pending policy decisions for each URL loaded into a
    // sub frame.
    std::map<const GURL, SubFrameUrlQuery> pending_sub_frame_queries_;
  };

  // Helper object that resets state for the policy decider when a navigation is
  // finished.
  class NavigationObserver : public web::WebStateObserver {
   public:
    NavigationObserver(web::WebState* web_state, PolicyDecider* policy_decider);
    ~NavigationObserver() override;

   private:
    // web::WebStateObserver:
    void DidFinishNavigation(
        web::WebState* web_state,
        web::NavigationContext* navigation_context) override;
    void WebStateDestroyed(web::WebState* web_state) override;

    PolicyDecider* policy_decider_ = nullptr;
    ScopedObserver<web::WebState, web::WebStateObserver> scoped_observer_{this};
  };

  explicit SafeBrowsingTabHelper(web::WebState* web_state);

  std::unique_ptr<UrlCheckerClient> url_checker_client_;
  PolicyDecider policy_decider_;
  NavigationObserver navigation_observer_;

  WEB_STATE_USER_DATA_KEY_DECL();
};

#endif  // IOS_CHROME_BROWSER_SAFE_BROWSING_SAFE_BROWSING_TAB_HELPER_H_


text:
mqtt_clients_demo
=================

MQTT clients in different programming languages.

See https://github.com/nivertech/mqtt_tools repo for vagrant box with MQTT development environment.


text:
START_ATF_NAMESPACE
    typedef _SETJMP_FLOAT128 SETJMP_FLOAT128;
END_ATF_NAMESPACE


text:
<?xml version="1.0" encoding="UTF-8"?>
<DARoots Version="1" Minor="26">
  <FileSet Name="constrs_1" Type="Constrs" RelSrcDir="$PSRCDIR/constrs_1">
    <Filter Type="Constrs"/>
    <File Path="$PPRDIR/../project_main.ucf">
      <FileInfo>
        <Attr Name="UsedInSynthesis" Val="1"/>
        <Attr Name="UsedInImplementation" Val="1"/>
      </FileInfo>
    </File>
    <Config>
      <Option Name="TargetConstrsFile" Val="$PPRDIR/../project_main.ucf"/>
      <Option Name="ConstrsType" Val="UCF"/>
    </Config>
  </FileSet>
</DARoots>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jenkins.plugins.pivot.section;

import hudson.DescriptorExtensionList;
import hudson.ExtensionPoint;
import hudson.model.Describable;
import hudson.model.Descriptor;
import jenkins.model.Jenkins;
import jenkins.plugins.pivot.Measure;

/**
 *
 * @author zijiang
 */
public abstract class PivotMeasureDefinition implements Describable<PivotMeasureDefinition>, ExtensionPoint{

    public abstract Measure getMeasure();

    @Override
    public Descriptor<PivotMeasureDefinition> getDescriptor() {
        return Jenkins.getInstance().getDescriptorOrDie(getClass());
    }

    public static DescriptorExtensionList<PivotMeasureDefinition, Descriptor<PivotMeasureDefinition>> all(){
        return Jenkins.getInstance().<PivotMeasureDefinition, Descriptor<PivotMeasureDefinition>>getDescriptorList(PivotMeasureDefinition.class);
    }

    public static abstract class PivotMeasureDefinitionDescriptor extends Descriptor<PivotMeasureDefinition> {
    }

}


text:
// ==========================================================================
// createClass
// ==========================================================================

/**
 * Create a class.
 * @param {string} name The string name of the class.
 * @param {function} superClass The superclass to inherit from. It will be
 *                          available as $super in the this instance, for
 *                          calls on the super class.
 * @param {Array<function>} mixins mixins definitions.
 * @param {Object} instanceProperties Instance properties that should be
 *          created. Properties that are prefixed with _ denode private
 *          properties, and creation of the class will fail if another
 *          property with the same name exists in the parent prototype.
 *          Properties prefixed with $ are protected properties.
 *          Shadowing is allowed only for public and protected members.
 *          The constructor() will be called if present with the arguments
 *          from the function itself.
 * @param {Object} staticProperties Static properties that will be defined
 *          on the returned class itself.
 * @type {Function}
 */
function createClass() {
    var args,
        result,
        classDefinition,
        newPrototype;

    args = Array.prototype.slice.apply(arguments);
    classDefinition = parseClassDefinition(args);

    var className = classDefinition.name ? classDefinition.name : "__anonymous__";
    result = new Function("return function " + className + "() {\n" +
            "   if (this.constructor) {\n" +
            "       this.constructor.apply(this,arguments); \n" +
            "   }\n" +
            "}")();

    result.prototype = objectCreate(classDefinition.superClass.prototype);
    newPrototype = result.prototype;
    newPrototype._super = classDefinition.superClass.prototype;
    newPrototype.__name = classDefinition.name;

    for (var i = 0; i < classDefinition.mixins.length; i++) {
        joinPrototype(classDefinition.mixins[i].prototype, newPrototype, /* mixin: */ true);
    }

    joinPrototype(classDefinition.instanceProperties, newPrototype);
    joinPrototype(classDefinition.staticProperties, result);

    return result;
}

/**
 * joinPrototype - Mixes the target prototype with the items from the
 *                 sourceObject.
 * @param {object} sourceObject
 * @param {object} targetPrototype
 * @param {boolean?} mixin Is the source from a mixin.
 * @return {void}
 */
function joinPrototype(sourceObject, targetPrototype, mixin) {
    for (var k in sourceObject) {
        if (mixin && (k == '_super' || k == '__name')) {
            continue; // ignore _super, __name from mixins.
        }

        if (/^_/.test(k) && (typeof targetPrototype[k] !== "undefined")) {
            throw new Error('Private member ' + k + ' is already defined.');
        }

        if (mixin && /^\$/.test(k) && (typeof targetPrototype[k] !== "undefined")) {
            throw new Error('Protected member ' + k + ' can not be overwritten by mixins.');
        }

        targetPrototype[k] = sourceObject[k];
    }
}

/**
 * Creates an object using Object.create, or defaults to a shim
 * implementation if it's not supported by the browser.
 */
var objectCreate = Object.create ? Object.create : function(proto) {
    function F(){}
    F.prototype = proto;

    return new F();
};


text:
var blueprints = [];

global.testdefine =  function (id, deps) {
  blueprints.push({ id: id, deps: deps });
};

require("../include/include.js");

var Evaller = demand('bolt.loader.executor.Evaller');

Evaller.execute(
  "true",
  function () { assert(true, "successful eval"); },
  function (error) { assert(false, "successful eval: " + error); }
);

Evaller.execute(
  "mth is wrong",
  function () { assert(false, "failed eval"); },
  function () { assert(true, "failed eval"); }
);

Evaller.execute(
  "testdefine('mth', ['marli'], function () {});",
  function () { assert(blueprints.length === 1 && blueprints[0].id === "mth", "define is called"); },
  function (error) { assert(false, "define is called: " + error); }
);


text:
package flare

import (
	"context"
	"fmt"

	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/log/level"
	"github.com/pkg/errors"

	"github.com/diegobernardes/flare/infra/config"
	"github.com/diegobernardes/flare/provider/aws"
	sqsQueue "github.com/diegobernardes/flare/provider/aws/queue"
	memoryQueue "github.com/diegobernardes/flare/provider/memory/queue"
)

type queuer interface {
	Push(context.Context, []byte) error
	Pull(context.Context, func(context.Context, []byte) error) error
}

type queue struct {
	cfg        *config.Client
	awsSession *aws.Session
	logger     log.Logger
}

func (q *queue) init() error {
	provider := q.cfg.GetString("provider.queue")
	switch provider {
	case providerMemory:
	case providerAWSSQS:
		var err error
		q.awsSession, err = aws.NewSession(
			aws.SessionKey(q.cfg.GetString("provider.aws.key")),
			aws.SessionRegion(q.cfg.GetString("provider.aws.region")),
			aws.SessionSecret(q.cfg.GetString("provider.aws.secret")),
		)
		if err != nil {
			return errors.Wrap(err, "error during AWS session initialization")
		}
	default:
		return fmt.Errorf("invalid provider.queue '%s' config", provider)
	}

	return nil
}

func (q *queue) fetch(name string) (queuer, error) {
	switch q.cfg.GetString("provider.queue") {
	case providerMemory:
		return memoryQueue.NewClient(), nil
	case providerAWSSQS:
		return q.providerAWSSQS(name)
	}
	return nil, nil
}

func (q *queue) providerAWSSQS(name string) (queuer, error) {
	queue, err := sqsQueue.NewSQS(
		sqsQueue.SQSQueueName(q.cfg.GetString(fmt.Sprintf("provider.aws.sqs.queue.%s.queue", name))),
		sqsQueue.SQSSession(q.awsSession),
	)
	if err != nil {
		return nil, err
	}

	return queue, nil
}

func (q *queue) setup(ctx context.Context) error {
	switch q.cfg.GetString("provider.queue") {
	case providerMemory:
	case providerAWSSQS:
		return q.setupAWSSQS(ctx)
	}

	return nil
}

func (q *queue) setupAWSSQS(ctx context.Context) error {
	names := []string{
		"subscription.partition", "subscription.spread", "subscription.delivery", "generic",
	}

	logger := level.Info(q.logger)
	for _, name := range names {
		qn := q.cfg.GetString(fmt.Sprintf("provider.aws.sqs.queue.%s.queue", name))

		logger.Log("message", fmt.Sprintf("creating SQS queue for worker '%s' with name '%s'", name, qn))

		err := sqsQueue.SQSSetup(
			ctx,
			sqsQueue.SQSQueueName(qn),
			sqsQueue.SQSSession(q.awsSession),
		)
		if err != nil {
			return err
		}
	}

	return nil
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>at.srfg.test</groupId>
  <artifactId>gitflowv2</artifactId>
  <version>2.0.1</version>
  <packaging>jar</packaging>

  <name>gitflowv2</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>versions-maven-plugin</artifactId>
        <version>2.5</version>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <scm>
    <connection>scm:git:https://github.com/emplexed/gitflowv2.git</connection>
    <url>scm:git:https://github.com/emplexed/gitflowv2.git</url>
    <developerConnection>scm:git:https://github.com/emplexed/gitflowv2.git</developerConnection>
  </scm>
</project>